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>conclave0/PhanQuyenNguoiDungATBM<file_sep>/ControlUserPrivacy.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace ATBMN28_Login { public partial class ControlUserPrivacy : Form { ConnectDB dbs; public ControlUserPrivacy(string username, string password) { InitializeComponent(); Syntax_Cbb.Items.Add("GRANT"); Syntax_Cbb.Items.Add("REVOKE"); Type_Cbb.Items.Add("ALL"); Type_Cbb.Items.Add("INSERT"); Type_Cbb.Items.Add("SELECT"); Type_Cbb.Items.Add("UPDATE"); Type_Cbb.Items.Add("DELETE"); Type_Cbb.Items.Add("EXECUTE"); Syntax_Cbb.SelectedIndex = 0; Type_Cbb.SelectedIndex = 0; dbs = new ConnectDB(username, password); } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void label3_Click(object sender, EventArgs e) { } private void comboBox3_SelectedIndexChanged(object sender, EventArgs e) { } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { } private void ControlUserPrivacy_Load(object sender, EventArgs e) { DataTable dt = dbs.viewAllUserPrivilege(); dataGridView1.DataSource = dt; } private void radioButton2_CheckedChanged(object sender, EventArgs e) { } private void radioButton1_CheckedChanged(object sender, EventArgs e) { } private void radioButton1_MouseClick(object sender, MouseEventArgs e) { User_Cbb.DataSource = null; DataTable dt = dbs.viewAllUser(); User_Cbb.ValueMember = "USERNAME"; User_Cbb.DisplayMember = "USERNAME"; User_Cbb.DataSource = dt; User_Cbb.SelectedIndex = 0; } private void radioButton2_MouseClick(object sender, MouseEventArgs e) { User_Cbb.DataSource = null; DataTable dt = dbs.viewAllRole(); User_Cbb.ValueMember = "GRANTED_ROLE"; User_Cbb.DisplayMember = "GRANTED_ROLE"; User_Cbb.DataSource = dt; User_Cbb.SelectedIndex = 0; } private void User_Cbb_SelectedIndexChanged(object sender, EventArgs e) { try { DataTable dt = dbs.viewRolePrivilege(User_Cbb.SelectedValue.ToString().Trim()); if (dt.Rows.Count != 0) { TS_Cbb.ValueMember = "TABLE_NAME"; TS_Cbb.DisplayMember = "TABLE_NAME"; TS_Cbb.DataSource = dt; TS_Cbb.SelectedIndex = 0; } } catch (Exception ex) { TS_Cbb.DataSource = null; } } private void Execute_Btn_Click(object sender, EventArgs e) { string cmd; string syntax = Syntax_Cbb.SelectedItem.ToString().Trim(); string user = User_Cbb.Text.ToString().Trim(); string type = Type_Cbb.SelectedItem.ToString().Trim(); string table = TS_Cbb.Text.ToString().Trim(); int temp; bool isNumeric = int.TryParse(user, out temp); if (syntax.Equals("GRANT")) { if (!type.Equals("EXECUTE")) { if (isNumeric) { cmd = syntax + " " + type + " on ATBMN28." + table + " to \"" + user + "\""; } else { cmd = syntax + " " + type + " on ATBMN28." + table + " to " + user; } } else { if (isNumeric) { cmd = syntax + " " + type + " on " + table + " to \"" + user + "\""; } else { cmd = syntax + " " + type + " on " + table + " to " + user; } } } else { if (!type.Equals("EXECUTE")) { if (isNumeric) { cmd = syntax + " " + type + " on ATBMN28." + table + " from \"" + user + "\""; } else { cmd = syntax + " " + type + " on ATBMN28." + table + " from " + user; } } else { if (isNumeric) { cmd = syntax + " " + type + " on " + table + " from \"" + user + "\""; } else { cmd = syntax + " " + type + " on " + table + " from " + user; } } } try { dbs.executeGrantRevokePrivilege(cmd); MessageBox.Show("Successful!"); ControlUserPrivacy_Load(this, e); } catch (Exception ex) { MessageBox.Show(ex.Message); } DataTable dt = dbs.viewAllUserPrivilege(); dataGridView1.DataSource = dt; } } } <file_sep>/AuditViewer.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace ATBMN28_Login { public partial class AuditViewer : Form { ConnectDB dbs; string username, password; public AuditViewer(string Username, string Password) { InitializeComponent(); username = Username; password = <PASSWORD>; dbs = new ConnectDB(username, password); } private void LuongDGV_DataError(object sender, DataGridViewDataErrorEventArgs e) { e.Cancel = true; } private void AuditViewer_Load(object sender, EventArgs e) { label1.Text = username; DataTable dt1 = new DataTable(); DataTable dt2 = new DataTable(); dt1 = dbs.auditThongBao(); dt2 = dbs.auditLuong(); ThongBaoDGV.DataSource = dt1; LuongDGV.DataSource = dt2; } } } <file_sep>/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.OleDb; using Oracle.ManagedDataAccess.Client; using Oracle.ManagedDataAccess.Types; namespace ATBMN28_Login { public partial class Form1 : Form { private OracleConnection _connection; //OleDbConnection _connection = null; String _connectionString = ""; string USN = null; string PW = null; ConnectDB dbs; public Form1() { InitializeComponent(); //_connection = new OleDbConnection(_connectionString); } private void button1_Click(object sender, EventArgs e) { USN = textBox1.Text.ToString().Trim(); PW = textBox2.Text.ToString().Trim(); dbs = new ConnectDB(USN, PW); if (dbs.GetConnected()) { MessageBox.Show("Đăng nhập thành công!"); if (dbs.isAdmin(USN)) { Form form2 = new Form2(USN, PW); form2.Show(); } else { if (USN.Equals("ATBMN28OLS")) { Form frm4 = new OLSAdminManager(USN, PW); frm4.Show(); } else { Form form3 = new Form3(USN, PW); form3.Show(); } } } else { USN = null; PW = null; MessageBox.Show("Đăng nhập thất bại"); } //_connectionString = "Provider=MSDAORA;Data Source=JSTComDevice:1521/ORCLPDB;User ID=" + textBox1.Text+";Password="+<PASSWORD>; // _connection = new OleDbConnection(_connectionString); /*if (dbs.GetConnected()) { Form2 form2 = new Form2(USN, PW); form2.Show(); Form3 form3 = new Form3(USN, PW); form3.Show(); /*Form frm4 = new OLSAdminManager(USN, PW); frm4.Show(); } else { }*/ } } } <file_sep>/ControlUserRole.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace ATBMN28_Login { public partial class ControlUserRole : Form { ConnectDB dbs; public ControlUserRole(string username, string password) { InitializeComponent(); Syntax_Cbb.Items.Add("GRANT"); Syntax_Cbb.Items.Add("REVOKE"); dbs = new ConnectDB(username, password); Syntax_Cbb.SelectedIndex = 0; } private void ControlUserRole_Load(object sender, EventArgs e) { DataTable dt = dbs.viewAllUserRole(); dataGridView1.DataSource = dt; DataTable role = dbs.viewAllRole(); Role_Cbb.ValueMember = "GRANTED_ROLE"; Role_Cbb.DisplayMember = "GRANTED_ROLE"; Role_Cbb.DataSource = role; DataTable user = dbs.viewAllUser(); User_Cbb.ValueMember = "USERNAME"; User_Cbb.DisplayMember = "USERNAME"; User_Cbb.DataSource = user; } private void Execute_Btn_Click(object sender, EventArgs e) { string cmd; string syntax = Syntax_Cbb.SelectedItem.ToString().Trim(); string user = User_Cbb.Text.ToString().Trim(); string role = Role_Cbb.SelectedValue.ToString().Trim(); int temp; bool isNumeric = int.TryParse(user, out temp); if (syntax.Equals("GRANT")) { if (isNumeric) { cmd = syntax + " " + role + " to \"" + user + "\""; } else { cmd = syntax + " " + role + " to " + user + " "; } } else { if (isNumeric) { cmd = syntax + " " + role + " from \"" + user + "\""; } else { cmd = syntax + " " + role + " from " + user + " "; } } try { dbs.executeGrantRevokePrivilege(cmd); MessageBox.Show("Successful!"); } catch (Exception ex) { MessageBox.Show(ex.Message); } DataTable dt = dbs.viewAllUserRole(); dataGridView1.DataSource = dt; } } } <file_sep>/OLSAdminManager.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace ATBMN28_Login { public partial class OLSAdminManager : Form { ConnectDB dbs; string username, password; public OLSAdminManager(string US, string PW) { InitializeComponent(); dbs = new ConnectDB(US, PW); Level_Cbb.Items.Insert(0, "BT:TT:CB"); Level_Cbb.Items.Insert(1, "QT:TT:CB"); Level_Cbb.Items.Insert(2, "BT:BM:CB"); Level_Cbb.Items.Insert(3, "QT:BM:CB"); Level_Cbb.Items.Insert(4, "BT:K:CB"); Level_Cbb.Items.Insert(5, "QT:K:CB"); Level_Cbb.Items.Insert(6, "BT:TT:GV"); Level_Cbb.Items.Insert(7, "QT:TT:GV"); Level_Cbb.Items.Insert(8, "BT:BM:GV"); Level_Cbb.Items.Insert(9, "QT:BM:GV"); Level_Cbb.Items.Insert(10, "BT:K:GV"); Level_Cbb.Items.Insert(11, "QT:K:GV"); Level_Cbb.Items.Insert(12, "BT:TT:SV"); Level_Cbb.Items.Insert(13, "QT:TT:SV"); Level_Cbb.Items.Insert(14, "BT:BM:SV"); Level_Cbb.Items.Insert(15, "QT:BM:SV"); Level_Cbb.Items.Insert(16, "BT:K:SV"); Level_Cbb.Items.Insert(17, "QT:K:SV"); Level_Cbb.SelectedIndex = 0; username = US; password = PW; } private void OLSAdminManager_Load(object sender, EventArgs e) { DataTable dt = dbs.viewThongBao(); dataGridView1.DataSource = dt; ID_Cbb.ValueMember = "ID"; ID_Cbb.DisplayMember = "ID"; ID_Cbb.DataSource = dt; //ID_Cbb.SelectedIndex = 0; label2.Text = username; } private void Execute_Btn_Click(object sender, EventArgs e) { int id = int.Parse(ID_Cbb.SelectedValue.ToString().Trim()); string policy = Level_Cbb.SelectedItem.ToString().Trim(); bool status = dbs.executeStoreSetThongBaoPolicy(id, policy); if (status) { MessageBox.Show("Changed Successfuly!"); } DataTable dt = dbs.viewThongBao(); dataGridView1.DataSource = dt; ID_Cbb.ValueMember = "ID"; ID_Cbb.DisplayMember = "ID"; ID_Cbb.DataSource = dt; ID_Cbb.SelectedIndex = 0; } } } <file_sep>/Form4.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.OleDb; using Oracle.ManagedDataAccess.Client; using Oracle.ManagedDataAccess.Types; namespace ATBMN28_Login { public partial class Form4 : Form { OracleConnection _connection = null; String _connectionString = ""; string username, password; public Form4(string Username, string Password) { InitializeComponent(); _connectionString = "DATA SOURCE=JSTComDevice:1521/ORCLPDB;USER ID=" + Username + "; Password =" + <PASSWORD>; _connection = new OracleConnection(_connectionString); username = Username; password = <PASSWORD>; } private void button1_Click(object sender, EventArgs e) { _connection.Open(); try { string cmstring = "select * from ATBMN28.monhoc_mo where monhoc_mo.nam='" + textBox1.Text + "' and monhoc_mo.hocky='" + textBox2.Text + "'"; OracleCommand cm = new OracleCommand(cmstring, _connection); OracleDataReader reader; reader = cm.ExecuteReader(); DataTable table = new DataTable(); table.Load(reader); dataGridView1.DataSource = table; } catch (Exception ex) { MessageBox.Show(ex.Message); } _connection.Close(); } private void Form4_Load(object sender, EventArgs e) { label3.Text = username; } } } <file_sep>/Form2.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.OleDb; using Oracle.ManagedDataAccess.Client; using Oracle.ManagedDataAccess.Types; namespace ATBMN28_Login { public partial class Form2 : Form { //OleDbConnection _connection = null; OracleConnection _connection = null; String _connectionString = ""; ConnectDB dbs; string US; string PW; public Form2(string Username,string Password) { InitializeComponent(); this.US = Username; this.PW = <PASSWORD>; //_connectionString = "Provider=MSDAORA;Data Source=localhost/orcl;User ID=" + Username + ";Password=" + <PASSWORD>; _connectionString = "DATA SOURCE=JSTComDevice:1521/ORCLPDB;USER ID=" + US + "; Password =" + PW; //_connection = new OleDbConnection(_connectionString); _connection = new OracleConnection(_connectionString); dbs = new ConnectDB(US,PW); comboBox1.SelectedIndex = 0; } private void button1_Click(object sender, EventArgs e) { //user role table views string cmstring=""; if (comboBox1.SelectedIndex == 0) cmstring = "select * from all_users"; if (comboBox1.SelectedIndex == 1) cmstring = "SELECT * FROM DBA_ROLES"; if (comboBox1.SelectedIndex == 2) cmstring = "SELECT * FROM all_tables"; if (comboBox1.SelectedIndex == 3) cmstring = "select view_name from all_views"; _connection.Open(); OracleCommand cm = new OracleCommand(cmstring, _connection); OracleDataReader reader; reader= cm.ExecuteReader(); DataTable table =new DataTable(); table.Load(reader); dataGridView1.DataSource=table; _connection.Close(); } private void button2_Click(object sender, EventArgs e) { //user role table views _connection.Open(); try { string cmstring = ""; if (comboBox1.SelectedIndex == 0) cmstring = "CREATE USER " + textBox1.Text + " IDENTIFIED BY " + textBox2.Text; if (comboBox1.SelectedIndex == 1) cmstring = "create role " + textBox1.Text; if (comboBox1.SelectedIndex == 2) cmstring = "create table " + textBox1.Text; if (comboBox1.SelectedIndex == 3) cmstring = "create view " + textBox1.Text; //OleDbCommand cm = new OleDbCommand(cmstring, _connection); OracleCommand cm = new OracleCommand(cmstring, _connection); cm.ExecuteNonQuery(); MessageBox.Show("Successful!"); } catch (Exception ex) { MessageBox.Show(ex.Message); } _connection.Close(); } private void Form2_Load(object sender, EventArgs e) { label3.Text = US; } private void controlUserPrivacyToolStripMenuItem_Click(object sender, EventArgs e) { Form frm = new ControlUserPrivacy(US, PW); frm.Show(); } private void viewUserToolStripMenuItem_Click(object sender, EventArgs e) { Form frm = new ControlUserRole(US, PW); frm.Show(); } private void auditViewerToolStripMenuItem_Click(object sender, EventArgs e) { Form frm = new AuditViewer(US, PW); frm.Show(); } } } <file_sep>/README.md # PhanQuyenNguoiDungATBM Ứng dụng phân quyền người dùng. Giao diện tự nhận diện loại người dùng. Form1 chứa form đăng nhập Form2 chứa form cho admin ATBMN28 OLSAdminManager chứa form cho admin ATBMN28OLS Form3 và Form4 chứa form cho user ControlUserRole, ControlUserPrivacy, AuditViewer chứa form cho admin điều khiển quyền của người dùng. <file_sep>/ConnectDB.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.OleDb; using Oracle.ManagedDataAccess.Client; using Oracle.ManagedDataAccess.Types; namespace ATBMN28_Login { class ConnectDB { private string connectString; private OracleConnection connection; public string StringCon { get { return connectString; } set { connectString = value; } } public ConnectDB(string us, string pw) { connectString = "DATA SOURCE=JSTComDevice:1521/ORCLPDB;USER ID=" + us + "; Password =" + pw; connection = new OracleConnection(); connection.ConnectionString = connectString; } public ConnectDB() { connectString = "DATA SOURCE=JSTComDevice:1521/ORCLPDB;USER ID=ATBMN28; Password =<PASSWORD>"; connection = new OracleConnection(); connection.ConnectionString = connectString; } public bool GetConnected() { bool status; try { connection.Open(); status = true; connection.Close(); } catch (Exception e) { status = false; } return status; } public bool isAdmin(string user) { bool value = false; try { DataTable dt = new DataTable(); using (OracleCommand cmd = new OracleCommand("select * from all_objects where owner ='"+user+"'", this.connection)) { connection.Open(); using (OracleDataReader reader = cmd.ExecuteReader()) { dt.Load(reader); if (dt.Rows.Count != 0) value = true; } connection.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } return value; } public DataTable getDiemSV(string masv) { DataTable dt = new DataTable(); if (masv == "") { try { using (OracleCommand cmd = new OracleCommand("select * from ATBMN28.DANGKY", this.connection)) { connection.Open(); using (OracleDataReader reader = cmd.ExecuteReader()) { dt.Load(reader); } connection.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { try { string SQLcommand = "select * from ATBMN28.DANGKY where MASV ='" + masv + "'"; using (OracleCommand cmd = new OracleCommand(SQLcommand, this.connection)) { connection.Open(); using (OracleDataReader reader = cmd.ExecuteReader()) { dt.Load(reader); } connection.Close(); } } catch(Exception ex) { MessageBox.Show(ex.Message); } } return dt; } public DataTable viewThongBao() { DataTable dt = new DataTable(); using (OracleCommand cmd = new OracleCommand("select * from ATBMN28.THONGBAO order by ID", this.connection)) { connection.Open(); using (OracleDataReader reader = cmd.ExecuteReader()) { dt.Load(reader); } connection.Close(); } return dt; } public DataTable viewAllUserPrivilege() { DataTable dt = new DataTable(); string commandString = "select distinct utp.GRANTEE,utp.TABLE_NAME, utp.PRIVILEGE, utp.TYPE from User_tab_privs utp, all_users au where utp.GRANTEE = au.USERNAME or (au.username like '1%' or au.username like '%GV%') order by utp.GRANTEE"; using (OracleCommand cmd = new OracleCommand(commandString, this.connection)) { connection.Open(); using (OracleDataReader reader = cmd.ExecuteReader()) { dt.Load(reader); } connection.Close(); } return dt; } public DataTable viewAllUser() { DataTable dt = new DataTable(); string commandString = "select distinct al.USERNAME from all_users al where al.USERNAME like 'GV%' or al.USERNAME like '1%'"; using (OracleCommand cmd = new OracleCommand(commandString, this.connection)) { connection.Open(); using (OracleDataReader reader = cmd.ExecuteReader()) { dt.Load(reader); } connection.Close(); } return dt; } public DataTable viewAllRole() { DataTable dt = new DataTable(); string commandString = "select distinct Granted_Role from Dba_role_privs where grantee like '1%' or grantee like'GV%' or grantee like 'ATBM%' "; using (OracleCommand cmd = new OracleCommand(commandString, this.connection)) { connection.Open(); using (OracleDataReader reader = cmd.ExecuteReader()) { dt.Load(reader); } connection.Close(); } return dt; } public DataTable viewRolePrivilege(string role) { DataTable dt = new DataTable(); try { string commandString = "select distinct uts.TABLE_NAME, uts.Type from User_tab_privs uts where (uts.PRIVILEGE like 'INSERT' or uts.PRIVILEGE like 'UPDATE' or uts.PRIVILEGE like 'DELETE' or uts.PRIVILEGE like 'SELECT' or uts.PRIVILEGE like 'EXECUTE')" + " and uts.Grantee = '" + role + "' order by uts.TABLE_NAME "; using (OracleCommand cmd = new OracleCommand(commandString, this.connection)) { connection.Open(); using (OracleDataReader reader = cmd.ExecuteReader()) { dt.Load(reader); } connection.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } return dt; } public bool executeGrantRevokePrivilege(string commandString) { bool status = false; try { using (OracleCommand cmd = new OracleCommand(commandString, this.connection)) { connection.Open(); cmd.ExecuteNonQuery(); status = true; connection.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message); connection.Close(); } return status; } public DataTable viewAllUserRole() { DataTable dt = new DataTable(); string commandString = "select distinct Granted_Role, GRANTEE from Dba_role_privs where grantee like '1%' or grantee like'GV%' or grantee like 'ATBM%' order by GRANTED_ROLE "; using (OracleCommand cmd = new OracleCommand(commandString, this.connection)) { connection.Open(); using (OracleDataReader reader = cmd.ExecuteReader()) { dt.Load(reader); } connection.Close(); } return dt; } public bool executeStoreSetThongBaoPolicy(int id, string policy) { bool status = false; string commandString = "ATBMN28.SetThongBaoPolicy"; try { using (OracleCommand cmd = new OracleCommand(commandString, this.connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("ip_id", OracleDbType.Int32).Value = id; cmd.Parameters.Add("ip_id", OracleDbType.Varchar2).Value = policy; connection.Open(); OracleDataAdapter da = new OracleDataAdapter(cmd); cmd.ExecuteNonQuery(); connection.Close(); } status = true; } catch (Exception ex) { MessageBox.Show(ex.Message); } return status; } public bool executeStoreAddThongBao(int id, string thongbao, string chucvu) { bool status = false; string commandString = "ATBMN28.ThemThongBao"; using (OracleCommand cmd = new OracleCommand(commandString, this.connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("inp_ID", OracleDbType.Int32).Value = id; cmd.Parameters.Add("inp_THONGBAO", OracleDbType.Varchar2).Value = thongbao; cmd.Parameters.Add("inp_CHUCVU", OracleDbType.Varchar2).Value = chucvu; connection.Open(); OracleDataAdapter da = new OracleDataAdapter(cmd); cmd.ExecuteNonQuery(); connection.Close(); status = true; } MessageBox.Show("Thêm Thông Báo Thành Công"); return status; } public DataTable auditThongBao() { DataTable dt = new DataTable(); try { string commandString = "select * from ATBMN28.THONGBAO$AUDIT"; using (OracleCommand cmd = new OracleCommand(commandString, this.connection)) { connection.Open(); using (OracleDataReader reader = cmd.ExecuteReader()) { dt.Load(reader); } connection.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } return dt; } public DataTable auditLuong() { DataTable dt = new DataTable(); try { string commandString = "select Log_Type, User_Name, Log_DATE,MAGV, ATBMN28.decrypt_Luong(OLD_VALUE,'antoanbaomat') OLD_LUONG from ATBMN28.log_luong"; using (OracleCommand cmd = new OracleCommand(commandString, this.connection)) { connection.Open(); using (OracleDataReader reader = cmd.ExecuteReader()) { dt.Load(reader); } connection.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } return dt; } } } <file_sep>/Form3.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.OleDb; using Oracle.ManagedDataAccess.Client; using Oracle.ManagedDataAccess.Types; namespace ATBMN28_Login { public partial class Form3 : Form { private string username, password; //OleDbConnection _connection = null; OracleConnection _connection = null; String _connectionString = ""; public Form3(string Username,string Password) { InitializeComponent(); username = Username; password = <PASSWORD>; //_connectionString = "Provider=MSDAORA;Data Source=localhost/orcl;User ID=" + Username + ";Password=" + <PASSWORD>; // _connection = new OleDbConnection(_connectionString); _connectionString = "DATA SOURCE=JSTComDevice:1521/ORCLPDB;USER ID=" + username + "; Password =" + <PASSWORD>; _connection = new OracleConnection(_connectionString); } private void button1_Click(object sender, EventArgs e) { _connection.Open(); try { string cmstring="select * from ATBMN28.GIAOVIEN where GiaoVien.MaGV='" + textBox1.Text.ToUpper() + "'"; //OleDbCommand cm = new OleDbCommand(cmstring, _connection); OracleCommand cm = new OracleCommand(cmstring, _connection); OracleDataReader reader; reader = cm.ExecuteReader(); DataTable table = new DataTable(); table.Load(reader); dataGridView1.DataSource = table; } catch (Exception ex) { MessageBox.Show(ex.Message); } _connection.Close(); } private void button2_Click(object sender, EventArgs e) { _connection.Open(); try { string cmstring="select MaGV,THOIGIAN,NAM from atbmn28.monhoc_mo where monhoc_mo.MaGV='" + textBox1.Text.ToUpper() + "'"; /*OleDbCommand cm = new OleDbCommand(cmstring, _connection); OleDbDataReader reader;*/ OracleCommand cm = new OracleCommand(cmstring, _connection); OracleDataReader reader; reader = cm.ExecuteReader(); DataTable table = new DataTable(); table.Load(reader); dataGridView1.DataSource = table; } catch (Exception ex) { MessageBox.Show(ex.Message); } _connection.Close(); } private void button3_Click(object sender, EventArgs e) { _connection.Open(); try { string cmstring = "update ATBMN28.GIAOVIEN set " + textBox2.Text + " where GIAOVIEN.MAGV='" + textBox1.Text.ToUpper() + "'"; OracleCommand cm = new OracleCommand(cmstring, _connection); cm.ExecuteNonQuery(); MessageBox.Show("Successful!"); } catch (Exception ex) { MessageBox.Show(ex.Message); } _connection.Close(); } private void button4_Click(object sender, EventArgs e) { Form4 form4 = new Form4(username, password); form4.Show(); } private void button5_Click(object sender, EventArgs e) { _connection.Open(); try { string cmstring = "select MAGV, ATBMN28.decrypt_Luong(LUONG,'" + textBox3.Text + "')from ATBMN28.Luong"; OracleCommand cm = new OracleCommand(cmstring, _connection); OracleDataReader reader; reader = cm.ExecuteReader(); DataTable table = new DataTable(); table.Load(reader); dataGridView1.DataSource = table; } catch (Exception ex) { MessageBox.Show(ex.Message); } _connection.Close(); } private void button6_Click(object sender, EventArgs e) { _connection.Open(); try { string cmstring = "update ATBMN28.GIAOVIEN set " + textBox2.Text + " where GIAOVIEN.MAGV='" + textBox1.Text.ToUpper() + "'"; OracleCommand cm = new OracleCommand(cmstring, _connection); cm.ExecuteNonQuery(); MessageBox.Show("Successful!"); } catch (Exception ex) { MessageBox.Show(ex.Message); } _connection.Close(); } private void label5_Click(object sender, EventArgs e) { } private void MSSV_TextBox_TextChanged(object sender, EventArgs e) { } private void XemDiem_Btn_Click(object sender, EventArgs e) { ConnectDB dbs = new ConnectDB(username, password); DataTable dt = dbs.getDiemSV(MSSV_TextBox.Text.Trim()); dataGridView1.DataSource = dt; } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void ViewThongBao_Click(object sender, EventArgs e) { ConnectDB dbs = new ConnectDB(username, password); DataTable dt = dbs.viewThongBao(); dataGridView1.DataSource = dt; } private void Form3_Load(object sender, EventArgs e) { label7.Text = username; comboBox1.SelectedIndex = 0; } private void tabPage3_Click(object sender, EventArgs e) { } private void ThemThongBao_Click(object sender, EventArgs e) { ConnectDB dbs = new ConnectDB(username, password); dbs.executeStoreAddThongBao(int.Parse(textBox6.Text), textBox7.Text, comboBox1.SelectedItem.ToString().Trim()); DataTable dt = dbs.viewThongBao(); dataGridView1.DataSource = dt; } private void button6_Click_1(object sender, EventArgs e) { _connection.Open(); try { string cmstring = "update ATBMN28.Luong set Luong= ATBMN28.encrypt_Luong('" + textBox5.Text + "','" + textBox3.Text + "') where MaGv='" +textBox4.Text.ToUpper() +"'"; OracleCommand cm = new OracleCommand(cmstring, _connection); cm.ExecuteNonQuery(); MessageBox.Show("Successful!"); } catch (Exception ex) { MessageBox.Show(ex.Message); } _connection.Close(); } } }
ca3d5448d6993c4ffa8da9e8778c0a1dd82b35f0
[ "Markdown", "C#" ]
10
C#
conclave0/PhanQuyenNguoiDungATBM
fc387e7caf45175acbf1c22466c035cf604673dc
2720ddd545e50b69e8288d0365bc2ccb2b0da871
refs/heads/master
<file_sep># -*- mode: ruby -*- # vi: set ft=ruby : unless Vagrant.has_plugin?("vagrant-docker-compose") system("vagrant plugin install vagrant-docker-compose") puts "Dependencies installed, please try the command again." exit end Vagrant.configure("2") do |config| config.vm.box = "ubuntu/trusty64" config.vm.network "private_network", ip: "192.168.50.5" config.vm.network(:forwarded_port, guest: 27017, host: 27018) config.nfs.map_uid = Process.uid config.nfs.map_gid = Process.gid config.vm.synced_folder "./data", "/vagrant-mongo", type: 'nfs' config.bindfs.bind_folder "/vagrant-mongo", "/data/db", create_as_user: true, perms: "u=rwx:g=rwx:o=rwx", :'chown-ignore' => true, :'chgrp-ignore' => true, :'chmod-ignore' => true, after: :provision, o: 'nonempty' config.vm.provision :docker config.vm.provision :docker_compose, yml: "/vagrant/docker-compose.yml", rebuild: true, project_name: "myproject", run: "always" end
d497b2e5d9a2fd578d21701c53c4ea6734bf79f8
[ "Ruby" ]
1
Ruby
dbatishchev/vagrant-bindfs
c97d3ccac13187433671e0316b462b00e538f500
6cfef9bd74625099243b40de58751afc015a2e86
refs/heads/master
<file_sep>-- OCPM, a simple but functional package manager for OC Linux -- local args = {...} local urlResolvers = { -- 3-letter shortcuts for much longer URLs ["git:"] = { resolveTo = "https://raw.githubusercontent.com/" }, ["ozc:"] = { resolveTo = "https://oz-craft.pickardayune.com/" } } local pmDirs = { "/var/cache/ocpm/packages/", "/var/cache/ocpm/lists/", "/tmp/", "/etc/ocpm/" } local pkgDir = pmDirs[1] local listDir = pmDirs[2] local tmpDir = pmDirs[3] local listFile = pmDirs[4] .. "sources.list" -- package sources local function require(path) if not fs.exists(path) then print("E: Path " .. path .. " does not exist.") return nil end local handle = fs.open(path, "r") local file = handle.readAll() handle.close() local data = loadstring(file)() return data end local function get(sUrl) -- Ripped straight from wget.lua local ok, err = http.checkURL(sUrl) if not ok then print( "Failed: " .. (err or " no reason given") .. ".") return nil end local response = http.get(sUrl, nil, true) if not response then print("Failed.") return nil end local sResponse = response.readAll() response.close() return sResponse end local function writeTo(sData, sPath) local handle = fs.open(sPath, "w") handle.write(sData) handle.close() end local function resolveURL(url) print("Resolving URL...") local retURL = url local firstFour = retURL:sub(1,4) if urlResolvers[firstFour] then retURL = urlResolvers[firstFour].resolveTo .. retURL:sub(5) end if urlResolvers[firstFour].suffix then retURL = retURL .. urlResolvers[firstFour].suffix end return retURL end local function checkDirs() -- Check for required directories print("Checking for existence of package manager directories...") for i=1, #pmDirs, 1 do if not fs.exists(pmDirs[i]) then fs.makeDir(pmDirs[i]) end end end local function checkArc() print("Checking for existence of package manager required archiver...") if not fs.exists("/usr/bin/arc.lua") then local arc = get("https://pastebin.com/VdJMpxkS") writeTo(arc, "/usr/bin/arc.lua") end end local function addRepo(repoURL) -- i.e. addRepo('git:ocawesome101/ocpm/packages') local full_url = resolveURL(repoURL) checkDirs() if not get(full_url .. "packages.list") then print("E: Provided repository either does not exist or does not have a packages.list file.") return nil end write("Add repository " .. repoURL .. "? [y/n]: ") local add = read() if add:lower() == "y" then local repoList = fs.open(listFile, "a") repoList.write(full_url) repoList.close() else print("Aborting.") end end local function getLists() local retList = {} local items = fs.list(listDir) for i=1, #items, 1 do print("Found list " .. listDir .. items[i]) local tmp = require(listDir .. items[i]) for j=1, #tmp, 1 do table.insert(retList, tmp[j]) end end return retList end local function resolveDepends(pkgData) if not pkgData.depends then print("No dependencies to resolve.") return nil end local rtn = {} for i=1, #pkgData.depends, 1 do table.insert(rtn, pkgData.depends[i]) end return rtn end local function splitLines(fileHandle) local retList for line in fileHandle:lines() do table.insert(retList, line) end return retList end local function getInstalled() local raw = fs.open(pmDirs[4] .. "installed.list", "r") local rtn = splitLines(raw) raw.close() end local function registerPkg(name, mode) local pkgRegs = getInstalled() if mode == nil or mode == "add" then table.insert(pkgRegs, name) writeList(pkgRegs, pmDirs[4] .. "installed.list") elseif mode == "sub" then for i=1, #pkgRegs, 1 do if pkgRegs[i] == name then pkgRegs[i] = nil end end end end local function installPackage(name) print("Installing package " .. name) checkDirs() checkArc() local list = getLists() if list == {} or #list == 0 then print("E: Package list(s) are missing or empty. Try running ocpm update.") return nil end if not list[name] then print("E: Package not found.") return nil end local pkg = list[name] print("Resolving dependencies...") local depends = resolveDepends(pkg) print("The following packages will be installed:") local toInstall = {} if depends then for i=1, #depends, 1 do write(depends[i] .. " ") table.insert(toInstall, depends[i]) end write("\n") end table.insert(toInstall, name) print(name) write("Install" .. tostring(#toInstall) .. " packages? [Y/n]: ") if string.lower(read()) == "n" then print("Aborting.") return nil end for i=1, #toInstall, 1 do local pkgURL = resolveURL(list[toInstall[i]].downloadURL) local data = get(pkgURL) writeTo(data, pkgDir .. toInstall[i] .. ".arc") end for i=1, #toInstall, 1 do shell.run("/usr/bin/arc x " .. toInstall[i] .. " " .. tmpDir) if not fs.exists(tmpDir .. toInstall[i] .. "/install.lua") then print("E: Package " .. toInstall[i] .. " has no install.lua.") return nil end if not fs.exists(tmpDir .. toInstall[i] .. "/uninstall.lua") then print("E: Package " .. toInstall[i] .. " has no uninstall.lua.") end shell.run(tmpDir .. toInstall[i] .. "/install.lua") print("Registering package " .. toInstall[i]) registerPkg(toInstall[i], "add") end return true end local function updateLists() local i = 1 for line in io.lines(listFile) do print("Download:" .. tostring(i) .. ": " .. line .. "/packages.list") local list = get(line .. "/packages.list") if list == "" or not list then print("E: Repo " .. line .. " has no packages.list file") return nil end writeTo(list, listDir .. "list_" .. tostring(i) .. ".list") i = i + 1 end end local function removePackage(name) print("Removing package " .. name) checkArc() print("Getting installed packages...") local installed = getInstalled() local toRemove = {} for i=1, #installed, 1 do if installed[i] == name then table.insert(toRemove, name) end end if toRemove == {} then print("E: Package " .. name .. " is not installed.") return nil end if not fs.exists(tmpDir .. toRemove[1]) then shell.run("/usr/bin/arc x " .. pkgDir .. toRemove[1] .. " " .. tmpDir) shell.run(tmpDir .. toRemove[1] .. "/uninstall.lua") end registerPkg(name, "sub") end local function usage() print([[ OCPM v0.2.7 by Ocawesome101 Usage: ocpm <install | remove> <package> Install or remove a package ocpm update Refresh package lists ocpm addrepo <url> Add a package repository ]]) end local function parseArgs(tArgs) if tArgs[1] == "update" then updateLists() elseif tArgs[1] == "addrepo" then if tArgs[2] then addRepo(tArgs[2]) else usage() end elseif tArgs[1] == "install" then if tArgs[2] then installPackage(tArgs[2]) else usage() end elseif tArgs[1] == "remove" then if tArgs[2] then removePackage(tArgs[2]) else usage() end else usage() end end parseArgs(args) <file_sep># ocpm A package manager for OC Linux. Similar to Apt. `ocpm.lua` is the script itself. It half works. `cache` should be `/var/cache`. Should be run inside OC Linux! ### Adding sources To add a source to OC Linux, you can either directly put a link in your `/etc/ocpm/sources.list` file, or you can run `ocpm addrepo <url>`. `url` can be one of the following: - a GitHub repo: `git:user/repo/branch/` or `https://raw.githubusercontent.com/user/repo/branch/`. In the root of said branch must be a `packages.list` file. See [this](https://github.com/ocawesome101/ocpm-packages) for an example of a `packages.list` file. - a Web site: `https://repo.example.com/stable/`. Note that Web sites must have `packages.list` in the same directory that `index.html` would be - in this case, `/opt/www/example/stable/packages.list` in the server filesystem. Alternatively, you can just use the link to the file (`https://example.com/raw/packages.list`) but without `packages.list` at the end (`https://example.com/raw/`). The file MUST be named `packages.list`! I may make a package list generator at some point in the future, probably written in either Python or Lua. NOTE: The `packages.list` format has not yet been finalized and is liable to change without notice.
8d763b56fe2ea8f95f07fa78e48f8117e27e5cc9
[ "Markdown", "Lua" ]
2
Lua
Ocawesome101/ocpm
ea628cbc05d4fd640caeeacb6b6235a0463399ef
bda5c8d584a640fca47c9ca6cc6a0f49c0961d56
refs/heads/master
<repo_name>ppedvAG/190708_CSharp-Einsteiger_MUC<file_sep>/OOP/OOP/Konto.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OOP { public class Konto { private decimal kontostand; public decimal Kontostand { get { return kontostand; } // Kontostand darf innerhalb meines Programms nicht verändert werden! private set { kontostand = GetKontoStandAusDatenbank(); //kontostand = value; } } private decimal GetKontoStandAusDatenbank() { // Logik zum Erhalten des Kontostandes return Convert.ToDecimal(0.00); } } }<file_sep>/HalloWelt/Vererbung/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Vererbung { class Program { static void Main(string[] args) { //Lebewesen Mensch = new Mensch("30","München"); Mensch Mensch = new Mensch("2222", "IUrgendwo"); Console.WriteLine(Mensch.GetType()); Console.ReadKey(); } } } <file_sep>/HalloWelt/VererbungZwei/Person.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VererbungZwei { public class Person { private string name; public string Name { get => name; set => name = value; } public virtual string Bearbeiten() { return "Es wird bearbeitet ..."; } } } <file_sep>/Enumeratoren/Enumeratoren/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Enumeratoren { class Program { enum Mahlzeiten { Frühstück, Mittagessen, Abendessen, Brotzeit }; enum Tag { Montag=1, Dienstag, Mittwoch, Donnerstag, Freitag, Samstag, Sonntag }; enum Monat { Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Okt, Nov, Dez }; enum MaschinenStatus { SaftAus = 0, Läuft = 5, StandBy = 10, Ruhemodus = StandBy + 5 } static void Main(string[] args) { Tag heute = Tag.Dienstag; int tagesNummer = (int)heute; Console.WriteLine($"Der heutige Tag hat die Nummer {tagesNummer}"); Monat aktuellerMonat = Monat.Jul; int monatsZahl = (int)aktuellerMonat; Console.WriteLine($"Der aktuelle Monat ist:{monatsZahl}"); MaschinenStatus aktuellerStatus = MaschinenStatus.Läuft; Console.WriteLine($"{aktuellerStatus.ToString()}"); Console konsole = new Console(); //List<string> MahlzeitenArray = new List<string>(); //MahlzeitenArray.Add("Frühstück"); //MahlzeitenArray.Add("Montag"); //MahlzeitenArray.Add("Dienstag"); //MahlzeitenArray.Add("Montag"); //MahlzeitenArray.Add("Montag"); //MahlzeitenArray.Add("Montag"); //Mahlzeiten Abendessen = Mahlzeiten.Abendessen; //Mahlzeiten Mittagessen = Mahlzeiten.Brotzeit; //foreach(string essen in MahlzeitenArray) //{ // Console.WriteLine($"{essen}"); //} Console.ReadLine(); } } } <file_sep>/TaschenRechner/TaschenRechner/Rechner.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TaschenRechner { public class Rechner // Bauplan { public int subtrahieren(int a, int b) { int differenz; if (a>=b) { differenz = a - b; } else { differenz = b - a; } return differenz; } public int addiere(int a, int b) { int summe = a + b; return summe; } public int multiplizieren(int a, int b) { int produkt = a * b; return produkt; } public double dividieren(int a, int b) { double quotient; if(! (a == 0 || b == 0)) { quotient = a / b; } else { quotient = 0; } return quotient; } } } <file_sep>/HalloWelt/Bibliotheken/Konto.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bibliotheken { public class Konto { public void Überweisen() { Console.WriteLine("Überweisung wird getätigt"); } } } <file_sep>/HalloWelt/Vererbung/Mensch.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Vererbung { public class Mensch { public string Wohnort { get; set; } public Mensch(string alter, string wohnort) { Wohnort = wohnort; Console.WriteLine($"Mein Wohnort lautet: {Wohnort}, Alter: {alter}"); } } } <file_sep>/OOP/OOP/Buch.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OOP { public class Buch { // Felder // Klassenintern private string titel; private Person autor; private string isbn; private int kapitel; // Eigenschaft // Zugriff von außen public string ISBN { get { return isbn; } private set { isbn = value; } } public float Preis; public string Titel { get { return titel; } private set { titel = value; } } public Person Autor { get { return autor; } } public int Kapitel { get => kapitel; set => kapitel = value; } public int Seiten { get; set; } public Buch() { titel = ""; } public Buch(Person autor) { this.autor = autor; } //public string GetTitel() //{ // return titel; //} //public void SetTitel(string value) //{ // titel = value; //} enum genre { Roman, Krimi, Fachbuch }; } } <file_sep>/HalloWelt/Bibliotheken/Person.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bibliotheken { public class Person { public void Laufen() { Console.WriteLine("Eine Person läuft"); } } } <file_sep>/HalloWelt/GenerischeDatentypen/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GenerischeDatentypen { class Program { static void Main(string[] args) { //Dictionary<string, int> meinDictionary = new Dictionary<string, int>(); //meinDictionary.Add("Kontostand", 3000); //List<string> StringListe = new List<string>(); //StringListe.Add("Item 1-Liste1"); //StringListe.Add("Item 2-Liste1"); //StringListe.Add("Item 3-Liste1"); //StringListe.Add("Item 4-Liste1"); //List<string> StringListe2 = new List<string>(); //StringListe2.Add("Item 1-Liste2"); //StringListe2.Add("Item 2-Liste2"); //StringListe2.Add("Item 3-Liste2"); //StringListe2.Add("Item 4-Liste2"); //Dictionary< string, List<string> > meinDictionary2 = new Dictionary<string, List<string>>(); //meinDictionary2.Add("Liste1", StringListe); //meinDictionary2.Add("Liste2", StringListe2); //foreach (KeyValuePair<string, List<string>> eintrag in meinDictionary2) //{ // foreach(string key in meinDictionary2.Keys) // { // Console.WriteLine(meinDictionary2[key][0]); // //Console.WriteLine(key); // } // //Console.WriteLine(eintrag.Key); //} List<string> einfacheStringListe = new List<string>(); einfacheStringListe.Add("Listen-Element 1"); //Predicate<int> match = new Predicate<int>() List<int> einfacheZahlenListe = new List<int>(); einfacheZahlenListe.Add(1); einfacheZahlenListe.Add(2); einfacheZahlenListe.Add(3); einfacheZahlenListe.Add(3); einfacheZahlenListe.Add(3); einfacheZahlenListe.Add(3); //einfacheZahlenListe.Remove(3); List<int> Ergebnis = einfacheZahlenListe.FindAll(NurDreier); //einfacheZahlenListe.RemoveAll(NurDreier); foreach (int zahl in einfacheZahlenListe) { Console.WriteLine($"Aktuelles Element: {zahl}"); } Queue<string> einfacheSchlange = new Queue<string>(); einfacheSchlange.Enqueue("Schlangen-Element 1"); einfacheSchlange.Enqueue("Schlangen-Element 2"); Stack<string> einfacherStapel = new Stack<string>(); einfacherStapel.Push("Stapel-Element 1"); einfacherStapel.Push("Stapel-Element 2"); Console.ReadLine(); } static bool NurDreier(int i) { return i == 3; } } } <file_sep>/OOP/OOP/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OOP { class Program { static void Main(string[] args) { Person buchAutor = new Person("Josef"); //Buch meinBuch = new Buch(); //meinBuch.Preis = 12.99f; Buch josefsBuch = new Buch(buchAutor); Console.WriteLine($"Wer ist der Autor des Buches? {josefsBuch.Autor.Vorname}"); //meinBuch.Titel = "Mein Buch"; //Console.WriteLine(meinBuch.Titel); //meinBuch.Titel = "Mein Buch"; //meinBuch.SetTitel("Mein Buch"); //Console.WriteLine(meinBuch.GetTitel()); //Console.WriteLine(Convert.ToDateTime("01.01.1985")); //Person Ralf = new Person("Ralf"); //Person Ralf = new Person("Ralf", "Gottschalk"); //Person Ralf = new Person("Ralf", "Gottschalk", Convert.ToDateTime("01.01.1980")); //Person Ralf = new Person(5); //Ralf.Vorname = "Ralf"; //Ralf.Nachname = "Gottschalk"; //Console.WriteLine(Ralf.BeschreibeMich()); Console.ReadKey(); } } } <file_sep>/HalloWelt/ObjektOrientierung/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ObjektOrientierung { class Program { static void Main(string[] args) { Fahrzeug BMW = new Fahrzeug(); BMW.Preis = 19.999; BMW.Name = "Audi"; BMW.BeschreibeMich(); BMW.StarteMotor(); BMW.Beschleunigen(10); BMW.BeschreibeMich(); Console.WriteLine("--- ENDE ---"); Console.ReadLine(); } } } <file_sep>/HalloWelt/Bibliotheken/Fahrzeug.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bibliotheken { public class Fahrzeug { public void Bewegen() { Console.WriteLine("Ich bewege mich"); } } } <file_sep>/HalloWelt/VererbungZwei/Formular.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VererbungZwei { public class Formular : IEditable { Person sachbearbeiter1 = new Sachbearbeiter(); public string BearbeitungsStatus { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public string Ausfüllen() { return sachbearbeiter1.Bearbeiten(); } } } <file_sep>/HalloWelt/HalloWelt/Program.cs using System; using System.Windows; namespace HalloWelt { class Program { static void Main(string[] args) { #region Eingabe/Ausgabe - Variablen //double ergebnis; //Console.WriteLine("Eine Zahl eingeben"); //int eingabe1 = Convert.ToInt32(Console.ReadLine()); //Console.WriteLine("Weitere Zahl"); //double eingabe2 = Convert.ToDouble(Console.ReadLine()); //int intSumme = eingabe1 + Convert.ToInt32(eingabe2); //double dblSumme = eingabe1 + eingabe2; //Console.WriteLine($"Int-Summe: {intSumme}, Double-Summe: {dblSumme}"); //Console.WriteLine(Environment.NewLine); //if (eingabe1 > eingabe2) //{ // ergebnis = eingabe1 / eingabe2; //} else //{ // ergebnis = eingabe2 / eingabe1; //} //Console.WriteLine($"Ergebnis der Division: {ergebnis}"); //int alter = 52; //string text = Convert.ToString(alter); // string text = "<NAME>"; //int a = 1; //int a = 1, b = 10, c = 15; //Console.WriteLine("Hallo. Wie heißt Du?"); //string name = Console.ReadLine(); //Console.WriteLine("Wie alt bist Du?"); ////int alter = Convert.ToInt32(Console.ReadLine()); ////int alter = int.Parse(Console.ReadLine()); //try { // if (Convert.ToBoolean(int.Parse(Console.ReadLine()))) { // Console.WriteLine("jup"); // } else { // Console.WriteLine("Leider nein"); // } //} catch (Exception ex) { // MessageBox.Show(ex.Message); //} //Console.WriteLine("Aha, Du bist also {0} Jahre {1} {2} {3} als!",alter, alter, alter); //Console.WriteLine("Aha, du bist also " + alter + "Jahre alt!"); //Console.WriteLine($"Aha, Du heißt also {name}!"); //Console.WriteLine(text); #endregion Eingabe/Ausgabe - Variablen #region Kontrollstrukturen //int a = 5, b = 10, c = 15, d = 20, e = 5; //if (a + b == c) //{ // Console.WriteLine("Wert der Variablen a entspricht Wert der Variablen b"); //} else //{ // Console.WriteLine("Nichts trifft zu!"); //} #endregion Kontrollstrukturen #region Zufallszahl //Random generator = new Random(); //int zufallszahl = generator.Next(1, 5); //Console.WriteLine("Bitte eine Zahl eingeben: "); //int benutzerEingabe = Convert.ToInt32(Console.ReadLine()); //if (benutzerEingabe < zufallszahl) //{ // Console.WriteLine("Deine Eingabe war kleiner als die generierte Zufallszahl"); //} else //{ // Console.WriteLine("Deine Eingabe war größer als die generierte Zufallszahl"); //} //// MessageBox.Show(Convert.ToString(zufallszahl)); #endregion Zufallszahl #region Schleifen //bool ja = true; //while(ja) //{ // Console.WriteLine("Ja"); // for(int i = 0; i < 5; i++) // { // Console.WriteLine($"{i+1}ter Durchlauf."); // } // ja = false; //} // Alle geraden Zahlen von 1 bis 10 // Modulo //for (int i = 1; i <= 10; i++) //{ // if (i % 2 == 0) // { // Console.WriteLine(i); // } //} #endregion Schleifen #region Arrays int[] zahlenListe = new int[] { 1,2,3,4,5,6,7 }; for(int i = 1; i < zahlenListe.Length; i++) { Console.WriteLine($"{i}<NAME>"); } Console.WriteLine(zahlenListe.Length); Console.ReadKey(); #endregion Console.WriteLine("--- ENDE ---"); Console.ReadKey(); } } } <file_sep>/HalloWelt/DateiOperationen/Program.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DateiOperationen { class Program { static void Main(string[] args) { string path = @"C:\Temp\Textdatei.txt"; Console.WriteLine(File.ReadAllText(path)); List<string> liste = new List<string>(); liste.Add("Erster Eintrag"); liste.Add("Zweiter Eintrag"); foreach(string aktuellerEintrag in liste) { File.AppendAllText(@"c:\temp\zurueckgeschrieben.txt", aktuellerEintrag); } //File.WriteAllText(@"c:\temp\zurueckgeschrieben.txt", $"Uberschrieben {Environment.NewLine}Uberschreiben"); //File.AppendAllText(@"c:\temp\zurueckgeschrieben.txt", $"Anhängen,{Environment.NewLine} Anhängen"); Console.ReadLine(); } } } <file_sep>/TaschenRechner/TaschenRechner/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TaschenRechner { class Program { static void Main(string[] args) { Math.Cos(5.00); Rechner meinRechner = new Rechner(); Console.WriteLine(meinRechner.dividieren(10, 0)); Program programInstanz = new Program(); programInstanz.erstellen(); Console.ReadLine(); //Rechner.addiere(1, 2); } public void erstellen() { Console.WriteLine("Hallo"); } } } <file_sep>/HalloWelt/VererbungZwei/Sachbearbeiter.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VererbungZwei { public class Sachbearbeiter : Person { public override string Bearbeiten() { return "Sachbearbeiter" + base.Bearbeiten(); } } } <file_sep>/HalloWelt/ObjektOrientierung/Fahrzeug.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ObjektOrientierung { public class Fahrzeug { #region Felder // Felder private bool motorGestartet = false; private int maximaleGeschwindigkeit = 250; private Zustand aktuellerZustand = Zustand.Stehend; #endregion #region Eigenschaften //Eigenschaften enum Zustand { Stehend, Fahrend }; public string Name { get; set; } public int MaximaleGeschwindigkeit { get => maximaleGeschwindigkeit; } public double Preis { get; set; } public int AktuelleGeschwindigkeit { get; private set; } #endregion #region Konstruktor // Konstruktor public Fahrzeug() { Console.WriteLine("Fahrzeug wurde instanziiert!"); //BeschreibeMich(); SetZustand(); } #endregion #region Methoden // Methoden private void SetZustand() { while (AktuelleGeschwindigkeit > 0) { aktuellerZustand = Zustand.Fahrend; } } /// <summary> /// Funktion an der Klasse Fahrzeug -> Methode zum Beschleunigen des Fahrzeugs /// </summary> /// <param name="geschwindigkeitsSchritt">Datentyp des Parameters: int</param> public void Beschleunigen(int GeschwindigkeitsSchritt) { if (motorGestartet) { do { AktuelleGeschwindigkeit += GeschwindigkeitsSchritt; Console.WriteLine($"Das Auto beschleunigt um {GeschwindigkeitsSchritt} und fährt nun {AktuelleGeschwindigkeit} "); } while (AktuelleGeschwindigkeit < maximaleGeschwindigkeit); aktuellerZustand = Zustand.Fahrend; } else { Console.WriteLine("Motor wurde noch nicht gestartet!"); } } public void StarteMotor() { motorGestartet = true; Console.WriteLine("Motor wurde gestartet!"); } public void StoppeMotor() { motorGestartet = false; Console.WriteLine("Motor wurde gestoppt!"); } public void BeschreibeMich() { Console.WriteLine($"Hersteller: {Name}"); Console.WriteLine($"Maximale Geschwindigkeit: {MaximaleGeschwindigkeit}"); Console.WriteLine($"Aktuelle Geschwindigkeit: {AktuelleGeschwindigkeit}"); Console.WriteLine($"Aktueller Zustand: {aktuellerZustand}"); Console.WriteLine($"Preis: {Preis}"); } #endregion } } <file_sep>/HalloWelt/Vererbung/CustomRandom.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Vererbung { public class CustomRandom : Random { public int NextInclusive(int minValue, int maxValue) { return base.Next(minValue, maxValue + 1); } } } <file_sep>/HalloWelt/VererbungZwei/IEditable.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VererbungZwei { interface IEditable { string BearbeitungsStatus { get; set; } string Ausfüllen(); } } <file_sep>/HalloWelt/GlobaleVariablen/GLOBALEVARIABLEN.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GlobaleVariablen { public static class GLOBALEVARIABLEN { public static string DATEIPFAD = "C:\Temp"; } } <file_sep>/OOP/OOP/Person.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OOP { public class Person { public string Vorname; public string Nachname; public DateTime Geburtsdatum; public Person() { } public Person(string vorname) : this(vorname, "") { } public Person(string vorname, string nachname) { Vorname = vorname; Nachname = nachname; } // Eine Methode zur Beschreibung einer Person public string BeschreibeMich() { return $"Hallo, ich bin {Vorname} {Nachname}"; } public string Lesen() { return "ich lese"; } } } <file_sep>/HalloWelt/Vererbung/Lebewesen.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Vererbung { public class Lebewesen { public string Alter { get; set; } public Lebewesen(string alter) { Alter = alter; } } }
67f0075b8abe892b9ed7f530ea818c03191468a7
[ "C#" ]
24
C#
ppedvAG/190708_CSharp-Einsteiger_MUC
3ec955c5abf5566762a4b58e626ce7fe51f2b850
c5bba30951ebcb815990b7f83500b6293c8041e2
refs/heads/main
<file_sep>import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.BorderLayout; import javax.swing.SwingConstants; import java.awt.Font; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JButton; public class Grafico1 { private JFrame frame; private JTextField textField; private JTextField textField_1; private JTextField textField_2; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Grafico1 window = new Grafico1(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public Grafico1() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JLabel lblNewLabel = new JLabel("DEPARTAMENTOS"); lblNewLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 16)); lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel.setBounds(0, 25, 450, 16); frame.getContentPane().add(lblNewLabel); JPanel panel = new JPanel(); panel.setBounds(39, 66, 355, 128); frame.getContentPane().add(panel); panel.setLayout(null); JLabel lblNewLabel_1 = new JLabel("Nombre Departamento:"); lblNewLabel_1.setBounds(23, 24, 147, 16); panel.add(lblNewLabel_1); JLabel lblNewLabel_1_1 = new JLabel("Código Departamento:"); lblNewLabel_1_1.setBounds(23, 59, 147, 16); panel.add(lblNewLabel_1_1); JLabel lblNewLabel_1_2 = new JLabel("Localidad Departamento:"); lblNewLabel_1_2.setBounds(23, 95, 161, 16); panel.add(lblNewLabel_1_2); textField = new JTextField(); textField.setBounds(196, 19, 130, 26); panel.add(textField); textField.setColumns(10); textField_1 = new JTextField(); textField_1.setColumns(10); textField_1.setBounds(196, 54, 130, 26); panel.add(textField_1); textField_2 = new JTextField(); textField_2.setColumns(10); textField_2.setBounds(196, 90, 130, 26); panel.add(textField_2); JButton btnNewButton = new JButton("INSERTAR DATOS"); btnNewButton.setBounds(49, 216, 153, 29); frame.getContentPane().add(btnNewButton); JButton btnBorrarDatos = new JButton("BORRAR DATOS"); btnBorrarDatos.setBounds(228, 216, 153, 29); frame.getContentPane().add(btnBorrarDatos); } } <file_sep># entornos-de-desarrollo Asignatura Entornos de desarrollo de 1º de DAM con el profesor <NAME> del instituto IES Juan de la Cierva
544deb93ea411b0cf82ea724606d6a11081ff72d
[ "Markdown", "Java" ]
2
Java
mateorussi/entornos-de-desarrollo
39a0718f7b8e00d007949edf60d8321dad7630aa
90cb90022444690d5aa20c028a8e7901bf6167c7
refs/heads/master
<repo_name>JakobKadosh/BrewDogApi<file_sep>/src/app/select-beer/select-beer.component.ts import { Component, OnInit } from '@angular/core'; import { BeerService } from 'src/shared/services/beer.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-select-beer', templateUrl: './select-beer.component.html', styleUrls: ['./select-beer.component.css'] }) export class SelectBeerComponent implements OnInit { id:number; constructor(private router:Router, private service:BeerService) { } ngOnInit() { } public setSelectedBeer(){ this.service.getSpecificBeer(this.id) this.router.navigate(['show']) } } <file_sep>/src/app/show-beer/show-beer.component.ts import { Component, OnInit } from '@angular/core'; import { Beer } from 'src/shared/models/Beer'; import { BeerService } from 'src/shared/services/beer.service'; @Component({ selector: 'app-show-beer', templateUrl: './show-beer.component.html', styleUrls: ['./show-beer.component.css'] }) export class ShowBeerComponent implements OnInit { constructor(private beerSer:BeerService) { } ngOnInit() { } public selectedBeerInfo:Beer= this.beerSer.beerInfo; } <file_sep>/src/shared/services/beer.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Beer } from '../models/Beer'; @Injectable({ providedIn: 'root' }) export class BeerService { beerInfo:any={ selected:null }; constructor(private http:HttpClient) { } public getSpecificBeer(id:number):void{ this.http.get<Beer[]>(`https://api.punkapi.com/v2/beers/${id}`).subscribe( res=>{ this.beerInfo.selected=res[0] }, err=>{alert("ERROR!")} ) } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import {HttpClientModule} from '@angular/common/http'; import { AppComponent } from './app.component'; import { SelectBeerComponent } from './select-beer/select-beer.component'; import { ShowBeerComponent } from './show-beer/show-beer.component'; import {FormsModule} from '@angular/forms'; import { Routes, RouterModule } from '@angular/router'; const routes=[ {path:"",component:SelectBeerComponent}, {path:"select",component:SelectBeerComponent }, {path:"show",component:ShowBeerComponent} ]; @NgModule({ declarations: [ AppComponent, SelectBeerComponent, ShowBeerComponent ], imports: [ BrowserModule, HttpClientModule, RouterModule.forRoot(routes), FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/README.md ### This is a small angular project using an outside API. ### two components with routing between them. with css.
1f501a582c0603774d8a10775f8125b92ad76cc0
[ "Markdown", "TypeScript" ]
5
TypeScript
JakobKadosh/BrewDogApi
1581a218b41c7b54a37ad5763a48bbdf65779cd4
875103bc7dd1e4d36fba6da544eb0b57f8b32b5c
refs/heads/master
<repo_name>di8735/Access<file_sep>/d3dUtility.cpp ////////////////////////////////////////////////////////////////////////////////////////////////// // // File: d3dUtility.cpp // // Author: <NAME> (C) All Rights Reserved // // System: AMD Athlon 1800+ XP, 512 DDR, Geforce 3, Windows XP, MSVC++ 7.0 // // Desc: Provides utility functions for simplifying common tasks. // ////////////////////////////////////////////////////////////////////////////////////////////////// #include "d3dUtility.h" // vertex formats const DWORD d3d::Vertex::FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1; HWND d3d::InitD3D( HINSTANCE hInstance, int width, int height, bool windowed, D3DDEVTYPE deviceType, IDirect3DDevice9** device, LPD3DXSPRITE* pSprite) { // // Create the main application window. // WNDCLASS wc; wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = (WNDPROC)d3d::WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(0, IDI_APPLICATION); wc.hCursor = LoadCursor(0, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wc.lpszMenuName = 0; wc.lpszClassName = L"Access"; if( !RegisterClass(&wc) ) { ::MessageBox(0, L"RegisterClass() - FAILED", 0, 0); return false; } HWND hwnd = 0; hwnd = ::CreateWindow(L"Access", L"Access", WS_EX_TOPMOST, 0, 0, width, height, 0 /*parent hwnd*/, 0 /* menu */, hInstance, 0 /*extra*/); if( !hwnd ) { ::MessageBox(0, L"CreateWindow() - FAILED", 0, 0); return false; } ::ShowWindow(hwnd, SW_SHOW); ::UpdateWindow(hwnd); // // Init D3D: // HRESULT hr = 0; // Step 1: Create the IDirect3D9 object. IDirect3D9* d3d9 = 0; d3d9 = Direct3DCreate9(D3D_SDK_VERSION); if( !d3d9 ) { ::MessageBox(0, L"Direct3DCreate9() - FAILED", 0, 0); return false; } // Step 2: Check for hardware vp. D3DCAPS9 caps; d3d9->GetDeviceCaps(D3DADAPTER_DEFAULT, deviceType, &caps); int vp = 0; if( caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) vp = D3DCREATE_HARDWARE_VERTEXPROCESSING; else vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING; // Step 3: Fill out the D3DPRESENT_PARAMETERS structure. D3DPRESENT_PARAMETERS d3dpp; d3dpp.BackBufferWidth = width; d3dpp.BackBufferHeight = height; d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8; d3dpp.BackBufferCount = 1; d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; d3dpp.MultiSampleQuality = 0; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.hDeviceWindow = hwnd; d3dpp.Windowed = windowed; d3dpp.EnableAutoDepthStencil = true; d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8; d3dpp.Flags = 0; d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Step 4: Create the device. hr = d3d9->CreateDevice( D3DADAPTER_DEFAULT, // primary adapter deviceType, // device type hwnd, // window associated with device vp, // vertex processing &d3dpp, // present parameters device); // return created device D3DXCreateSprite(*device, pSprite); if( FAILED(hr) ) { // try again using a 16-bit depth buffer d3dpp.AutoDepthStencilFormat = D3DFMT_D16; hr = d3d9->CreateDevice( D3DADAPTER_DEFAULT, deviceType, hwnd, vp, &d3dpp, device); if( FAILED(hr) ) { d3d9->Release(); // done with d3d9 object ::MessageBox(0, L"CreateDevice() - FAILED", 0, 0); return false; } } d3d9->Release(); // done with d3d9 object return hwnd; } wchar_t* CharToWideChar(const char* str) { assert(str); int charLen = strlen(str) + 1; WCHAR* wText = (LPWSTR)new WCHAR[sizeof(WCHAR) * charLen]; int retval = MultiByteToWideChar(949, 0, str, -1, wText, charLen); return wText; } int d3d::EnterMsgLoop( bool (*ptr_display)(float timeDelta) ) { MSG msg; ::ZeroMemory(&msg, sizeof(MSG)); static float lastTime = (float)timeGetTime(); while(msg.message != WM_QUIT) { if(::PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } else { float currTime = (float)timeGetTime(); float timeDelta = (currTime - lastTime)*0.001f; ptr_display(timeDelta); lastTime = currTime; } } return msg.wParam; } D3DLIGHT9 d3d::InitDirectionalLight(D3DXVECTOR3* direction, D3DXCOLOR* color) { D3DLIGHT9 light; ::ZeroMemory(&light, sizeof(light)); light.Type = D3DLIGHT_DIRECTIONAL; light.Ambient = *color * 0.8f; light.Diffuse = *color; light.Specular = *color * 0.6f; light.Direction = *direction; return light; } D3DLIGHT9 d3d::InitPointLight(D3DXVECTOR3* position, D3DXCOLOR* color) { D3DLIGHT9 light; ::ZeroMemory(&light, sizeof(light)); light.Type = D3DLIGHT_POINT; light.Ambient = *color * 1.0f; light.Diffuse = *color; light.Specular = *color * 1.0f; light.Position = *position; light.Range = 100000.0f; light.Falloff = 1.0f; light.Attenuation0 = 1.0f; light.Attenuation1 = 0.0f; light.Attenuation2 = 0.0f; return light; } D3DLIGHT9 d3d::InitSpotLight(D3DXVECTOR3* position, D3DXVECTOR3* direction, D3DXCOLOR* color) { D3DLIGHT9 light; ::ZeroMemory(&light, sizeof(light)); light.Type = D3DLIGHT_SPOT; light.Ambient = *color * 0.4f; light.Diffuse = *color; light.Specular = *color * 0.6f; light.Position = *position; light.Direction = *direction; light.Range = 1000.0f; light.Falloff = 1.0f; light.Attenuation0 = 1.0f; light.Attenuation1 = 0.0f; light.Attenuation2 = 0.0f; light.Theta = 0.5f; light.Phi = 0.7f; return light; } D3DMATERIAL9 d3d::InitMtrl(D3DXCOLOR a, D3DXCOLOR d, D3DXCOLOR s, D3DXCOLOR e, float p) { D3DMATERIAL9 mtrl; mtrl.Ambient = a; mtrl.Diffuse = d; mtrl.Specular = s; mtrl.Emissive = e; mtrl.Power = p; return mtrl; } LPD3DXFONT d3d::InitFont(IDirect3DDevice9* device, LPD3DXSPRITE &pSprite) { LPD3DXFONT fonts = NULL; ::ZeroMemory(&fonts, sizeof(fonts)); D3DXCreateFontW(device, 15, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, TEXT("28 Days Later º¸Åë"), &fonts); return fonts; } int d3d::CountFrame(float timeDelta) { static int countNum = 0; static int frame = 0; static float countTime = 0; countTime += timeDelta; if (countTime >= 1) { countTime = 0; frame = countNum; countNum = 0; } else ++countNum; return frame; } d3d::BoundingBox::BoundingBox() { // infinite small _min.x = d3d::Infinity; _min.y = d3d::Infinity; _min.z = d3d::Infinity; _max.x = -d3d::Infinity; _max.y = -d3d::Infinity; _max.z = -d3d::Infinity; } bool d3d::BoundingBox::isPointInside(D3DXVECTOR3& p) { if( p.x >= _min.x && p.y >= _min.y && p.z >= _min.z && p.x <= _max.x && p.y <= _max.y && p.z <= _max.z ) { return true; } else { return false; } } d3d::BoundingSphere::BoundingSphere() { _radius = 0.0f; } HRESULT AllocateName(LPCSTR Name, LPSTR* pNewName) { UINT cbLength; if (Name != NULL) { cbLength = (UINT)strlen(Name) + 1; *pNewName = new CHAR[cbLength]; if (*pNewName == NULL) return E_OUTOFMEMORY; memcpy(*pNewName, Name, cbLength * sizeof(CHAR)); } else { *pNewName = NULL; } return S_OK; } HRESULT CAllocateHierarchy::CreateFrame(LPCSTR Name, LPD3DXFRAME* ppNewFrame) { HRESULT hr = S_OK; D3DXFRAME_DERIVED* pFrame; *ppNewFrame = NULL; pFrame = new D3DXFRAME_DERIVED; if (pFrame == NULL) { hr = E_OUTOFMEMORY; goto e_Exit; } hr = AllocateName(Name, &pFrame->Name); if (FAILED(hr)) goto e_Exit; // initialize other data members of the frame D3DXMatrixIdentity(&pFrame->TransformationMatrix); D3DXMatrixIdentity(&pFrame->CombinedTransformationMatrix); pFrame->pMeshContainer = NULL; pFrame->pFrameSibling = NULL; pFrame->pFrameFirstChild = NULL; *ppNewFrame = pFrame; pFrame = NULL; e_Exit: delete pFrame; return hr; } HRESULT CAllocateHierarchy::CreateMeshContainer( LPCSTR Name, CONST D3DXMESHDATA *pMeshData, CONST D3DXMATERIAL *pMaterials, CONST D3DXEFFECTINSTANCE *pEffectInstances, DWORD NumMaterials, CONST DWORD *pAdjacency, LPD3DXSKININFO pSkinInfo, LPD3DXMESHCONTAINER *ppNewMeshContainer) { HRESULT hr; D3DXMESHCONTAINER_DERIVED *pMeshContainer = NULL; UINT NumFaces; UINT iMaterial; UINT iBone, cBones; LPDIRECT3DDEVICE9 pd3dDevice = NULL; LPD3DXMESH pMesh = NULL; *ppNewMeshContainer = NULL; // this sample does not handle patch meshes, so fail when one is found if (pMeshData->Type != D3DXMESHTYPE_MESH) { hr = E_FAIL; goto e_Exit; } // get the pMesh interface pointer out of the mesh data structure pMesh = pMeshData->pMesh; // this sample does not FVF compatible meshes, so fail when one is found if (pMesh->GetFVF() == 0) { hr = E_FAIL; goto e_Exit; } // allocate the overloaded structure to return as a D3DXMESHCONTAINER pMeshContainer = new D3DXMESHCONTAINER_DERIVED; if (pMeshContainer == NULL) { hr = E_OUTOFMEMORY; goto e_Exit; } memset(pMeshContainer, 0, sizeof(D3DXMESHCONTAINER_DERIVED)); // make sure and copy the name. All memory as input belongs to caller, interfaces can be addref'd though hr = AllocateName(Name, &pMeshContainer->Name); if (FAILED(hr)) goto e_Exit; pMesh->GetDevice(&pd3dDevice); NumFaces = pMesh->GetNumFaces(); // if no normals are in the mesh, add them if (!(pMesh->GetFVF() & D3DFVF_NORMAL)) { pMeshContainer->MeshData.Type = D3DXMESHTYPE_MESH; // clone the mesh to make room for the normals hr = pMesh->CloneMeshFVF(pMesh->GetOptions(), pMesh->GetFVF() | D3DFVF_NORMAL, pd3dDevice, &pMeshContainer->MeshData.pMesh); if (FAILED(hr)) goto e_Exit; // get the new pMesh pointer back out of the mesh container to use // NOTE: we do not release pMesh because we do not have a reference to it yet pMesh = pMeshContainer->MeshData.pMesh; // now generate the normals for the pmesh D3DXComputeNormals(pMesh, NULL); } else // if no normals, just add a reference to the mesh for the mesh container { pMeshContainer->MeshData.pMesh = pMesh; pMeshContainer->MeshData.Type = D3DXMESHTYPE_MESH; pMesh->AddRef(); } // allocate memory to contain the material information. This sample uses // the D3D9 materials and texture names instead of the EffectInstance style materials pMeshContainer->NumMaterials = max(1, NumMaterials); pMeshContainer->pMaterials = new D3DXMATERIAL[pMeshContainer->NumMaterials]; pMeshContainer->ppTextures = new LPDIRECT3DTEXTURE9[pMeshContainer->NumMaterials]; pMeshContainer->pAdjacency = new DWORD[NumFaces * 3]; if ((pMeshContainer->pAdjacency == NULL) || (pMeshContainer->pMaterials == NULL)) { hr = E_OUTOFMEMORY; goto e_Exit; } memcpy(pMeshContainer->pAdjacency, pAdjacency, sizeof(DWORD)* NumFaces * 3); memset(pMeshContainer->ppTextures, 0, sizeof(LPDIRECT3DTEXTURE9)* pMeshContainer->NumMaterials); // if materials provided, copy them if (NumMaterials > 0) { memcpy(pMeshContainer->pMaterials, pMaterials, sizeof(D3DXMATERIAL)* NumMaterials); for (iMaterial = 0; iMaterial < NumMaterials; iMaterial++) { if (pMeshContainer->pMaterials[iMaterial].pTextureFilename != NULL) { LPSTR charFileName; wchar_t* WideCharFileName; wchar_t location[MAX_PATH]; charFileName = pMeshContainer->pMaterials[iMaterial].pTextureFilename; WideCharFileName = CharToWideChar(charFileName); if (D3D_OK != D3DXCreateTextureFromFileA(pd3dDevice, pMeshContainer->pMaterials[iMaterial].pTextureFilename, &pMeshContainer->ppTextures[iMaterial])) { wcscpy_s(location, L"suit\\"); wcscat_s(location, WideCharFileName); D3DXCreateTextureFromFile(pd3dDevice, location, &pMeshContainer->ppTextures[iMaterial]); wcscpy_s(location, L"effect\\"); wcscat_s(location, WideCharFileName); D3DXCreateTextureFromFile(pd3dDevice, location, &pMeshContainer->ppTextures[iMaterial]); wcscpy_s(location, L"map\\"); wcscat_s(location, WideCharFileName); D3DXCreateTextureFromFile(pd3dDevice, location, &pMeshContainer->ppTextures[iMaterial]); wcscpy_s(location, L"mob\\"); wcscat_s(location, WideCharFileName); D3DXCreateTextureFromFile(pd3dDevice, location, &pMeshContainer->ppTextures[iMaterial]); wcscpy_s(location, L"etc\\"); wcscat_s(location, WideCharFileName); D3DXCreateTextureFromFile(pd3dDevice, location, &pMeshContainer->ppTextures[iMaterial]); //pMeshContainer->ppTextures[iMaterial] = NULL; } // don't remember a pointer into the dynamic memory, just forget the name after loading pMeshContainer->pMaterials[iMaterial].pTextureFilename = NULL; } } } else // if no materials provided, use a default one { pMeshContainer->pMaterials[0].pTextureFilename = NULL; memset(&pMeshContainer->pMaterials[0].MatD3D, 0, sizeof(D3DMATERIAL9)); pMeshContainer->pMaterials[0].MatD3D.Diffuse.r = 0.5f; pMeshContainer->pMaterials[0].MatD3D.Diffuse.g = 0.5f; pMeshContainer->pMaterials[0].MatD3D.Diffuse.b = 0.5f; pMeshContainer->pMaterials[0].MatD3D.Specular = pMeshContainer->pMaterials[0].MatD3D.Diffuse; } // if there is skinning information, save off the required data and then setup for HW skinning if (pSkinInfo != NULL) { // first save off the SkinInfo and original mesh data pMeshContainer->pSkinInfo = pSkinInfo; pSkinInfo->AddRef(); pMeshContainer->pOrigMesh = pMesh; pMesh->AddRef(); // Will need an array of offset matrices to move the vertices from the figure space to the bone's space cBones = pSkinInfo->GetNumBones(); pMeshContainer->pBoneOffsetMatrices = new D3DXMATRIX[cBones]; if (pMeshContainer->pBoneOffsetMatrices == NULL) { hr = E_OUTOFMEMORY; goto e_Exit; } // get each of the bone offset matrices so that we don't need to get them later for (iBone = 0; iBone < cBones; iBone++) { pMeshContainer->pBoneOffsetMatrices[iBone] = *(pMeshContainer->pSkinInfo->GetBoneOffsetMatrix(iBone)); } // GenerateSkinnedMesh will take the general skinning information and transform it to a HW friendly version hr = GenerateSkinnedMesh(pd3dDevice, pMeshContainer); if (FAILED(hr)) goto e_Exit; } *ppNewMeshContainer = pMeshContainer; pMeshContainer = NULL; e_Exit: SAFE_RELEASE(pd3dDevice); // call Destroy function to properly clean up the memory allocated if (pMeshContainer != NULL) { DestroyMeshContainer(pMeshContainer); } return hr; } HRESULT CAllocateHierarchy::DestroyFrame(LPD3DXFRAME pFrameToFree) { SAFE_DELETE_ARRAY(pFrameToFree->Name); SAFE_DELETE(pFrameToFree); return S_OK; } HRESULT CAllocateHierarchy::DestroyMeshContainer(LPD3DXMESHCONTAINER pMeshContainerBase) { UINT iMaterial; D3DXMESHCONTAINER_DERIVED* pMeshContainer = (D3DXMESHCONTAINER_DERIVED*)pMeshContainerBase; SAFE_DELETE_ARRAY(pMeshContainer->Name); SAFE_DELETE_ARRAY(pMeshContainer->pAdjacency); SAFE_DELETE_ARRAY(pMeshContainer->pMaterials); SAFE_DELETE_ARRAY(pMeshContainer->pBoneOffsetMatrices); // release all the allocated textures if (pMeshContainer->ppTextures != NULL) { for (iMaterial = 0; iMaterial < pMeshContainer->NumMaterials; iMaterial++) { SAFE_RELEASE(pMeshContainer->ppTextures[iMaterial]); } } SAFE_DELETE_ARRAY(pMeshContainer->ppTextures); SAFE_DELETE_ARRAY(pMeshContainer->ppBoneMatrixPtrs); SAFE_RELEASE(pMeshContainer->pBoneCombinationBuf); SAFE_RELEASE(pMeshContainer->MeshData.pMesh); SAFE_RELEASE(pMeshContainer->pSkinInfo); SAFE_RELEASE(pMeshContainer->pOrigMesh); SAFE_DELETE(pMeshContainer); return S_OK; } void UpdateFrameMatrices(LPD3DXFRAME pFrameBase, LPD3DXMATRIX pParentMatrix) { D3DXFRAME_DERIVED* pFrame = (D3DXFRAME_DERIVED*)pFrameBase; if (pParentMatrix != NULL) D3DXMatrixMultiply(&pFrame->CombinedTransformationMatrix, &pFrame->TransformationMatrix, pParentMatrix); else pFrame->CombinedTransformationMatrix = pFrame->TransformationMatrix; if (pFrame->pFrameSibling != NULL) { UpdateFrameMatrices(pFrame->pFrameSibling, pParentMatrix); } if (pFrame->pFrameFirstChild != NULL) { UpdateFrameMatrices(pFrame->pFrameFirstChild, &pFrame->CombinedTransformationMatrix); } } float d3d::GetRandomFloat(float lowBound, float highBound) { if (lowBound >= highBound) // bad input return lowBound; // get random float in [0, 1] interval float f = (rand() % 10000) * 0.0001f; // return float in [lowBound, highBound] interval. return (f * (highBound - lowBound)) + lowBound; } void d3d::GetRandomVector( D3DXVECTOR3* out, D3DXVECTOR3* min, D3DXVECTOR3* max) { out->x = GetRandomFloat(min->x, max->x); out->y = GetRandomFloat(min->y, max->y); out->z = GetRandomFloat(min->z, max->z); } DWORD d3d::FtoDw(float f) { return *((DWORD*)&f); } float d3d::Lerp(float a, float b, float t) { return a - (a*t) + (b*t); } <file_sep>/network.h #define WIN32_LEAN_AND_MEAN #pragma comment (lib, "ws2_32.lib") #include "d3dUtility.h" #include "..\\..\\Server\\Access Server\\protocol.h" #define BUF_SIZE 1024 #define WM_SOCKET WM_USER + 1<file_sep>/PathFinder.cpp #include "PathFinder.h" PathFinder::PathFinder(Map * pMap){ m_pRMap = pMap; for (int y = 0; y < MAX_X_SIZE; ++y){ for (int x = 0; x < MAX_Y_SIZE; ++x){ m_map.m_tile[x][y] = pMap->m_tile[x][y]; } } } PathFinder::~PathFinder(){ } int PathFinder::FindPath(float startX, float startY, float destinationX, float destinationY, std::vector<Node_2D *> * saveVector){ // FindNearlist Tile int stx = startX / SIZE_TILE; int sty = startY / SIZE_TILE; int desx = destinationX / SIZE_TILE; int desy = destinationY / SIZE_TILE; // Check Range if (stx < 0 || stx > MAX_X_SIZE || sty < 0 || sty > MAX_Y_SIZE || desx < 0 || desx > MAX_X_SIZE || desy < 0 || desy > MAX_Y_SIZE) return OUT; // Check Destination Able if (m_map.m_tile[desx][desy] == DABLE){ return FAULT; } // Check Need PathFind if (abs(stx - desx) < 1.0f && abs(sty - desy) < 1.0f){ return DES; } // Ready PathFind int hCost = 0; Node_2D * pCurr; Node_2D * pPred; pPred = new Node_2D(); pPred->m_x = stx; pPred->m_y = sty; pPred->m_Hcost = hCost; pPred->m_Gcost = (float) (abs(pPred->m_x - desx) * abs(pPred->m_x - desx)) + (abs(pPred->m_y - desy) * abs(pPred->m_y - desy)); pPred->m_Fcost = pPred->m_Hcost + pPred->m_Gcost; pPred->m_parent = NULL; pPred->m_direction = ROOT; pPred->m_used = true; m_path.push_back(pPred); pCurr = NULL; int bestx = stx; int besty = sty; while (pPred->m_x != desx || pPred->m_y != desy){ //** 팔방을 확인해서 배열에 Cost값대로 넣는다. **// // 좌측 확인 // if (0 < pPred->m_x) { if (m_map.m_tile[pPred->m_x - 1][pPred->m_y] != DABLE){ pCurr = new Node_2D(); pCurr->m_x = pPred->m_x - 1; pCurr->m_y = pPred->m_y; pCurr->m_parent = pPred; pCurr->m_direction = LEFT; pCurr->m_used = false; pCurr->m_Hcost = pPred->m_Hcost + 1; pCurr->m_Gcost = (float)(abs(pCurr->m_x - desx) * abs(pCurr->m_x - desx)) + (abs(pCurr->m_y - desy) * abs(pCurr->m_y - desy)); pCurr->m_Fcost = pCurr->m_Hcost + pCurr->m_Gcost; if (m_map.m_tile[pCurr->m_x][pCurr->m_y] == USED){ Node_2D * pNode = FindNode(pCurr->m_x, pCurr->m_y); if (!pNode){ InsertNode(pCurr); } else if (pCurr->m_Fcost < pNode->m_Fcost){ pNode->m_Hcost = pCurr->m_Hcost; pNode->m_Gcost = pCurr->m_Gcost; pNode->m_Fcost = pCurr->m_Fcost; pNode->m_parent = pCurr->m_parent; pNode->m_direction = pCurr->m_direction; pNode->m_used = false; delete pCurr; } } else{ InsertNode(pCurr); m_map.m_tile[pCurr->m_x][pCurr->m_y] = USED; } } } // 우측 확인 // if (MAX_X_SIZE > pPred->m_x) { if (m_map.m_tile[pPred->m_x + 1][pPred->m_y] != DABLE){ pCurr = new Node_2D(); pCurr->m_x = pPred->m_x + 1; pCurr->m_y = pPred->m_y; pCurr->m_parent = pPred; pCurr->m_direction = RIGHT; pCurr->m_used = false; pCurr->m_Hcost = pPred->m_Hcost + 1; pCurr->m_Gcost = (float)(abs(pCurr->m_x - desx) * abs(pCurr->m_x - desx)) + (abs(pCurr->m_y - desy) * abs(pCurr->m_y - desy)); pCurr->m_Fcost = pCurr->m_Hcost + pCurr->m_Gcost; if (m_map.m_tile[pCurr->m_x][pCurr->m_y] == USED){ Node_2D * pNode = FindNode(pCurr->m_x, pCurr->m_y); if (!pNode){ InsertNode(pCurr); } else if (pCurr->m_Fcost < pNode->m_Fcost){ pNode->m_Hcost = pCurr->m_Hcost; pNode->m_Gcost = pCurr->m_Gcost; pNode->m_Fcost = pCurr->m_Fcost; pNode->m_parent = pCurr->m_parent; pNode->m_direction = pCurr->m_direction; pNode->m_used = false; delete pCurr; } } else{ InsertNode(pCurr); m_map.m_tile[pCurr->m_x][pCurr->m_y] = USED; } } } // 상단 확인 if (0 < pPred->m_y) { if (m_map.m_tile[pPred->m_x][pPred->m_y - 1] != DABLE){ pCurr = new Node_2D(); pCurr->m_x = pPred->m_x; pCurr->m_y = pPred->m_y - 1; pCurr->m_parent = pPred; pCurr->m_direction = UP; pCurr->m_used = false; pCurr->m_Hcost = pPred->m_Hcost + 1; pCurr->m_Gcost = (float)(abs(pCurr->m_x - desx) * abs(pCurr->m_x - desx)) + (abs(pCurr->m_y - desy) * abs(pCurr->m_y - desy)); pCurr->m_Fcost = pCurr->m_Hcost + pCurr->m_Gcost; if (m_map.m_tile[pCurr->m_x][pCurr->m_y] == USED){ Node_2D * pNode = FindNode(pCurr->m_x, pCurr->m_y); if (!pNode){ InsertNode(pCurr); } else if (pCurr->m_Fcost < pNode->m_Fcost){ pNode->m_Hcost = pCurr->m_Hcost; pNode->m_Gcost = pCurr->m_Gcost; pNode->m_Fcost = pCurr->m_Fcost; pNode->m_parent = pCurr->m_parent; pNode->m_direction = pCurr->m_direction; pNode->m_used = false; delete pCurr; } } else{ InsertNode(pCurr); m_map.m_tile[pCurr->m_x][pCurr->m_y] = USED; } } } // 하단 확인 if (MAX_Y_SIZE > pPred->m_y) { if (m_map.m_tile[pPred->m_x][pPred->m_y + 1] != DABLE){ pCurr = new Node_2D(); pCurr->m_x = pPred->m_x; pCurr->m_y = pPred->m_y + 1; pCurr->m_parent = pPred; pCurr->m_direction = DOWN; pCurr->m_used = false; pCurr->m_Hcost = pPred->m_Hcost + 1; pCurr->m_Gcost = (float)(abs(pCurr->m_x - desx) * abs(pCurr->m_x - desx)) + (abs(pCurr->m_y - desy) * abs(pCurr->m_y - desy)); pCurr->m_Fcost = pCurr->m_Hcost + pCurr->m_Gcost; if (m_map.m_tile[pCurr->m_x][pCurr->m_y] == USED){ Node_2D * pNode = FindNode(pCurr->m_x, pCurr->m_y); if (!pNode){ InsertNode(pCurr); } else if (pCurr->m_Fcost < pNode->m_Fcost){ pNode->m_Hcost = pCurr->m_Hcost; pNode->m_Gcost = pCurr->m_Gcost; pNode->m_Fcost = pCurr->m_Fcost; pNode->m_parent = pCurr->m_parent; pNode->m_direction = pCurr->m_direction; pNode->m_used = false; delete pCurr; } } else{ InsertNode(pCurr); m_map.m_tile[pCurr->m_x][pCurr->m_y] = USED; } } // 좌상 확인 if (0 < pPred->m_x && 0 < pPred->m_y){ if (m_map.m_tile[pPred->m_x - 1][pPred->m_y] != DABLE && m_map.m_tile[pPred->m_x][pPred->m_y - 1] != DABLE && m_map.m_tile[pPred->m_x - 1][pPred->m_y - 1] != DABLE){ pCurr = new Node_2D(); pCurr->m_x = pPred->m_x - 1; pCurr->m_y = pPred->m_y - 1; pCurr->m_parent = pPred; pCurr->m_direction = LUP; pCurr->m_used = false; pCurr->m_Hcost = pPred->m_Hcost + 1.5; pCurr->m_Gcost = (float)(abs(pCurr->m_x - desx) * abs(pCurr->m_x - desx)) + (abs(pCurr->m_y - desy) * abs(pCurr->m_y - desy)); pCurr->m_Fcost = pCurr->m_Hcost + pCurr->m_Gcost; if (m_map.m_tile[pCurr->m_x][pCurr->m_y] == USED){ Node_2D * pNode = FindNode(pCurr->m_x, pCurr->m_y); if (!pNode){ InsertNode(pCurr); } else if (pCurr->m_Fcost < pNode->m_Fcost){ pNode->m_Hcost = pCurr->m_Hcost; pNode->m_Gcost = pCurr->m_Gcost; pNode->m_Fcost = pCurr->m_Fcost; pNode->m_parent = pCurr->m_parent; pNode->m_direction = pCurr->m_direction; pNode->m_used = false; delete pCurr; } } else{ InsertNode(pCurr); m_map.m_tile[pCurr->m_x][pCurr->m_y] = USED; } } // 우상 확인 if (513 > pPred->m_x && 0 < pPred->m_y){ if (m_map.m_tile[pPred->m_x + 1][pPred->m_y] != DABLE && m_map.m_tile[pPred->m_x][pPred->m_y - 1] != DABLE && m_map.m_tile[pPred->m_x + 1][pPred->m_y - 1] != DABLE){ pCurr = new Node_2D(); pCurr->m_x = pPred->m_x + 1; pCurr->m_y = pPred->m_y - 1; pCurr->m_parent = pPred; pCurr->m_direction = RUP; pCurr->m_used = false; pCurr->m_Hcost = pPred->m_Hcost + 1.5; pCurr->m_Gcost = (float)(abs(pCurr->m_x - desx) * abs(pCurr->m_x - desx)) + (abs(pCurr->m_y - desy) * abs(pCurr->m_y - desy)); pCurr->m_Fcost = pCurr->m_Hcost + pCurr->m_Gcost; if (m_map.m_tile[pCurr->m_x][pCurr->m_y] == USED){ Node_2D * pNode = FindNode(pCurr->m_x, pCurr->m_y); if (!pNode){ InsertNode(pCurr); } else if (pCurr->m_Fcost < pNode->m_Fcost){ pNode->m_Hcost = pCurr->m_Hcost; pNode->m_Gcost = pCurr->m_Gcost; pNode->m_Fcost = pCurr->m_Fcost; pNode->m_parent = pCurr->m_parent; pNode->m_direction = pCurr->m_direction; pNode->m_used = false; delete pCurr; } } else{ InsertNode(pCurr); m_map.m_tile[pCurr->m_x][pCurr->m_y] = USED; } } } // 좌하 확인 if (0 < pPred->m_x && 513 > pPred->m_y){ if (m_map.m_tile[pPred->m_x - 1][pPred->m_y] != DABLE && m_map.m_tile[pPred->m_x][pPred->m_y + 1] != DABLE && m_map.m_tile[pPred->m_x - 1][pPred->m_y + 1] != DABLE){ pCurr = new Node_2D(); pCurr->m_x = pPred->m_x - 1; pCurr->m_y = pPred->m_y + 1; pCurr->m_parent = pPred; pCurr->m_direction = LDW; pCurr->m_used = false; pCurr->m_Hcost = pPred->m_Hcost + 1.5; pCurr->m_Gcost = (float)(abs(pCurr->m_x - desx) * abs(pCurr->m_x - desx)) + (abs(pCurr->m_y - desy) * abs(pCurr->m_y - desy)); pCurr->m_Fcost = pCurr->m_Hcost + pCurr->m_Gcost; if (m_map.m_tile[pCurr->m_x][pCurr->m_y] == USED){ Node_2D * pNode = FindNode(pCurr->m_x, pCurr->m_y); if (!pNode){ InsertNode(pCurr); } else if (pCurr->m_Fcost < pNode->m_Fcost){ pNode->m_Hcost = pCurr->m_Hcost; pNode->m_Gcost = pCurr->m_Gcost; pNode->m_Fcost = pCurr->m_Fcost; pNode->m_parent = pCurr->m_parent; pNode->m_direction = pCurr->m_direction; pNode->m_used = false; delete pCurr; } } else{ InsertNode(pCurr); m_map.m_tile[pCurr->m_x][pCurr->m_y] = USED; } } } // 우하 확인 if (513 > pPred->m_x && 513 > pPred->m_y){ if (m_map.m_tile[pPred->m_x + 1][pPred->m_y] != DABLE && m_map.m_tile[pPred->m_x][pPred->m_y + 1] != DABLE && m_map.m_tile[pPred->m_x + 1][pPred->m_y + 1] != DABLE){ pCurr = new Node_2D(); pCurr->m_x = pPred->m_x + 1; pCurr->m_y = pPred->m_y + 1; pCurr->m_parent = pPred; pCurr->m_direction = RDW; pCurr->m_used = false; pCurr->m_Hcost = pPred->m_Hcost + 1.5; pCurr->m_Gcost = (float)(abs(pCurr->m_x - desx) * abs(pCurr->m_x - desx)) + (abs(pCurr->m_y - desy) * abs(pCurr->m_y - desy)); pCurr->m_Fcost = pCurr->m_Hcost + pCurr->m_Gcost; if (m_map.m_tile[pCurr->m_x][pCurr->m_y] == USED){ Node_2D * pNode = FindNode(pCurr->m_x, pCurr->m_y); if (!pNode){ InsertNode(pCurr); } else if (pCurr->m_Fcost < pNode->m_Fcost){ pNode->m_Hcost = pCurr->m_Hcost; pNode->m_Gcost = pCurr->m_Gcost; pNode->m_Fcost = pCurr->m_Fcost; pNode->m_parent = pCurr->m_parent; pNode->m_direction = pCurr->m_direction; pNode->m_used = false; delete pCurr; } } else{ InsertNode(pCurr); m_map.m_tile[pCurr->m_x][pCurr->m_y] = USED; } } } } } pPred->m_used = true; // 사방을 확인하였으니 아제 새로운 Pred를 선출한다. // 선출 방법은 배열에서 사용되지 않은 가장 F_Cost값이 작은 노드를 선발한다. pPred = FindPred(); if (!pPred){ return FAIL; } } // 검색을 성공적으로 마쳤으면 해당 노드 인덱스를 리턴하고 노드들을 원상복귀한다. // return Value; //std::cout << " PathSize : " << m_path.size(); for (int i = 0; i < saveVector->size(); ++i){ delete *saveVector->begin(); saveVector->erase(saveVector->begin()); } Node_2D * pNode = new Node_2D(); pNode->m_x = pPred->m_x * 10; pNode->m_y = pPred->m_y * 10; pNode->m_direction = pPred->m_direction; saveVector->push_back(pNode); pPred = pPred->m_parent; while (pPred->m_parent != ROOT){ pNode = new Node_2D(); pNode->m_x = pPred->m_x *10; pNode->m_y = pPred->m_y *10; pNode->m_direction = pPred->m_direction; saveVector->push_back(pNode); pPred = pPred->m_parent; } //std::cout << " RSize : " << saveVector->size() << std::endl; ClearNode(); return SUCCESS; } Node_2D * PathFinder::FindNode(int x, int y){ for (auto i = m_path.begin(); i != m_path.end(); ++i){ if ((*i)->m_x == x && (*i)->m_y == y) return (*i); } return NULL; } Node_2D * PathFinder::FindPred(void){ for (auto i = m_path.begin(); i != m_path.end(); ++i){ if (!(*i)->m_used) return (*i); } return NULL; } void PathFinder::InsertNode(Node_2D * newNode){ for (auto i = m_path.begin(); i != m_path.end(); ++i){ if ((*i)->m_Fcost > newNode->m_Fcost){ m_path.insert(i, newNode); return; } } m_path.push_back(newNode); } void PathFinder::ClearNode(void){ int size = m_path.size(); int x; int y; for (int i = 0; i < size; ++i){ x = (*m_path.begin())->m_x; y = (*m_path.begin())->m_y; m_map.m_tile[x][y] = m_pRMap->m_tile[x][y]; delete * m_path.begin(); m_path.erase(m_path.begin()); } } bool KeyDown(int nVirtKey) { if ((GetKeyState(nVirtKey) & 0x8000) != 0) return true; else return false; }<file_sep>/BoundingBox.h #include <d3dx9.h> const float Infinity = FLT_MAX; struct BoundingBox { BoundingBox(); bool isPointInside(D3DXVECTOR3& p); D3DXVECTOR3 _min; D3DXVECTOR3 _max; };<file_sep>/AlienOwnedStates.h #pragma once #include "State.h" #include "PathFinder.h" class AlienSoldier; static Map m_Map; static PathFinder m_pathFinder(&m_Map); class Stand : public State<AlienSoldier> { private: Stand(){} //copy ctor and assignment should be private Stand(const Stand&); Stand& operator=(const Stand&); public: static Stand* Instance(); public: virtual void Enter(AlienSoldier* alien); virtual void Execute(AlienSoldier* alien); virtual void Exit(AlienSoldier* alien); }; class TraceEnemy : public State<AlienSoldier> { private: TraceEnemy(){} //copy ctor and assignment should be private TraceEnemy(const TraceEnemy&); TraceEnemy& operator=(const TraceEnemy&); public: static TraceEnemy* Instance(); virtual void Enter(AlienSoldier* Alien); virtual void Execute(AlienSoldier* Alien); virtual void Exit(AlienSoldier* Alien); }; class AttackEnemy : public State<AlienSoldier> { private: AttackEnemy(){} //copy ctor and assignment should be private AttackEnemy(const AttackEnemy&); AttackEnemy& operator=(const AttackEnemy&); public: static AttackEnemy* Instance(); virtual void Enter(AlienSoldier* Alien); virtual void Execute(AlienSoldier* Alien); virtual void Exit(AlienSoldier* Alien); }; class Dead : public State<AlienSoldier> { private: Dead(){} //copy ctor and assignment should be private Dead(const Dead&); Dead& operator=(const Dead&); public: static Dead* Instance(); virtual void Enter(AlienSoldier* Alien); virtual void Execute(AlienSoldier* Alien); virtual void Exit(AlienSoldier* Alien); }; class Damaged : public State<AlienSoldier> { private: Damaged(){} //copy ctor and assignment should be private Damaged(const Damaged&); Damaged& operator=(const Damaged&); public: static Damaged* Instance(); virtual void Enter(AlienSoldier* Alien); virtual void Execute(AlienSoldier* Alien); virtual void Exit(AlienSoldier* Alien); };<file_sep>/State.h #pragma once template <class entity_type> class State { public: virtual ~State(){} //this will execute when the state is entered virtual void Enter(entity_type*)=0; //this is the states normal update function virtual void Execute(entity_type*)=0; //this will execute when the state is exited. (My word, isn't //life full of surprises... ;o)) virtual void Exit(entity_type*)=0; }; struct Vector3 { float x; float y; float z; };<file_sep>/Map.h #pragma once #include <math.h> #include <Windows.h> #define MAX_X_SIZE 1000//예 맵이 5000이면 노드를 10으로 잡는다면 5000/10 #define MAX_Y_SIZE 1000 #define DABLE 1 #define ABLE 2 #define USED 3 class Map{ public: BYTE m_tile[MAX_X_SIZE][MAX_Y_SIZE]; Map(){ for (int i = 0; i < MAX_X_SIZE; ++i){ for (int j = 0; j < MAX_Y_SIZE; ++j){ m_tile[MAX_X_SIZE][MAX_Y_SIZE] = rand() % 2 + 1; } } }; };<file_sep>/xfile.cpp ////////////////////////////////////////////////////////////////////////////////////////////////// // // File: xfile.cpp // // Author: <NAME> (C) All Rights Reserved // // System: AMD Athlon 1800+ XP, 512 DDR, Geforce 3, Windows XP, MSVC++ 7.0 // // Desc: Demonstrates how to load and render an XFile. // ////////////////////////////////////////////////////////////////////////////////////////////////// #include "d3dUtility.h" #include <vector> #include "camera.h" #include "CModel.h" #include "Player.h" #include "network.h" #include "AlienSoldier.h" #include "SkyBox.h" #include "Effect.h" #include "Billboard.h" #include <fstream> using namespace std; #define SEND_PACKET_TIME 0.03 #define ROAD_HEIGHT 15 #define START_TEXTURE_WIDTH 800 #define START_TEXTURE_HEIGHT 480 // // Globals // IDirect3DDevice9* Device = 0; LPDIRECTINPUT8 g_pDInput; LPDIRECTINPUTDEVICE8 g_pDIKeyboard; LPDIRECTINPUTDEVICE8 g_pDIMouse; LPD3DXSPRITE pSprite; LPDIRECT3DTEXTURE9 g_pTexture; LPDIRECT3DTEXTURE9 g_pStartTexture; LPDIRECT3DTEXTURE9 g_pHpBar; LPDIRECT3DTEXTURE9 g_pHp; LPDIRECT3DTEXTURE9 g_pRespawn; LPDIRECT3DTEXTURE9 g_pRespawnBar; LPDIRECT3DTEXTURE9 g_pRespawnFont; LPD3DXFONT pFonts = NULL; CAllocateHierarchy Alloc; LPD3DXFRAME g_pFrameRoot; LPD3DXANIMATIONCONTROLLER g_pAnimController; CPlayer player; CPlayer skelaton[MAX_USER]; Effect effect; CModel startMap; CModel stageMap1; CModel stageMap2; CModel stageMap3; CModel stageMap4; AlienSoldier alien[NUM_OF_MONSTER]; HWND main_window_handle; HINSTANCE hInst; Billboard blood; Billboard nextStage; Billboard lightEffect; CModel stage1UI; CModel stage2UI; CModel stage3UI; CModel stage4UI; ifstream file; const int Width = 1068; const int Height = 768; float sendTime = 0.0f; Camera TheCamera(Camera::LANDOBJECT); SkyBox skyBox; SOCKET g_mysocket; WSABUF send_wsabuf; char send_buffer[BUF_SIZE]; WSABUF recv_wsabuf; char recv_buffer[BUF_SIZE]; char packet_buffer[BUF_SIZE]; DWORD in_packet_size = 0; int saved_packet_size = 0; int g_myid; DIMOUSESTATE mouseState; BYTE g_KeyboardState[256]; POINT windowPt; bool start = false; // // Framework functions // bool IsTimePassed(float duringTime, float timeDelta) { static float startTime = 0.0f; startTime += timeDelta; if (startTime > duringTime) { startTime = 0.0f; return true; } else return false; } bool connectServer(HWND main_window_handle) { file.open("ip.txt"); char ipBuf[64]; if (file.is_open()) { while (!file.eof()) file >> ipBuf; } file.close(); WSADATA wsadata; WSAStartup(MAKEWORD(2, 2), &wsadata); g_mysocket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0); SOCKADDR_IN ServerAddr; ZeroMemory(&ServerAddr, sizeof(SOCKADDR_IN)); ServerAddr.sin_family = AF_INET; ServerAddr.sin_port = htons(MY_SERVER_PORT); ServerAddr.sin_addr.s_addr = inet_addr(ipBuf); int Result = WSAConnect(g_mysocket, (sockaddr *)&ServerAddr, sizeof(ServerAddr), NULL, NULL, NULL, NULL); Result = WSAAsyncSelect(g_mysocket, main_window_handle, WM_SOCKET, FD_CLOSE | FD_READ); send_wsabuf.buf = send_buffer; send_wsabuf.len = BUF_SIZE; recv_wsabuf.buf = recv_buffer; recv_wsabuf.len = BUF_SIZE; return 0; } void ProcessPacket(char *ptr) { static bool first_time = true; sc_packet_put_player *put_packet = reinterpret_cast<sc_packet_put_player *>(ptr); sc_packet_pos *pos_packet = reinterpret_cast<sc_packet_pos *>(ptr); sc_packet_monster *mons_packet = reinterpret_cast<sc_packet_monster *>(ptr); sc_packet_dead_player *dead_player_packet = reinterpret_cast<sc_packet_dead_player *>(ptr); sc_packet_respawn_player *respawn_packet = reinterpret_cast<sc_packet_respawn_player*>(ptr); int id; switch (ptr[1]) { case SC_PUT_PLAYER: id = put_packet->id; if (first_time) { first_time = false; g_myid = id; } if (id == g_myid) { player.setPos(D3DXVECTOR3(put_packet->x, put_packet->y, put_packet->z)); player.setDrawPlayer(true); } else if (id < NPC_START) { skelaton[id].setPos(D3DXVECTOR3(put_packet->x, put_packet->y, put_packet->z)); skelaton[id].loadModel(L"suit\\suit_A_v3.X", Device); skelaton[id].setDrawPlayer(true); } break; case SC_POS: id = pos_packet->id; if (id == g_myid) { /* D3DXVECTOR3 vec; vec.x = my_packet->x; vec.y = my_packet->y; vec.z = my_packet->z; vec -= player.getPos(); if (D3DXVec3Length(&vec) > 1.0f) player.setPos(D3DXVECTOR3(my_packet->x, my_packet->y, my_packet->z));*/ player.setPos(D3DXVECTOR3(pos_packet->x, pos_packet->y, pos_packet->z)); player.setHp(pos_packet->hp); if (pos_packet->onLoad) { D3DXVECTOR3 pos(player.getPos()); pos.y += ROAD_HEIGHT; player.setPos(pos); } } else if (id < NPC_START) { skelaton[id].setPos(D3DXVECTOR3(pos_packet->x, pos_packet->y, pos_packet->z)); skelaton[id].setSkelatonDirection(D3DXVECTOR3(pos_packet->dx, pos_packet->dy, pos_packet->dz)); skelaton[id].setState(pos_packet->animState); if (pos_packet->onLoad) { D3DXVECTOR3 pos(skelaton[id].getPos()); pos.y += ROAD_HEIGHT; skelaton[id].setPos(pos); } } // else { // npc[other_id - NPC_START].x = my_packet->x; // npc[other_id - NPC_START].y = my_packet->y; // } break; case SC_MONSTER: alien[mons_packet->id].setPos(D3DXVECTOR3(mons_packet->x, mons_packet->y, mons_packet->z)); alien[mons_packet->id].setTraceEnemyPos(D3DXVECTOR3(mons_packet->tx, mons_packet->ty, mons_packet->tz)); alien[mons_packet->id].setState(mons_packet->state); alien[mons_packet->id].setAlive(mons_packet->alive); alien[mons_packet->id].setType(mons_packet->monsterType); break; case SC_DEAD_PLAYER: id = dead_player_packet->id; if (id == g_myid) player.setState(PLAYER_DEAD); else if (id < NPC_START) skelaton[id].setState(PLAYER_DEAD); break; case SC_RESPAWN_PLAYER: id = respawn_packet->id; if (id == g_myid) { player.setPos(D3DXVECTOR3(respawn_packet->x, respawn_packet->y, respawn_packet->z)); player.setHp(respawn_packet->hp); player.setState(respawn_packet->animState); player.initPlayerModel(); } else if (id < NPC_START) { skelaton[id].setPos(D3DXVECTOR3(respawn_packet->x, respawn_packet->y, respawn_packet->z)); skelaton[id].setHp(respawn_packet->hp); skelaton[id].setState(respawn_packet->animState); skelaton[id].initPlayerModel(); } break; //case SC_REMOVE_PLAYER: // sc_packet_remove_player *my_packet = reinterpret_cast<sc_packet_remove_player *>(ptr); // int other_id = my_packet->id; // if (other_id == g_myid) { // player.attr &= ~BOB_ATTR_VISIBLE; // } // else if (other_id < NPC_START) { // skelaton[other_id].attr &= ~BOB_ATTR_VISIBLE; // } // else { // npc[other_id - NPC_START].attr &= ~BOB_ATTR_VISIBLE; // } // break; //case SC_CHAT: // sc_packet_chat *my_packet = reinterpret_cast<sc_packet_chat *>(ptr); // int other_id = my_packet->id; // if (other_id == g_myid) { // wcsncpy(player.message, my_packet->message, 256); // player.message_time = GetTickCount(); // } // else if (other_id < NPC_START) { // wcsncpy(skelaton[other_id].message, my_packet->message, 256); // skelaton[other_id].message_time = GetTickCount(); // } // else { // wcsncpy(npc[other_id - NPC_START].message, my_packet->message, 256); // npc[other_id - NPC_START].message_time = GetTickCount(); // } // break; //default: //printf("Unknown PACKET type [%d]\n", ptr[1]); } } void ReadPacket(SOCKET sock) { DWORD iobyte, ioflag = 0; int ret = WSARecv(sock, &recv_wsabuf, 1, &iobyte, &ioflag, NULL, NULL); if (ret) { int err_code = WSAGetLastError(); printf("Recv Error [%d]\n", err_code); } BYTE *ptr = reinterpret_cast<BYTE *>(recv_buffer); while (0 != iobyte) { if (0 == in_packet_size) in_packet_size = ptr[0]; if (iobyte + saved_packet_size >= in_packet_size) { memcpy(packet_buffer + saved_packet_size, ptr, in_packet_size - saved_packet_size); ProcessPacket(packet_buffer); ptr += in_packet_size - saved_packet_size; iobyte -= in_packet_size - saved_packet_size; in_packet_size = 0; saved_packet_size = 0; } else { memcpy(packet_buffer + saved_packet_size, ptr, iobyte); saved_packet_size += iobyte; iobyte = 0; } } } d3d::Ray CalcPickingRay(int x, int y) { float px = 0.0f; float py = 0.0f; D3DVIEWPORT9 vp; Device->GetViewport(&vp); D3DXMATRIX proj; Device->GetTransform(D3DTS_PROJECTION, &proj); px = (((2.0f*x) / vp.Width) - 1.0f) / proj(0, 0); py = (((-2.0f*y) / vp.Height) + 1.0f) / proj(1, 1); d3d::Ray ray; ray._origin = D3DXVECTOR3(0.0f, 0.0f, 0.0f); ray._direction = D3DXVECTOR3(px, py, 1.0f); return ray; } void TransformRay(d3d::Ray* ray, D3DXMATRIX* T) { // transform the ray's origin, w = 1. D3DXVec3TransformCoord( &ray->_origin, &ray->_origin, T); // transform the ray's direction, w = 0. D3DXVec3TransformNormal( &ray->_direction, &ray->_direction, T); // normalize the direction D3DXVec3Normalize(&ray->_direction, &ray->_direction); } bool RaySphereIntTest(d3d::Ray* ray, d3d::BoundingSphere* sphere) { D3DXVECTOR3 v = ray->_origin - sphere->_center; float b = 2.0f * D3DXVec3Dot(&ray->_direction, &v); float c = D3DXVec3Dot(&v, &v) - (sphere->_radius * sphere->_radius); // find the discriminant float discriminant = (b * b) - (4.0f * c); // test for imaginary number if (discriminant < 0.0f) return false; discriminant = sqrtf(discriminant); float s0 = (-b + discriminant) / 2.0f; float s1 = (-b - discriminant) / 2.0f; // if a solution is >= 0, then we intersected the sphere if (s0 >= 0.0f || s1 >= 0.0f) return true; return false; } void clienterror(void) { exit(-1); } bool Setup() { HRESULT hr = 0; connectServer(main_window_handle); // // Load the XFile data. // blood.loadTexture(L"effect\\blood.png", Device); blood.createQuad(Device, 16, 4, 4); //blood.scaleBillboard(2.0f, 2.0f, 2.0f); blood.setAnimTime(0.2f); nextStage.loadTexture(L"effect\\nextStage.png", Device); nextStage.createQuad(Device, 16, 4, 4); nextStage.setAnimTime(1.0f); player.loadModel(L"suit\\suit_A_v3.X", Device); alien[0].loadModel(L"mob\\AlienSoldier_v8_b.X", Device); alien[1].loadModel(L"mob\\AlienSoldier_v8_w.X", Device); for (int i = 2; i < NUM_OF_MONSTER; ++i) { if (alien[i].getType() == 0) alien[i].setMesh(alien[0].getFrame(), alien[0].getAnimController()); else if (alien[i].getType() == 1) alien[i].setMesh(alien[1].getFrame(), alien[1].getAnimController()); } skyBox.loadModel(L"etc\\sky_v1.X", Device); startMap.LoadXFile(L"map\\stage1.X", Device); stageMap1.LoadXFile(L"map\\stage2.X", Device); stageMap2.LoadXFile(L"map\\stage3.X", Device); stageMap3.LoadXFile(L"map\\stage4.X", Device); stageMap4.LoadXFile(L"map\\stage5.X", Device); D3DXCreateTextureFromFile(Device, L"etc\\crosshairs1.tga", &g_pTexture); D3DXCreateTextureFromFile(Device, L"etc\\startTexture.png", &g_pStartTexture); D3DXCreateTextureFromFile(Device, L"ui\\hp_bar.tga", &g_pHpBar); D3DXCreateTextureFromFile(Device, L"ui\\hp.tga", &g_pHp); D3DXCreateTextureFromFile(Device, L"ui\\respawn.png", &g_pRespawn); D3DXCreateTextureFromFile(Device, L"ui\\respawnbar.png", &g_pRespawnBar); D3DXCreateTextureFromFile(Device, L"ui\\respawnFont.png", &g_pRespawnFont); effect.loadEffect(L"effect\\muzzle_3.X", Device); lightEffect.loadTexture(L"effect\\Tex_Roiling_Blast2_SubUV_1024.tga", Device); lightEffect.createQuad(Device, 9, 3, 3); lightEffect.setAnimTime(0.5f); lightEffect.setPos(D3DXVECTOR3(0.0f, 200.0f, 0.0f)); stage1UI.LoadXFile(L"ui\\stage_A.X", Device); stage1UI.setScale(D3DXVECTOR3(1.5f, 1.5f, 1.5f)); stage1UI.setModelPosition(D3DXVECTOR3(0.0f, 30.0f, 500.0f)); D3DXMATRIX rotateMatrix; D3DXMatrixIdentity(&rotateMatrix); D3DXMatrixRotationYawPitchRoll(&rotateMatrix, -PI / 2, PI / 2, 0.0f); stage1UI.setworldMatrix(rotateMatrix * stage1UI.getworldMatrix()); stage2UI.LoadXFile(L"ui\\stage_A2.X", Device); stage2UI.setScale(D3DXVECTOR3(1.5f, 1.5f, 1.5f)); stage2UI.setModelPosition(D3DXVECTOR3(500.0f, 30.0f, -500.0f)); D3DXMatrixIdentity(&rotateMatrix); D3DXMatrixRotationYawPitchRoll(&rotateMatrix, 0, PI / 2, 0.0f); stage2UI.setworldMatrix(rotateMatrix * stage2UI.getworldMatrix()); stage3UI.LoadXFile(L"ui\\stage_A3.X", Device); stage3UI.setScale(D3DXVECTOR3(1.5f, 1.5f, 1.5f)); stage3UI.setModelPosition(D3DXVECTOR3(0.0f, 30.0f, -500.0f)); D3DXMatrixIdentity(&rotateMatrix); D3DXMatrixRotationYawPitchRoll(&rotateMatrix, PI / 2, PI / 2, 0.0f); stage3UI.setworldMatrix(rotateMatrix * stage3UI.getworldMatrix()); stage4UI.LoadXFile(L"ui\\stage_A4.X", Device); stage4UI.setScale(D3DXVECTOR3(1.5f, 1.5f, 1.5f)); stage4UI.setModelPosition(D3DXVECTOR3(500.0f, 30.0f, -500.0f)); D3DXMatrixIdentity(&rotateMatrix); D3DXMatrixRotationYawPitchRoll(&rotateMatrix, PI, PI / 2, 0.0f); stage4UI.setworldMatrix(rotateMatrix * stage4UI.getworldMatrix()); for (int i = 0; i < NUM_OF_MONSTER; ++i) alien[i].createSphere(Device); // // DirectInput Init // if(FAILED(DirectInput8Create(hInst, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&g_pDInput, NULL))) return E_FAIL; if (FAILED(g_pDInput->CreateDevice(GUID_SysMouse, &g_pDIMouse, NULL))) return E_FAIL; if (FAILED(g_pDInput->CreateDevice(GUID_SysKeyboard, &g_pDIKeyboard, NULL))) return E_FAIL; if (FAILED(g_pDIMouse->SetDataFormat(&c_dfDIMouse))) return E_FAIL; if (FAILED(g_pDIKeyboard->SetDataFormat(&c_dfDIKeyboard))) return E_FAIL; if (FAILED(g_pDIMouse->SetCooperativeLevel(main_window_handle, DISCL_NONEXCLUSIVE | DISCL_BACKGROUND))) return E_FAIL; if (FAILED(g_pDIKeyboard->SetCooperativeLevel(main_window_handle, DISCL_NONEXCLUSIVE | DISCL_BACKGROUND))) return E_FAIL; // // Set texture filters. // Device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); Device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); Device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT); // // Set Lights. // //TheTerrain = new Terrain(Device, "Map\\map256.raw", 256, 256, 20, 0.5f); //TheTerrain->loadTexture("Map\\tile_.dds"); D3DXVECTOR3 dir(1.0f, -1.0f, 1.0f); D3DXCOLOR col(0.8f, 0.8f, 0.8f, 0.8f); D3DLIGHT9 light = d3d::InitDirectionalLight(&dir, &col); D3DXVECTOR3 posLight(0.0f, 10000.0f, 1.0f); col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); light = d3d::InitPointLight(&posLight, &col); Device->SetLight(0, &light); Device->LightEnable(0, true); /*Device->SetLight(0, &light); Device->LightEnable(0, true);*/ dir = D3DXVECTOR3(0.0f, 1.0f, 0.0f); col = D3DXCOLOR(0.5f, 0.5f, 0.5f, 1.0f); light = d3d::InitDirectionalLight(&dir, &col); Device->SetLight(1, &light); Device->LightEnable(1, true); Device->SetRenderState(D3DRS_NORMALIZENORMALS, true); Device->SetRenderState(D3DRS_SPECULARENABLE, true); // // Set Fonts. // pFonts = d3d::InitFont(Device, pSprite); // // Set camera. // TheCamera.yaw(2 * 3.14f / 3); //TheCamera.yaw(-3.14f / 3); // // Set projection matrix. // D3DXMATRIX proj; D3DXMatrixPerspectiveFovLH( &proj, D3DX_PI * 0.5f, // 90 - degree (float)Width / (float)Height, 1.0f, 500000.0f); Device->SetTransform(D3DTS_PROJECTION, &proj); return true; } void Cleanup() { } bool Display(float timeDelta) { HRESULT hr; if(start) { sendTime += timeDelta; ShowCursor(false); RECT windowRect; GetWindowRect(main_window_handle, &windowRect); SetCursorPos(((windowRect.right - windowRect.left) / 2) + windowRect.left, ((windowRect.bottom - windowRect.top) / 2) + windowRect.top); DWORD iobyte; D3DXMATRIX world; D3DXVECTOR3 playerDirection; world = player.getWorldMatrix(); playerDirection.x = world._31; playerDirection.y = world._32; playerDirection.z = world._33; D3DXVec3Normalize(&playerDirection, &playerDirection); if (FAILED(g_pDIMouse->GetDeviceState(sizeof(DIMOUSESTATE), &mouseState))) { if (FAILED(g_pDIMouse->Acquire())) return E_FAIL; } if (FAILED(g_pDIKeyboard->GetDeviceState(sizeof(g_KeyboardState), &g_KeyboardState))) { if (FAILED(g_pDIKeyboard->Acquire())) return E_FAIL; } static int lastKeyDown = UP_KEY; if (g_KeyboardState[DIK_NUMPADENTER] & 0x80) { } if (g_KeyboardState[DIK_W] & 0x80 && player.getHp() > 0) { player.movePlayerPos(timeDelta); D3DXVECTOR3 lookVec; TheCamera.getLook(&lookVec); player.rotateYPlayer(-lookVec); player.setState(PLAYER_FRONT_RUN); if (sendTime > SEND_PACKET_TIME) { cs_packet_move *my_packet = reinterpret_cast<cs_packet_move *>(send_buffer); my_packet->size = sizeof(cs_packet_move); send_wsabuf.buf = send_buffer; send_wsabuf.len = sizeof(cs_packet_move); int ret = 0; my_packet->dx = playerDirection.x; my_packet->dy = playerDirection.y; my_packet->dz = playerDirection.z; my_packet->type = CS_MOVE; my_packet->time = timeDelta; my_packet->animState = player.getCurrAnimNum(); memcpy(&send_buffer, my_packet, my_packet->size); ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); ::MessageBox(NULL, L"Error while sending packet", NULL, MB_OK); } sendTime = 0.0f; } } else if (g_KeyboardState[DIK_S] & 0x80 && player.getHp() > 0) { player.movePlayerPos(timeDelta); D3DXVECTOR3 lookVec; TheCamera.getLook(&lookVec); player.rotateYPlayer(lookVec); if (sendTime > SEND_PACKET_TIME) { cs_packet_move *my_packet = reinterpret_cast<cs_packet_move *>(send_buffer); my_packet->size = sizeof(cs_packet_move); send_wsabuf.buf = send_buffer; send_wsabuf.len = sizeof(cs_packet_move); int ret = 0; my_packet->dx = playerDirection.x; my_packet->dy = playerDirection.y; my_packet->dz = playerDirection.z; my_packet->type = CS_MOVE; my_packet->time = timeDelta; my_packet->animState = player.getCurrAnimNum(); memcpy(&send_buffer, my_packet, my_packet->size); ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); ::MessageBox(NULL, L"Error while sending packet", NULL, MB_OK); } sendTime = 0.0f; } } else if (g_KeyboardState[DIK_A] & 0x80 && player.getHp() > 0) { player.movePlayerPos(timeDelta); D3DXVECTOR3 rightVec; TheCamera.getRight(&rightVec); player.rotateYPlayer(rightVec); player.setState(PLAYER_LEFT_RUN); if (sendTime > SEND_PACKET_TIME) { cs_packet_move *my_packet = reinterpret_cast<cs_packet_move *>(send_buffer); my_packet->size = sizeof(cs_packet_move); send_wsabuf.buf = send_buffer; send_wsabuf.len = sizeof(cs_packet_move); int ret = 0; my_packet->dx = playerDirection.x; my_packet->dy = playerDirection.y; my_packet->dz = playerDirection.z; my_packet->type = CS_MOVE; my_packet->time = timeDelta; my_packet->animState = player.getCurrAnimNum(); memcpy(&send_buffer, my_packet, my_packet->size); ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); ::MessageBox(NULL, L"Error while sending packet", NULL, MB_OK); } sendTime = 0.0f; } } else if (g_KeyboardState[DIK_D] & 0x80 && player.getHp() > 0) { player.movePlayerPos(timeDelta); D3DXVECTOR3 rightVec; TheCamera.getRight(&rightVec); player.rotateYPlayer(-rightVec); player.setState(PLAYER_RIGHT_RUN); if (sendTime > SEND_PACKET_TIME) { cs_packet_move *my_packet = reinterpret_cast<cs_packet_move *>(send_buffer); my_packet->size = sizeof(cs_packet_move); send_wsabuf.buf = send_buffer; send_wsabuf.len = sizeof(cs_packet_move); int ret = 0; my_packet->dx = playerDirection.x; my_packet->dy = playerDirection.y; my_packet->dz = playerDirection.z; my_packet->type = CS_MOVE; my_packet->time = timeDelta; my_packet->animState = player.getCurrAnimNum(); memcpy(&send_buffer, my_packet, my_packet->size); ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); ::MessageBox(NULL, L"Error while sending packet", NULL, MB_OK); } sendTime = 0.0f; } } else { if (sendTime > SEND_PACKET_TIME) { cs_packet_move *my_packet = reinterpret_cast<cs_packet_move *>(send_buffer); my_packet->size = sizeof(cs_packet_move); send_wsabuf.buf = send_buffer; send_wsabuf.len = sizeof(cs_packet_move); int ret = 0; my_packet->dx = playerDirection.x; my_packet->dy = playerDirection.y; my_packet->dz = playerDirection.z; my_packet->type = CS_STOP; my_packet->time = timeDelta; my_packet->animState = player.getCurrAnimNum(); memcpy(&send_buffer, my_packet, my_packet->size); ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); ::MessageBox(NULL, L"Error while sending packet", NULL, MB_OK); } sendTime = 0.0f; } player.stopPlayer(lastKeyDown); player.setState(PLAYER_STOP); } D3DXVECTOR3 cameralook; TheCamera.getLook(&cameralook); static float shootDelayTime = 0.0f; if (mouseState.rgbButtons[0] & 0x80 && player.getHp() > 0) { player.fireGun(true, -cameralook); POINT pt; GetCursorPos(&pt); ScreenToClient(main_window_handle, &pt); effect.setVisible(true); if (player.getState() == PLAYER_STOP) { D3DXVECTOR3 lookVec; TheCamera.getLook(&lookVec); player.rotateYPlayer(-lookVec); } // compute the ray in view space given the clicked screen point d3d::Ray ray = CalcPickingRay(pt.x + 10, pt.y + 20); // transform the ray to world space D3DXMATRIX view; Device->GetTransform(D3DTS_VIEW, &view); D3DXMATRIX viewInverse; D3DXMatrixInverse(&viewInverse, 0, &view); TransformRay(&ray, &viewInverse); for (int i = 0; i < NUM_OF_MONSTER; ++i) { if (RaySphereIntTest(&ray, &alien[i].getBodyBoundingSphere()) && alien[i].getAlive()) { if (shootDelayTime > SHOOT_DELAY_TIME || shootDelayTime == 0.0f) { float bloodX, bloodY, bloodZ; bloodX = alien[i].getModel().getworldMatrix()._41; bloodY = alien[i].getModel().getworldMatrix()._42 + 100.0f; bloodZ = alien[i].getModel().getworldMatrix()._43; blood.setPos(D3DXVECTOR3(bloodX, bloodY, bloodZ)); blood.setVisible(true); cs_packet_shot_monster *my_packet = reinterpret_cast<cs_packet_shot_monster *>(send_buffer); my_packet->size = sizeof(cs_packet_shot_monster); send_wsabuf.buf = send_buffer; send_wsabuf.len = sizeof(cs_packet_shot_monster); int ret = 0; my_packet->type = MON_DAMAGED_BODY; my_packet->id = i; memcpy(&send_buffer, my_packet, my_packet->size); ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); ::MessageBox(NULL, L"Error while sending packet", NULL, MB_OK); } shootDelayTime = 0.0f; } } else if (RaySphereIntTest(&ray, &alien[i].getHeadBoundingSphere()) && alien[i].getAlive()) { if (shootDelayTime > SHOOT_DELAY_TIME || shootDelayTime == 0.0f) { float bloodX, bloodY, bloodZ; bloodX = alien[i].getModel().getworldMatrix()._41; bloodY = alien[i].getModel().getworldMatrix()._42 + 150.0f; bloodZ = alien[i].getModel().getworldMatrix()._43; blood.setPos(D3DXVECTOR3(bloodX, bloodY, bloodZ)); blood.setVisible(true); cs_packet_shot_monster *my_packet = reinterpret_cast<cs_packet_shot_monster *>(send_buffer); my_packet->size = sizeof(cs_packet_shot_monster); send_wsabuf.buf = send_buffer; send_wsabuf.len = sizeof(cs_packet_shot_monster); int ret = 0; my_packet->type = MON_DAMAGED_HEAD; my_packet->id = i; memcpy(&send_buffer, my_packet, my_packet->size); ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); ::MessageBox(NULL, L"Error while sending packet", NULL, MB_OK); } shootDelayTime = 0.0f; } } } } else { player.setIsFire(false); effect.setVisible(false); player.setState(PLAYER_STOP); } shootDelayTime += timeDelta; for (int i = 0; i < NUM_OF_MONSTER; ++i) { if (ATTACK_STATE == alien[i].getState()) { static float startTime = 0.0f; startTime += timeDelta; if (startTime > 0.35f) { player.setState(PLAYER_DAMAGED); if (startTime > 0.5f) { cs_packet_damaged_player *my_packet = reinterpret_cast<cs_packet_damaged_player *>(send_buffer); my_packet->size = sizeof(cs_packet_damaged_player); send_wsabuf.buf = send_buffer; send_wsabuf.len = sizeof(cs_packet_damaged_player); int ret = 0; my_packet->type = CS_PLAYER_DAMAGED; my_packet->animState = PLAYER_DAMAGED; memcpy(&send_buffer, my_packet, my_packet->size); ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); ::MessageBox(NULL, L"Error while sending packet", NULL, MB_OK); } startTime = 0.0f; } } } } static float mouseMove = 0.0f; mouseMove -= (float)mouseState.lX * timeDelta / 2; D3DXVECTOR3 pos; TheCamera.getPosition(&pos); pos.x = player.getPos().x + 150.0f * cos(mouseMove); pos.y = player.getPos().y + 200.0f; pos.z = player.getPos().z + 150.0f * sin(mouseMove); TheCamera.setPosition(&pos); TheCamera.yaw(mouseState.lX * timeDelta / 2); TheCamera.pitch(mouseState.lY * timeDelta / 2); // Update the view matrix representing the cameras // new position/orientation. D3DXMATRIX V; TheCamera.getViewMatrix(&V); Device->SetTransform(D3DTS_VIEW, &V); // // Update: Rotate the mesh. // // // Render // Device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0); Device->BeginScene(); Device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); Device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); ////////////////////////////////////////////////////////////////////////////////////// //draw player.drawPlayer(Device, timeDelta); for (int i = 0; i < NUM_OF_MONSTER; ++i) { alien[i].moveAlienPos(timeDelta); alien[i].rotateAlien(); alien[i].drawSphere(Device); alien[i].drawAlien(Device, timeDelta); } skyBox.drawSkyBox(Device, timeDelta); startMap.Draw(Device, timeDelta); stageMap1.Draw(Device, timeDelta); stageMap2.Draw(Device, timeDelta); stageMap3.Draw(Device, timeDelta); stageMap4.Draw(Device, timeDelta); //////////////////////////////////////////////////////////////////////////////////////// for (auto i = 0; i < MAX_USER; ++i) { if (skelaton[i].getDrawPlayer()) { skelaton[i].setSkelatonPosition(timeDelta); skelaton[i].skelatonRotate(); skelaton[i].drawSkelaton(Device, timeDelta); } } D3DXVECTOR3 cameraPos; D3DXVECTOR3 playerPos; D3DXMATRIX playerWorld; D3DXMATRIX temp; TheCamera.getPosition(&cameraPos); cameraPos.y = 0.0f; D3DXMatrixIdentity(&playerWorld); D3DXMatrixRotationY(&temp, PI); playerWorld *= temp; playerPos.x = -25.0f; playerPos.y = 140.0f; playerPos.z = -100.0f; D3DXMatrixTranslation(&temp, playerPos.x, playerPos.y, playerPos.z); playerWorld *= temp; if (player.getState() == PLAYER_LEFT_RUN) { D3DXMatrixRotationY(&temp, PI / 2.15); playerWorld *= temp; } else if (player.getState() == PLAYER_RIGHT_RUN) { D3DXMatrixRotationY(&temp, -PI / 2.15); playerWorld *= temp; } temp = player.getWorldMatrix(); playerWorld *= temp; D3DXMATRIX camera; D3DXVECTOR3 tempVec; D3DXMatrixIdentity(&camera); TheCamera.getRight(&tempVec); camera._11 = tempVec.x; camera._21 = tempVec.y; camera._31 = tempVec.z; TheCamera.getLook(&tempVec); camera._13 = tempVec.x; camera._23 = tempVec.y; camera._33 = tempVec.z; D3DXMatrixInverse(&camera, NULL, &camera); blood.setMatrix(&camera); //ÀÌÆåÆ® ºí·»µù Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); Device->SetRenderState(D3DRS_ALPHABLENDENABLE, true); Device->SetRenderState(D3DRS_NORMALIZENORMALS, false); Device->SetRenderState(D3DRS_SPECULARENABLE, false); effect.setWorldMatrix(playerWorld); if(player.getState() != PLAYER_DEAD) effect.drawEffect(Device, timeDelta); blood.drawBillboardOnce(Device, timeDelta); //lightEffect.drawBillboard(Device, timeDelta); //nextStage.setPos(D3DXVECTOR3(0.0f, 200.0f, 0.0f)); //nextStage.drawBillboard(Device, timeDelta); stage1UI.Draw(Device, timeDelta); stage2UI.Draw(Device, timeDelta); stage3UI.Draw(Device, timeDelta); stage4UI.Draw(Device, timeDelta); Device->SetRenderState(D3DRS_ALPHABLENDENABLE, false); Device->SetRenderState(D3DRS_NORMALIZENORMALS, true); Device->SetRenderState(D3DRS_SPECULARENABLE, true); //////////////////////////////////////////////////////////////////////////////////// //Print Frame Rate pSprite->Begin(D3DXSPRITE_ALPHABLEND | D3DXSPRITE_SORT_TEXTURE); //wchar_t buf[128]; //RECT tempRect; //int frameRate = 0; //static int maxFrameRate = 0; //static int minFrameRate = 50000; //frameRate = d3d::CountFrame(timeDelta); //if (frameRate > maxFrameRate) // maxFrameRate = frameRate; //if (frameRate < minFrameRate && frameRate > 0) // minFrameRate = frameRate; //tempRect.left = 20; //tempRect.right = 120; //tempRect.top = 500; //tempRect.bottom = 520; //pFonts->DrawTextW(pSprite, L"Frame Rate :", -1, &tempRect, 0, D3DCOLOR_ARGB(255, 0, 0, 0)); //tempRect.left = 130; //tempRect.right = 200; //tempRect.top = 500; //tempRect.bottom = 520; //_itow_s(frameRate, buf, 10); //pFonts->DrawTextW(pSprite, buf, -1, &tempRect, 0, D3DCOLOR_ARGB(255, 0, 0, 0)); //tempRect.left = 20; //tempRect.right = 100; //tempRect.top = 530; //tempRect.bottom = 550; //pFonts->DrawTextW(pSprite, L"Max FPS :", -1, &tempRect, 0, D3DCOLOR_ARGB(255, 0, 0, 0)); //tempRect.left = 115; //tempRect.right = 160; //tempRect.top = 530; //tempRect.bottom = 550; //_itow_s(maxFrameRate, buf, 10); //pFonts->DrawTextW(pSprite, buf, -1, &tempRect, 0, D3DCOLOR_ARGB(255, 0, 0, 0)); //tempRect.left = 20; //tempRect.right = 100; //tempRect.top = 560; //tempRect.bottom = 580; //pFonts->DrawTextW(pSprite, L"Min FPS :", -1, &tempRect, 0, D3DCOLOR_ARGB(255, 0, 0, 0)); //tempRect.left = 115; //tempRect.right = 160; //tempRect.top = 560; //tempRect.bottom = 580; //_itow_s(minFrameRate, buf, 10); //pFonts->DrawTextW(pSprite, buf, -1, &tempRect, 0, D3DCOLOR_ARGB(255, 0, 0, 0)); //tempRect.left = 200; //tempRect.right = 250; //tempRect.top = 560; //tempRect.bottom = 580; ////itoa(player.getPos().x, buf, 10); //_itow_s(player.getHp(), buf, 10); //pFonts->DrawTextW(pSprite, buf, -1, &tempRect, 0, D3DCOLOR_ARGB(255, 0, 0, 0)); //tempRect.left = 260; //tempRect.right = 320; //tempRect.top = 560; //tempRect.bottom = 580; //_itow_s(player.getPos().z, buf, 10); //pFonts->DrawTextW(pSprite, buf, -1, &tempRect, 0, D3DCOLOR_ARGB(255, 0, 0, 0)); ////////////////////////////////////////////////////////////////////////////////////// D3DXMATRIX transMatrix; D3DXMATRIX scaleMatrix; D3DXMatrixIdentity(&transMatrix); D3DXMatrixTranslation(&transMatrix, -32, -32, 0.0f); D3DXMatrixIdentity(&scaleMatrix); POINT p; GetCursorPos(&p); RECT hpRect; hpRect.top = 0.0f; hpRect.bottom = 33.0f; hpRect.left = 0.0f; if (player.getHp() < 0) hpRect.right = 0.0f; else hpRect.right = 255.0f * ((float)player.getHp() / 100); static float elapseTime = 0.0f; RECT respawnRect; respawnRect.top = 0.0f; respawnRect.left = 0.0f; respawnRect.bottom = 32.0f; if (elapseTime < RESPAWN_TIME) respawnRect.right = 256.0f * (elapseTime / RESPAWN_TIME); else respawnRect.right = 256.0f; D3DXMatrixScaling(&scaleMatrix, 0.95f, 0.60f, 1.0f); pSprite->SetTransform(&scaleMatrix); pSprite->Draw(g_pHpBar, &hpRect, NULL, &D3DXVECTOR3(Width / 35, Height / 28, 0.0f), D3DCOLOR_RGBA(255, 255, 255, 255)); D3DXMatrixIdentity(&scaleMatrix); pSprite->SetTransform(&scaleMatrix); D3DXMatrixScaling(&scaleMatrix, 1.0f, 0.5f, 1.0f); pSprite->SetTransform(&scaleMatrix); pSprite->Draw(g_pHp, NULL, NULL, &D3DXVECTOR3(Width / 40, Height / 40, 0.0f), D3DCOLOR_RGBA(255, 255, 255, 255)); D3DXMatrixIdentity(&scaleMatrix); pSprite->SetTransform(&scaleMatrix); pSprite->SetTransform(&transMatrix); pSprite->Draw(g_pTexture, NULL, NULL, &D3DXVECTOR3(Width / 2, Height / 2, 0.0f), D3DCOLOR_RGBA(255, 255, 255, 255)); D3DXMatrixIdentity(&transMatrix); pSprite->SetTransform(&transMatrix); switch(player.startRespawn(timeDelta)) { case RESPAWNING: elapseTime += timeDelta; D3DXMatrixScaling(&scaleMatrix, 1.5f, 0.5f, 1.0f); pSprite->SetTransform(&scaleMatrix); pSprite->Draw(g_pRespawn, NULL, NULL, &D3DXVECTOR3(Width / 4.2, Height / 0.7, 0.01f), D3DCOLOR_RGBA(255, 255, 255, 255)); D3DXMatrixIdentity(&scaleMatrix); pSprite->SetTransform(&scaleMatrix); D3DXMatrixScaling(&scaleMatrix, 1.48f, 0.82f, 1.0f); pSprite->SetTransform(&scaleMatrix); pSprite->Draw(g_pRespawnBar, &respawnRect, NULL, &D3DXVECTOR3(Width / 4.12, Height / 1.142, 0.0f), D3DCOLOR_RGBA(255, 255, 255, 255)); D3DXMatrixIdentity(&scaleMatrix); pSprite->SetTransform(&scaleMatrix); D3DXMatrixScaling(&scaleMatrix, 0.5f, 0.3f, 1.0f); pSprite->SetTransform(&scaleMatrix); pSprite->Draw(g_pRespawnFont, NULL, NULL, &D3DXVECTOR3(Width / 1.25, Height / 0.5, 0.0f), D3DCOLOR_RGBA(255, 255, 255, 255)); D3DXMatrixIdentity(&scaleMatrix); pSprite->SetTransform(&scaleMatrix); break; case RESPAWN_NOW: elapseTime = 0.0f; cs_packet_respawn *my_packet = reinterpret_cast<cs_packet_respawn *>(send_buffer); my_packet->size = sizeof(cs_packet_respawn); my_packet->type = CS_PLAYER_RESPAWN; send_wsabuf.buf = send_buffer; send_wsabuf.len = sizeof(cs_packet_respawn); int ret = 0; memcpy(&send_buffer, my_packet, my_packet->size); ret = WSASend(g_mysocket, &send_wsabuf, 1, &iobyte, 0, NULL, NULL); if (ret) { int error_code = WSAGetLastError(); ::MessageBox(NULL, L"Error while sending packet", NULL, MB_OK); } } pSprite->End(); Device->EndScene(); Device->Present(0, 0, 0, 0); } else { if (FAILED(g_pDIMouse->GetDeviceState(sizeof(DIMOUSESTATE), &mouseState))) { if (FAILED(g_pDIMouse->Acquire())) return E_FAIL; } Device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0); Device->BeginScene(); pSprite->Begin(D3DXSPRITE_ALPHABLEND | D3DXSPRITE_SORT_TEXTURE); RECT rect; GetWindowRect(main_window_handle, &rect); D3DXMATRIX mat; D3DXMatrixScaling(&mat, ((float)rect.right / (float)START_TEXTURE_WIDTH), ((float)rect.bottom / (float)START_TEXTURE_HEIGHT), 1.0f); pSprite->SetTransform(&mat); pSprite->Draw(g_pStartTexture, NULL, NULL, NULL, D3DCOLOR_RGBA(255, 255, 255, 255)); pSprite->End(); POINT p; GetCursorPos(&p); GetWindowRect(main_window_handle, &rect); if (p.x > rect.right / 20 && p.x < rect.right / 1.8 && p.y > rect.bottom / 3.5 && p.y < rect.bottom / 2.5 && mouseState.rgbButtons[1] & 0x80) { start = true; } if (p.x > rect.right / 20 && p.x < rect.right / 2.8 && p.y > rect.bottom / 1.63 && p.y < rect.bottom / 1.45 && mouseState.rgbButtons[0] & 0x80) { ::DestroyWindow(main_window_handle); } Device->EndScene(); Device->Present(0, 0, 0, 0); } return true; } // // WndProc // LRESULT CALLBACK d3d::WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch( msg ) { case WM_DESTROY: ::PostQuitMessage(0); break; case WM_SOCKET: if (WSAGETSELECTERROR(lParam)) { closesocket((SOCKET)wParam); clienterror(); break; } switch (WSAGETSELECTEVENT(lParam)) { case FD_READ: ReadPacket((SOCKET)wParam); break; case FD_CLOSE: closesocket((SOCKET)wParam); clienterror(); break; } break; case WM_KEYDOWN: if( wParam == VK_ESCAPE ) ::DestroyWindow(hwnd); break; } return ::DefWindowProc(hwnd, msg, wParam, lParam); } // // WinMain // int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE prevInstance, PSTR cmdLine, int showCmd) { main_window_handle = d3d::InitD3D(hinstance, Width, Height, true, D3DDEVTYPE_HAL, &Device, &pSprite); hInst = hinstance; if(!Setup()) { ::MessageBox(0, L"Setup() - FAILED", 0, 0); return 0; } d3d::EnterMsgLoop( Display ); Cleanup(); Device->Release(); return 0; } <file_sep>/AlienOwnedStates.cpp #include "AlienOwnedStates.h" #include "AlienSoldier.h" #include <cmath> Stand* Stand::Instance() { static Stand instance; return &instance; } void Stand::Enter(AlienSoldier* alien) { } void Stand::Execute(AlienSoldier* alien) { } void Stand::Exit(AlienSoldier* alien) { } ///////////////////////////////////////////////////////////// TraceEnemy* TraceEnemy::Instance() { static TraceEnemy instance; return &instance; } void TraceEnemy::Enter(AlienSoldier* alien) { } void TraceEnemy::Execute(AlienSoldier* alien) { // 길찾기 Vector3 tracePos, alienPos; /*m_pathFinder.FindPath(alien->getPos().x, alien->getPos().z, alien->getTracePlayerPos().x, alien->getTracePlayerPos().z, &(alien->m_path)); Vector3 direction; if (alien->m_path.size() > 0){ direction.x = (*(alien->m_path.end() - 1))->m_x - alien->getPos().x; direction.y = 0; direction.z = (*(alien->m_path.end() - 1))->m_y - alien->getPos().z; }*/ tracePos.x = alien->getTracePlayerPos().x; tracePos.y = alien->getTracePlayerPos().y; tracePos.z = alien->getTracePlayerPos().z; alienPos.x = alien->getPos().x; alienPos.y = alien->getPos().y; alienPos.z = alien->getPos().z; // tracePos 가 길찾기 결과 노드의 첫번째 노드가 되야됨. Vector3 direction; direction.x = tracePos.x - alienPos.x; direction.y = tracePos.y - alienPos.y; direction.z = tracePos.z - alienPos.z; float size = sqrt(pow(tracePos.x - alienPos.x, 2) + pow(tracePos.y - alienPos.y, 2) + pow(tracePos.z - alienPos.z, 2)); direction.x = direction.x / size; direction.y = direction.y / size; direction.z = direction.z / size; alien->moveAlien(direction); } void TraceEnemy::Exit(AlienSoldier* alien) { } /////////////////////////////////////////////////////// AttackEnemy* AttackEnemy::Instance() { static AttackEnemy instance; return &instance; } void AttackEnemy::Enter(AlienSoldier* alien) { } void AttackEnemy::Execute(AlienSoldier* alien) { } void AttackEnemy::Exit(AlienSoldier* alien) { } Dead* Dead::Instance() { static Dead instance; return &instance; } void Dead::Enter(AlienSoldier* alien) { } void Dead::Execute(AlienSoldier* alien) { } void Dead::Exit(AlienSoldier* alien) { } Damaged* Damaged::Instance() { static Damaged instance; return &instance; } void Damaged::Enter(AlienSoldier* alien) { } void Damaged::Execute(AlienSoldier* alien) { } void Damaged::Exit(AlienSoldier* alien) { }<file_sep>/Player.cpp #include "Player.h" CPlayer::CPlayer() { pos.x = 0.0f; pos.y = 0.0f; pos.z = 0.0f; charSpeed = 300.0f; isDrawPlayer = false; skelatonKeyDown = 1; mSkelatonDirection = D3DXVECTOR3(0.0f, 0.0f, 1.0f); mState = IDLE_ANIMATION; mHp = 100; } CPlayer::~CPlayer() { } void CPlayer::loadModel(wchar_t* strFileName, LPDIRECT3DDEVICE9 pd3dDevice) { mModel.LoadXFile(strFileName, pd3dDevice); mModel.SelectAnimation(IDLE_ANIMATION); } void CPlayer::movePlayerPos(float timeDelta) { if (timeDelta > 0) { D3DXVECTOR3 playerDirection; playerDirection.x = mModel.getworldMatrix()._31; playerDirection.y = mModel.getworldMatrix()._32; playerDirection.z = mModel.getworldMatrix()._33; D3DXVec3Normalize(&playerDirection, &playerDirection); pos -= playerDirection * charSpeed * timeDelta; mModel.setModelPosition(pos); if (mState == 0) mModel.SelectAnimation(RUN_ANIMATION); } } void CPlayer::setSkelatonPosition(float timeDelta) { if (timeDelta > 0) mModel.setModelPosition(pos); } void CPlayer::drawPlayer(LPDIRECT3DDEVICE9 pd3dDevice, float timeDelta) { if (isDrawPlayer) { if (mIsFire) { if (mState == PLAYER_FRONT_RUN) mModel.SelectAnimation(RUN_FRONT_FIRE_ANIMATION); else if (mState == PLAYER_STOP) mModel.SelectAnimation(FIRE_ANIMATION); else if (mState == PLAYER_LEFT_RUN) mModel.SelectAnimation(RUN_RIGHT_FIRE_ANIMATION); else if (mState == PLAYER_RIGHT_RUN) mModel.SelectAnimation(RUN_LEFT_FIRE_ANIMATION); } if (mState == PLAYER_DAMAGED) mModel.SelectAnimation(DAMAGED_ANIMATION); else if (mHp <= 0) { mState = PLAYER_DEAD; mModel.selectAnimationPlayOnce(DYING_ANIMATION, timeDelta); } mModel.Draw(pd3dDevice, timeDelta); } } void CPlayer::drawSkelaton(LPDIRECT3DDEVICE9 pd3dDevice, float timeDelta) { if (isDrawPlayer) { mModel.SelectAnimation(mState); mModel.Draw(pd3dDevice, timeDelta); } } void CPlayer::stopPlayer(int lastKey) { mModel.initRotateMatrix(); mModel.SelectAnimation(IDLE_ANIMATION); } float CPlayer::rotateYPlayer(D3DXVECTOR3 cameraVec) { float angle = 0.0f; float rotateAngle = 0.0f; D3DXMATRIX tempMatrix; D3DXMatrixIdentity(&tempMatrix); D3DXVECTOR3 charDirection; charDirection.x = mModel.getworldMatrix()._31; charDirection.y = mModel.getworldMatrix()._32; charDirection.z = mModel.getworldMatrix()._33; D3DXVec3Normalize(&charDirection, &charDirection); D3DXVec3Normalize(&cameraVec, &cameraVec); rotateAngle = D3DXVec3Dot(&charDirection, &cameraVec); rotateAngle = acos(rotateAngle); D3DXVECTOR3 tempCross; D3DXVec3Cross(&tempCross, &cameraVec, &charDirection); if (rotateAngle > 0.1f) { angle = -tempCross.y; mModel.initRotateMatrix(); D3DXMatrixRotationY(&tempMatrix, angle); mModel.rotateMatrixMultiply(tempMatrix); } else if (rotateAngle < 0.1f) { mModel.initRotateMatrix(); } return angle; } void CPlayer::fireGun(bool fire, D3DXVECTOR3 cameraLookVec) { if (fire) { mIsFire = true; } } void CPlayer::setMoveAnim(char animNum) { mModel.SelectAnimation(animNum); } void CPlayer::skelatonRotate() { float angle = 0.0f; float rotateAngle = 0.0f; D3DXMATRIX tempMatrix; D3DXMatrixIdentity(&tempMatrix); D3DXVECTOR3 oldCharDirection; D3DXVECTOR3 newCharDirection; oldCharDirection.x = mModel.getworldMatrix()._31; oldCharDirection.y = mModel.getworldMatrix()._32; oldCharDirection.z = mModel.getworldMatrix()._33; newCharDirection = mSkelatonDirection; D3DXVec3Normalize(&newCharDirection, &newCharDirection); D3DXVec3Normalize(&oldCharDirection, &oldCharDirection); rotateAngle = D3DXVec3Dot(&newCharDirection, &oldCharDirection); rotateAngle = acos(rotateAngle); D3DXVECTOR3 tempCross; D3DXVec3Cross(&tempCross, &newCharDirection, &oldCharDirection); if (rotateAngle > 0.1f) { angle = -tempCross.y; mModel.initRotateMatrix(); D3DXMatrixRotationY(&tempMatrix, angle); mModel.rotateMatrixMultiply(tempMatrix); } else if (rotateAngle < 0.1f) { mModel.initRotateMatrix(); } } int CPlayer::startRespawn(float timeDelta) { static float waitingTime = 0.0f; if (mHp <= 0) { waitingTime += timeDelta; if (waitingTime >= RESPAWN_WAITING_TIME + RESPAWN_TIME) { waitingTime = 0.0f; return RESPAWN_NOW; } if (waitingTime >= RESPAWN_WAITING_TIME) return RESPAWNING; } return NOT_RESPAWN; } void CPlayer::initPlayerModel() { mModel.initModel(); }<file_sep>/Effect.cpp #include "Effect.h" Effect::Effect() { effect.setIsEffect(true); visible = false; } Effect::~Effect() { } void Effect::loadEffect(wchar_t* strFileName, LPDIRECT3DDEVICE9 pd3dDevice) { effect.LoadXFile(strFileName, pd3dDevice); } void Effect::rotateYawToCamera(D3DXVECTOR3 cameraPos) { float angle = 0.0f; float rotateAngle = 0.0f; D3DXMATRIX tempMatrix; D3DXMatrixIdentity(&tempMatrix); D3DXVECTOR3 effectDirection; effectDirection.x = effect.getworldMatrix()._31; effectDirection.y = 0.0f; effectDirection.z = effect.getworldMatrix()._33; effectDirection = -effectDirection; D3DXVec3Normalize(&effectDirection, &effectDirection); D3DXVec3Normalize(&cameraPos, &cameraPos); rotateAngle = D3DXVec3Dot(&effectDirection, &cameraPos); rotateAngle = acos(rotateAngle); D3DXVECTOR3 tempCross; D3DXVec3Cross(&tempCross, &cameraPos, &effectDirection); if (rotateAngle > 0.1f) { angle = -tempCross.y; effect.initRotateMatrix(); D3DXMatrixRotationY(&tempMatrix, angle); effect.rotateMatrixMultiply(tempMatrix); } else if (rotateAngle < 0.1f) { effect.initRotateMatrix(); } } void Effect::rotatePitchToCamera(D3DXVECTOR3 cameraPos) { float angle = 0.0f; float rotateAngle = 0.0f; D3DXMATRIX tempMatrix; D3DXMatrixIdentity(&tempMatrix); D3DXVECTOR3 effectDirection; effectDirection.x = 0.0f; effectDirection.y = effect.getworldMatrix()._32; effectDirection.z = effect.getworldMatrix()._33; effectDirection = -effectDirection; D3DXVec3Normalize(&effectDirection, &effectDirection); D3DXVec3Normalize(&cameraPos, &cameraPos); rotateAngle = D3DXVec3Dot(&effectDirection, &cameraPos); rotateAngle = acos(rotateAngle); D3DXVECTOR3 tempCross; D3DXVec3Cross(&tempCross, &cameraPos, &effectDirection); if (rotateAngle > 0.1f) { angle = -tempCross.y; effect.initRotateMatrix(); D3DXMatrixRotationX(&tempMatrix, angle); effect.rotateMatrixMultiply(tempMatrix); } else if (rotateAngle < 0.1f) { effect.initRotateMatrix(); } } void Effect::drawEffect(LPDIRECT3DDEVICE9 pd3dDevice, float timeDelta) { if (visible) { effect.SelectAnimation(0); effect.Draw(pd3dDevice, timeDelta); } } void Effect::rotateY(float angle) { D3DXMATRIX rotate; D3DXMatrixRotationY(&rotate, angle); effect.setworldMatrix(rotate); }<file_sep>/FindWay.cpp class Pos{ bool walked; }; //0인지 1인지 구분해놓은 맵정보를 받아와서 맵을 하나 만들어야함.그리고 이 맵 정보를 아래 맵에 대입. Pos Map[500][500]; //이 맵은 walked인지 판단하는 맵 class Node{ int result_value; int x; int y; int next_x; int next_y; }; float range(Vector * Alien, Node * Player) { //vector.x - NOde.x를 리턴 return sqrt(Alien - Player); } class RoadFind{ Pos * pMap = Map; vector<Node> path; Node * nowNode; iterator::vector<Node> * pNode; //targetNode는 플레이어 좌표 Node * Find(Vector * AlienPosition, Node * targetNode) { // 한걸음 이하인지 확인한다. if (range(AlienPosition, targetNode) < 1){ return targetNode; } else{ // 첫노드가 갈수 없는 노드일때. if (!FindNearistNode(PlayerPosition)) return false; else nowNode = FindNearistNode(PlayerPosition)); } pNode = NULL; while (true){ float right_value = 0; float left_value = 0; float up_value= 0; float down_value = 0; if (nowNode){ // 노드가 전에 사용 됐는지확인 if (Map[nowNode.x][nowNode.y].walked){ // 해당 노드의 삭제 if (pNode) pNode = path.erase(pNode) // 벡터에 다음 노드가 있는지 확인 if (pNode == path.end()) return false; } // 현재 노드의 사용을 표시한다. Map[nowNode.x][nowNode.y].walked = true; // 4방면 각노드의 최종값 계산 if (nowNode.x - 1 > 0){ // 갔었는지 확인 if (!Map[nowNode.x - 1][nowNode.y].walked){ } } } } // 4진트리 처리 방식에 따라서(방향은 그다지 상관없음) 각 노드의 깊이와 각 노드에서 도착점까지의 거리를 저장해서 리스트에 최종값과 함께 좌표 인덱스를 저장. //if (각 4진트리의 walked 가 false인지 확인 ){ // 최종값을 대입 // 리스트에 최종값을 비교해서 삽입 //} } // 루프.. End 도착지점과 한걸음 이하일 때까지 // 리스트에 최종 도착점을 넣어야 함. } };<file_sep>/PathFinder.h #pragma once #include "Map.h" #include "vector" #include <Windows.h> #define OUT 1 #define DES 2 #define FAULT 3 #define SUCCESS 4 #define FAIL 5 #define ROOT 0 #define LEFT 1 #define RIGHT 2 #define UP 3 #define DOWN 4 #define LUP 5 #define RUP 6 #define LDW 7 #define RDW 8 class Node_2D{ public: int m_x; int m_y; float m_Hcost; float m_Gcost; float m_Fcost; Node_2D * m_parent; BYTE m_direction; bool m_used; }; #define SIZE_TILE 1 class PathFinder{ public: PathFinder(Map * pMap); ~PathFinder(); Map * m_pRMap; //유닛 충돌의 경우만 Map m_map; std::vector<Node_2D *> m_path; //가는길을 저 int FindPath(float startX, float startY, float destinationX, float destinationY, std::vector<Node_2D *> * saveVector); Node_2D * FindNode(int x, int y); //지금 노드가 만들어 놓은 노드경로중에 지금 노드가 있나 없나를 체크. Node_2D * FindPred(void); //지금 있는 노드에서 주변을 검색 후 갈 노드를 찾는것. void InsertNode(Node_2D * newNode); //노드를 찾은후 집어넣는것. void ClearNode(void); }; /* //Declare constants const int mapWidth = SZ_MAP_X, mapHeight = SZ_MAP_Y, tileSize = 1, numberPeople = 1; const int notfinished = 0, notStarted = 0;// path-related constants const int found = 1, nonexistent = 2; const int walkable = 0, unwalkable = 1;// walkability array constants class PathFinder { public: PathFinder(); ~PathFinder(void); Map m_map; bool LoadMapData(LPCWSTR filename); int FindPath(int pathfinderID, int startingX, int startingZ, int targetX, int targetZ); void ReadPath(int pathfinderID, int currentX, int currentY, int pixelsPerFrame); int ReadPathX(int pathfinderID, int pathLocation); int ReadPathY(int pathfinderID, int pathLocation); void SetStatus(int id, int status) { pathStatus[id] = status; } //Create needed arrays char walkability[mapWidth][mapHeight]; int openList[mapWidth*mapHeight + 2]; //1 dimensional array holding ID# of open list items int whichList[mapWidth + 1][mapHeight + 1]; //2 dimensional array used to record // whether a cell is on the open list or on the closed list. int openX[mapWidth*mapHeight + 2]; //1d array stores the x location of an item on the open list int openY[mapWidth*mapHeight + 2]; //1d array stores the y location of an item on the open list int parentX[mapWidth + 1][mapHeight + 1]; //2d array to store parent of each cell (x) int parentY[mapWidth + 1][mapHeight + 1]; //2d array to store parent of each cell (y) int Fcost[mapWidth*mapHeight + 2]; //1d array to store F cost of a cell on the open list int Gcost[mapWidth + 1][mapHeight + 1]; //2d array to store G cost for each cell. int Hcost[mapWidth*mapHeight + 2]; //1d array to store H cost of a cell on the open list int pathLength[numberPeople + 1]; //stores length of the found path for critter int pathLocation[numberPeople + 1]; //stores current position along the chosen path for critter int* pathBank[numberPeople + 1]; //Path reading variables int pathStatus[numberPeople + 1]; int xPath[numberPeople + 1]; int yPath[numberPeople + 1]; int nOnClosedList; }; */ <file_sep>/main.cpp #include <iostream> #include <thread> #include <vector> #include <WinSock2.h> #include <Windows.h> #define BOUNDINGBOX_NUM 50 #define ALIENSOLDIER_ATTACK_RANGE 200 using namespace std; #include "protocol.h" #include "AlienSoldier.h" #include "BoundingBox.h" const float PLAYER_SPEED = 15.0f; const int NUM_THREADS = 6; BoundingBox box[BOUNDINGBOX_NUM]; BoundingBox loadBox[4]; HANDLE hIOCP; struct OVERAPPED_EX { WSAOVERLAPPED overapped; bool is_send; WSABUF wsabuf; char IOCPbuf[MAX_BUFF_SIZE]; char PacketBuf[MAX_PACKET_SIZE]; unsigned int prev_received; unsigned int curr_packet_size; }; struct PLAYER { int x; int y; int z; int hp; int stage; float dx; float dy; float dz; int animState; bool onLoad; SOCKET sock; bool in_use; OVERAPPED_EX my_overapped; }; PLAYER players[MAX_USER]; AlienSoldier alien[NUM_OF_MONSTER]; Stand *stand; TraceEnemy *trace; AttackEnemy *attack; bool collisionCheckByMap(D3DXVECTOR3& vec, int stage) { for (int i = 0; i < BOUNDINGBOX_NUM; ++i) { if (box[i].isPointInside(vec)) return true; } return false; } bool detectPlayer() { Vector3 alienPos[NUM_OF_MONSTER]; Vector3 playerPos[MAX_USER]; for (auto j = 0; j < NUM_OF_MONSTER; ++j) { for (int i = 0; i < MAX_USER; ++i) { if (players[i].in_use) { alienPos[j].x = alien[j].getPos().x; alienPos[j].y = alien[j].getPos().y; alienPos[j].z = alien[j].getPos().z; if (!alien[j].getAlive()) { alien[j].changeState_dead(); } else if (pow(players[i].x - alienPos[j].x, 2) + pow(players[i].y - alienPos[j].y, 2) + pow(players[i].z - alienPos[j].z, 2) < ALIENSOLDIER_ATTACK_RANGE * ALIENSOLDIER_ATTACK_RANGE) { if (players[i].hp <= 0) alien[j].changeState_idle(); else { playerPos[i].x = players[i].x; playerPos[i].y = players[i].y; playerPos[i].z = players[i].z; alien[j].setTracePlayerPos(playerPos[i]); alien[j].changeState_attack(); } } else if (pow(players[i].x - alienPos[j].x, 2) + pow(players[i].y - alienPos[j].y, 2) + pow(players[i].z - alienPos[j].z, 2) < 1000 * 1000) { playerPos[i].x = players[i].x; playerPos[i].y = players[i].y; playerPos[i].z = players[i].z; alien[j].setTracePlayerPos(playerPos[i]); alien[j].changeState_trace(); break; } else alien[j].changeState_idle(); } } } return false; } void error_display(char *msg, int err_no) { WCHAR *lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, err_no, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); printf("%s :", msg); wprintf(L"에러%s\n", lpMsgBuf); LocalFree(lpMsgBuf); } void PlayerInit(int id) { ZeroMemory(&players[id], sizeof(players[id])); players[id].in_use = false; players[id].my_overapped.is_send = false; players[id].my_overapped.wsabuf.buf = players[id].my_overapped.IOCPbuf; players[id].my_overapped.wsabuf.len = sizeof(players[id].my_overapped.IOCPbuf); players[id].hp = 100; players[id].onLoad = false; players[id].animState = 8; players[id].stage = 1; } void MonsterInit() { for (int i = 0; i < NUM_OF_MONSTER; ++i) { alien[i].setAlive(true); alien[i].changeState_idle(); alien[i].setHp(50); } for (int i = 0; i < NUM_OF_MONSTER; ++i) { if (i < 10) alien[i].setStagePosition(11); else if (i >= 10 && i < 20) alien[i].setStagePosition(12); else if (i >= 20 && i < 30) alien[i].setStagePosition(13); else if (i >= 30 && i < 40) alien[i].setStagePosition(14); if (players[0].stage == 2 && players[0].in_use && !players[1].in_use) { if (i >= 0 && i < 20) alien[i].setStagePosition(21); else if (i >= 20 && i < 30) alien[i].setStagePosition(22); else if (i >= 30 && i < 40) alien[i].setStagePosition(23); } else if (players[0].stage == 3 && players[0].in_use && !players[1].in_use) { if (i >= 0 && i < 8) alien[i].setStagePosition(31); else if (i >= 8 && i < 16) alien[i].setStagePosition(32); else if (i >= 16 && i < 24) alien[i].setStagePosition(33); else if (i >= 24 && i < 32) alien[i].setStagePosition(34); else if (i >= 32 && i < 40) alien[i].setStagePosition(35); } else if (players[0].stage == 2 && players[1].stage == 2 && players[0].in_use && players[1].in_use) { if (i >= 0 && i < 20) alien[i].setStagePosition(21); else if (i >= 20 && i < 30) alien[i].setStagePosition(22); else if (i >= 30 && i < 40) alien[i].setStagePosition(23); } else if (players[0].stage == 3 && players[1].stage == 3 && players[0].in_use && players[1].in_use) { if (i >= 0 && i < 8) alien[i].setStagePosition(31); else if (i >= 8 && i < 16) alien[i].setStagePosition(32); else if (i >= 16 && i < 24) alien[i].setStagePosition(33); else if (i >= 24 && i < 32) alien[i].setStagePosition(34); else if (i >= 32 && i < 40) alien[i].setStagePosition(35); } } for (int i = 0; i < NUM_OF_MONSTER; ++i) { if (alien[i].getStagePosition() == 11) alien[i].setPos(rand() % 2100 - 1050, 0, rand() % 5000 + 1104); else if (alien[i].getStagePosition() == 12) alien[i].setPos(rand() % 7500 + 2000, 0, rand() % 2000 - 1600); else if (alien[i].getStagePosition() == 13) alien[i].setPos(rand() % 1900 - 1050, 0, rand() % 7500 - 10000); else if (alien[i].getStagePosition() == 14) alien[i].setPos(rand() % 5000 - 7000, 0, rand() % 1900 - 1400); else if (alien[i].getStagePosition() == 21) alien[i].setPos(rand() % 1200 + 5900, 0, rand() % 9300 + 15950); else if (alien[i].getStagePosition() == 22) alien[i].setPos(rand() % 8000 - 1730, 0, rand() % 1000 + 14360); else if (alien[i].getStagePosition() == 23) alien[i].setPos(rand() % 1100 - 3560, 0, rand() % 7200 + 15750); else if (alien[i].getStagePosition() == 31) alien[i].setPos(rand() % 8800 - 4468, 0, rand() % 1000 + 44610); else if (alien[i].getStagePosition() == 32) alien[i].setPos(rand() % 1000 + 5200, 0, rand() % 6400 + 39339); else if (alien[i].getStagePosition() == 33) alien[i].setPos(rand() % 6800 - 640, 0, rand() % 1100 + 37488); else if (alien[i].getStagePosition() == 34) alien[i].setPos(rand() % 1000 - 772, 0, rand() % 2200 + 34508); else if (alien[i].getStagePosition() == 35) alien[i].setPos(rand() % 3900 - 3629, 0, rand() % 1100 + 32841); } } void BoundingBoxInit() { box[0]._min = D3DXVECTOR3(-7650.0f, -100.0f, 880.0f); box[0]._max = D3DXVECTOR3(-1500.0f, 100.0f, 7100.0f); box[1]._min = D3DXVECTOR3(1527.0f, -100.0f, -11320.0f); box[1]._max = D3DXVECTOR3(10757.0f, 100.0f, -2077.0f); box[2]._min = D3DXVECTOR3(-1527.0f, -100.0f, -13320.0f); box[2]._max = D3DXVECTOR3(1527.0f, 100.0f, -11320.0f); box[3]._min = D3DXVECTOR3(-7665.0f, -100.0f, -11320.0f); box[3]._max = D3DXVECTOR3(-1527.0f, 100.0f, -2090.0f); box[4]._min = D3DXVECTOR3(-10000.0f, -100.0f, -2090.0f); box[4]._max = D3DXVECTOR3(-7665.0f, 100.0f, -889.0f); box[5]._min = D3DXVECTOR3(-1527.0f, -100.0f, 7100.0f); box[5]._max = D3DXVECTOR3(1500.0f, 100.0f, 10000.0f); box[6]._min = D3DXVECTOR3(1500.0f, -100.0f, 961.0f); box[6]._max = D3DXVECTOR3(4594.0f, 100.0f, 7150.0f); box[7]._min = D3DXVECTOR3(4594.0f, -100.0f, 1184.0f); box[7]._max = D3DXVECTOR3(10730.0f, 100.0f, 3184.0f); box[8]._min = D3DXVECTOR3(10730.0f, -100.0f, -2077.0f); box[8]._max = D3DXVECTOR3(12000.0f, 100.0f, 1184.0f); box[9]._min = D3DXVECTOR3(5408.0f, -100.0f, 28921.0f); box[9]._max = D3DXVECTOR3(7846.0f, 100.0f, 31590.0f); box[10]._min = D3DXVECTOR3(7663.0f, -100.0f, 13000.0f); box[10]._max = D3DXVECTOR3(9849.0f, 100.0f, 28919.0f); box[11]._min = D3DXVECTOR3(-4500.0f, -100.0f, 11117.0f); box[11]._max = D3DXVECTOR3(8000.0f, 100.0f, 13852.0f); box[12]._min = D3DXVECTOR3(-6500.0f, -100.0f, 13000.0f); box[12]._max = D3DXVECTOR3(-4100.0f, 100.0f, 25000.0f); box[13]._min = D3DXVECTOR3(-2000.0f, -100.0f, 15900.0f); box[13]._max = D3DXVECTOR3(2000.0f, 100.0f, 25000.0f); box[14]._min = D3DXVECTOR3(1000.0f, -100.0f, 15900.0f); box[14]._max = D3DXVECTOR3(5500.0f, 100.0f, 28900.0f); box[15]._min = D3DXVECTOR3(-7500.0f, -100.0f, 38000.0f); box[15]._max = D3DXVECTOR3(-5100.0f, 100.0f, 47000.0f); box[16]._min = D3DXVECTOR3(-5500.0f, -100.0f, 46200.0f); box[16]._max = D3DXVECTOR3(8000.0f, 100.0f, 50000.0f); box[17]._min = D3DXVECTOR3(6700.0f, -100.0f, 35000.0f); box[17]._max = D3DXVECTOR3(10000.0f, 100.0f, 48000.0f); box[18]._min = D3DXVECTOR3(900.0f, -100.0f, 30000.0f); box[18]._max = D3DXVECTOR3(7500.0f, 100.0f, 36900.0f); box[19]._min = D3DXVECTOR3(-5000.0f, -100.0f, 29000.0f); box[19]._max = D3DXVECTOR3(2000.0f, 100.0f, 32300.0f); box[20]._min = D3DXVECTOR3(-6000.0f, -100.0f, 34400.0f); box[20]._max = D3DXVECTOR3(-1200.0f, 100.0f, 40000.0f); box[21]._min = D3DXVECTOR3(-2000.0f, -100.0f, 39100.0f); box[21]._max = D3DXVECTOR3(4600.0f, 100.0f, 43000.0f); box[22]._min = D3DXVECTOR3(-3000.0f, -100.0f, 40000.0f); box[22]._max = D3DXVECTOR3(4600.0f, 100.0f, 44100.0f); loadBox[0]._min = D3DXVECTOR3(-INFINITY, -100.0f, 520.0f); loadBox[0]._max = D3DXVECTOR3(-1100.0f, 100.0f, INFINITY); loadBox[1]._min = D3DXVECTOR3(1100.0f, -100.0f, 520.0f); loadBox[1]._max = D3DXVECTOR3(INFINITY, 100.0f, INFINITY); loadBox[2]._min = D3DXVECTOR3(1100.0f, -100.0f, -INFINITY); loadBox[2]._max = D3DXVECTOR3(INFINITY, 100.0f, -1660.0f); loadBox[3]._min = D3DXVECTOR3(-INFINITY, -100.0f, -INFINITY); loadBox[3]._max = D3DXVECTOR3(-1100.0f, 100.0f, -1660.0f); } void SendPacket(int id, void *packet) { int packet_size = reinterpret_cast<unsigned char *>(packet)[0]; OVERAPPED_EX *send_over = new OVERAPPED_EX; ZeroMemory(send_over, sizeof(OVERAPPED_EX)); send_over->is_send = true; send_over->wsabuf.buf = send_over->IOCPbuf; send_over->wsabuf.len = packet_size; unsigned long io_size; memcpy(send_over->IOCPbuf, packet, packet_size); WSASend(players[id].sock, &send_over->wsabuf, 1, &io_size, NULL, &send_over->overapped, NULL); } void ProcessPacket(char packet[], int id) { sc_packet_pos pos_packet; sc_packet_monster mons_packet; detectPlayer(); if (packet[1] == MON_DAMAGED_BODY || packet[1] == MON_DAMAGED_HEAD) { cs_packet_shot_monster *shot_monster = reinterpret_cast<cs_packet_shot_monster*>(packet); if (alien[shot_monster->id].getAlive()) { int mons_id = shot_monster->id; int hp = alien[mons_id].getHp(); if (shot_monster->type == 6)//대가리 { hp = 0; alien[mons_id].setAlive(false); } else if (shot_monster->type == 7)//몸통 { if (alien[mons_id].getHp() <= 0) { alien[mons_id].setAlive(false); } else { alien[mons_id].decreaseHp(10); alien[mons_id].changeState_damaged(); } } } } if (CS_PLAYER_RESPAWN == packet[1]) { players[id].animState = 0; players[id].x = 0; players[id].y = 0; players[id].z = 0; players[id].stage = 1; players[id].hp = 100; sc_packet_respawn_player respawn_packet; respawn_packet.size = sizeof(respawn_packet); respawn_packet.type = SC_RESPAWN_PLAYER; respawn_packet.x = players[id].x; respawn_packet.y = players[id].y; respawn_packet.z = players[id].z; respawn_packet.hp = players[id].hp; respawn_packet.animState = players[id].animState; for (int i = 0; i < MAX_USER; ++i) SendPacket(i, &pos_packet); } if (CS_PLAYER_DAMAGED == packet[1]) { cs_packet_damaged_player *packet_damaged_player = reinterpret_cast<cs_packet_damaged_player*>(packet); players[id].animState = packet_damaged_player->animState; players[id].hp -= 10; } if (CS_MOVE == packet[1]) { cs_packet_move *packet_move = reinterpret_cast<cs_packet_move*>(packet); players[id].dx = packet_move->dx; players[id].dy = packet_move->dy; players[id].dz = packet_move->dz; players[id].animState = packet_move->animState; if (players[id].x > -1000 && players[id].x < 1000 && players[id].z > 6500 && players[id].z < 7000) { players[id].stage = 2; players[id].x = 6500; players[id].z = 28500; MonsterInit(); } if (players[id].x > -4500 && players[id].x < -2500 && players[id].z > 23500 && players[id].z < 24000) { players[id].stage = 1; players[id].x = 0; players[id].z = 0; MonsterInit(); } if (players[id].x > 10000 && players[id].x < 10700 && players[id].z > -2000 && players[id].z < 1000) { players[id].stage = 3; players[id].x = -5000; players[id].z = 41000; MonsterInit(); } if (players[id].x > -5000 && players[id].x < -4500 && players[id].z > 32000 && players[id].z < 34000) { players[id].stage = 1; players[id].x = 0; players[id].z = 0; MonsterInit(); } float x = packet_move->dx * PLAYER_SPEED; float y = packet_move->dy; float z = packet_move->dz * PLAYER_SPEED; D3DXVECTOR3 vec; vec.x = players[id].x - x; vec.y = players[id].y; vec.z = players[id].z - z; if (!collisionCheckByMap(vec, players[id].stage)) { players[id].x -= x; players[id].z -= z; } vec.x = players[id].x; vec.y = players[id].y; vec.z = players[id].z; if (loadBox[0].isPointInside(vec) || loadBox[1].isPointInside(vec) || loadBox[2].isPointInside(vec) || loadBox[3].isPointInside(vec)) { players[id].onLoad = true; } else players[id].onLoad = false; } if (CS_STOP == packet[1]) { cs_packet_move *packet_move = reinterpret_cast<cs_packet_move*>(packet); players[id].dx = packet_move->dx; players[id].dy = packet_move->dy; players[id].dz = packet_move->dz; players[id].animState = packet_move->animState; } pos_packet.size = sizeof(pos_packet); pos_packet.type = SC_POS; pos_packet.id = id; pos_packet.x = players[id].x; pos_packet.y = players[id].y; pos_packet.z = players[id].z; pos_packet.dx = players[id].dx; pos_packet.dy = players[id].dy; pos_packet.dz = players[id].dz; pos_packet.hp = players[id].hp; pos_packet.animState = players[id].animState; pos_packet.onLoad = players[id].onLoad; for (int i = 0; i < NUM_OF_MONSTER; ++i) alien[i].updateStateMachine(); for (int i = 0; i < NUM_OF_MONSTER; ++i) { mons_packet.size = sizeof(mons_packet); mons_packet.type = SC_MONSTER; mons_packet.x = alien[i].getPos().x; mons_packet.y = alien[i].getPos().y; mons_packet.z = alien[i].getPos().z; mons_packet.state = alien[i].states(); mons_packet.tx = alien[i].getTracePlayerPos().x; mons_packet.ty = alien[i].getTracePlayerPos().y; mons_packet.tz = alien[i].getTracePlayerPos().z; mons_packet.alive = alien[i].getAlive(); mons_packet.hp = alien[i].getHp(); mons_packet.id = i; mons_packet.monsterType = alien[i].getType(); //접속한 모두가 볼수있도록. for (int j = 0; j < MAX_USER; ++j) { if (true == players[j].in_use) SendPacket(j, &mons_packet); } } for (int i = 0; i < MAX_USER; ++i) SendPacket(i, &pos_packet); } void worker_thread() { while (true) { unsigned long io_size; unsigned long key; OVERAPPED_EX *over_ex; GetQueuedCompletionStatus(hIOCP, &io_size, &key, reinterpret_cast<LPOVERLAPPED *>(&over_ex), INFINITE); // ERROR // 접속종료 if (io_size == 0) { closesocket(players[key].sock); sc_packet_remove_player rem_packet; rem_packet.id = key; rem_packet.size = sizeof(rem_packet); rem_packet.type = SC_REMOVE_PLAYER; for (int i = 0; i < MAX_USER; ++i){ if (key == i) continue; if (false == players[i].in_use) continue; SendPacket(i, &rem_packet); } players[key].in_use = false; continue; } if (over_ex->is_send == false){ // RECV int rest_size = io_size; char *buf = over_ex->IOCPbuf; int packet_size = over_ex->curr_packet_size; while (0 < rest_size) { if (0 == packet_size) packet_size = buf[0]; int remain = packet_size - over_ex->prev_received; if (remain > rest_size) { // 패킷 만들기에는 부족하다. memcpy(over_ex->PacketBuf + over_ex->prev_received, buf, rest_size); over_ex->prev_received += rest_size; break; } else { // 패킷을 만들 수 있다. memcpy(over_ex->PacketBuf + over_ex->prev_received, buf, remain); ProcessPacket(over_ex->PacketBuf, key); rest_size -= remain; packet_size = 0; over_ex->prev_received = 0; } } over_ex->curr_packet_size = packet_size; unsigned long recv_flag = 0; WSARecv(players[key].sock, &over_ex->wsabuf, 1, NULL, &recv_flag, &over_ex->overapped, NULL); } else { delete over_ex; // SEND } } } int GetNewClient_ID() { for (int i = 0; i < MAX_USER; ++i) if (players[i].in_use == false){ PlayerInit(i); return i; } cout << "USER FULL ERROR!!"; exit(-1); return -1; } void accept_thread() { struct sockaddr_in listen_addr; struct sockaddr_in client_addr; SOCKET listen_socket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED); ZeroMemory(&listen_addr, sizeof(listen_addr)); listen_addr.sin_family = AF_INET; listen_addr.sin_addr.s_addr = htonl(INADDR_ANY); listen_addr.sin_port = htons(MY_SERVER_PORT); ZeroMemory(&listen_addr.sin_zero, 8); int ret = ::bind(listen_socket, reinterpret_cast<sockaddr *>(&listen_addr), sizeof(listen_addr)); if (SOCKET_ERROR == ret) { error_display("BIND", WSAGetLastError()); exit(-1); } ret = listen(listen_socket, 10); if (SOCKET_ERROR == ret) { error_display("LISTEN", WSAGetLastError()); exit(-1); } while (true) { int addr_size = sizeof(client_addr); SOCKET client_socket = WSAAccept(listen_socket, reinterpret_cast<sockaddr *>(&client_addr), &addr_size, NULL, NULL); cout << " 클라이언트 접속. 포트번호: "<< client_addr.sin_port << endl; if (INVALID_SOCKET == client_socket) { error_display("ACCEPT", WSAGetLastError()); exit(-1); } int id = GetNewClient_ID(); players[id].sock = client_socket; players[id].x = STARTING_X; players[id].y = STARTING_Y; players[id].z = STARTING_Z; CreateIoCompletionPort( reinterpret_cast<HANDLE>(client_socket), hIOCP, id, 0); unsigned long recv_flag = 0; ret = WSARecv(client_socket, &players[id].my_overapped.wsabuf, 1, NULL, &recv_flag, &players[id].my_overapped.overapped, NULL); if (SOCKET_ERROR == ret) { int err_code = WSAGetLastError(); if (WSA_IO_PENDING != err_code) { error_display("ACCEPT(WSARecv):", err_code); exit(-1); } } sc_packet_put_player put_player_packet; put_player_packet.id = id; put_player_packet.type = SC_PUT_PLAYER; put_player_packet.size = sizeof(put_player_packet); put_player_packet.x = players[id].x; put_player_packet.y = players[id].y; put_player_packet.z = players[id].z; SendPacket(id, &put_player_packet); for (int i = 0; i < MAX_USER; ++i){ if (false == players[i].in_use) continue; if (id == i) continue; SendPacket(i, &put_player_packet); } for (int i = 0; i < MAX_USER; ++i){ if (false == players[i].in_use) continue; if (id == i) continue; put_player_packet.id = i; put_player_packet.x = players[i].x; put_player_packet.y = players[i].y; put_player_packet.z = players[i].z; SendPacket(id, &put_player_packet); } players[id].in_use = true; sc_packet_monster mons_packet; for (int i = 0; i < NUM_OF_MONSTER; ++i) { mons_packet.size = sizeof(mons_packet); mons_packet.type = SC_MONSTER; mons_packet.x = alien[i].getPos().x; mons_packet.y = alien[i].getPos().y; mons_packet.z = alien[i].getPos().z; mons_packet.state = alien[i].states(); mons_packet.tx = alien[i].getTracePlayerPos().x; mons_packet.ty = alien[i].getTracePlayerPos().y; mons_packet.tz = alien[i].getTracePlayerPos().z; mons_packet.alive = alien[i].getAlive(); mons_packet.hp = alien[i].getHp(); mons_packet.id = i; mons_packet.type = alien[i].getType(); //접속한 모두가 볼수있도록. for (int j = 0; j < MAX_USER; ++j) { if (true == players[j].in_use) SendPacket(j, &mons_packet); } } } } void NetworkInit() { WSADATA wsadata; WSAStartup(MAKEWORD(2, 2), &wsadata); } int main(){ vector <thread *> worker_threads; _wsetlocale(LC_ALL, L"korean"); NetworkInit(); for (int i = 0; i < MAX_USER; ++i) PlayerInit(i); MonsterInit(); BoundingBoxInit(); hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0); for (int i = 0; i < NUM_THREADS; ++i) worker_threads.push_back(new thread{ worker_thread }); /*Initialize_NPC();*/ thread accept_threads = thread{ accept_thread }; while (true) { Sleep(1000); // if (g_server_shutdown == true) break; } }<file_sep>/protocol.h #include <Windows.h> #define MAX_BUFF_SIZE 4000 #define MAX_PACKET_SIZE 255 #define VIEW_RADIUS 4 #define MAX_USER 2 #define MY_SERVER_PORT 4000 #define MAX_STR_SIZE 100 #define NUM_OF_MONSTER 40 #define NPC_START 500 #define STARTING_X 0 #define STARTING_Y 0 #define STARTING_Z 0 #define SC_POS 1 #define SC_PUT_PLAYER 2 #define SC_REMOVE_PLAYER 3 #define SC_MONSTER 4 #define SC_DEAD_PLAYER 5 #define SC_RESPAWN_PLAYER 6 #define MON_STAND 1 #define MON_TRACE 2 #define MON_ATTACK 3 #define CS_MOVE 1 #define CS_DOWN 2 #define CS_LEFT 3 #define CS_RIGHT 4 #define CS_STOP 5 #define MON_DAMAGED_HEAD 6 #define MON_DAMAGED_BODY 7 #define CS_PLAYER_DAMAGED 8 #define CS_PLAYER_FIRED 9 #define CS_PLAYER_STOP_FIRE 10 #define CS_PLAYER_RESPAWN 11 #pragma pack (push, 1) struct cs_packet_move { BYTE size; BYTE type; int animState; float time; float dx; float dy; float dz; float x; float y; float z; }; struct cs_packet_player_fired{ BYTE size; BYTE type; bool isFire; int animState; }; struct cs_packet_shot_monster{ BYTE size; BYTE type; int id; }; //1΄λ°΅Έ® 2 ΈφΕλ struct cs_packet_damaged_player{ BYTE size; BYTE type; int animState; }; struct cs_packet_stop{ BYTE size; BYTE type; }; struct cs_packet_respawn{ BYTE size; BYTE type; }; struct sc_packet_pos { BYTE size; BYTE type; WORD id; float x; float y; float z; float dx; float dy; float dz; int hp; int animState; bool onLoad; }; struct sc_packet_put_player { BYTE size; BYTE type; WORD id; float x; float y; float z; }; struct sc_packet_remove_player { BYTE size; BYTE type; WORD id; }; struct sc_packet_dead_player{ BYTE size; BYTE type; WORD id; }; struct sc_packet_respawn_player{ BYTE size; BYTE type; WORD id; float x; float y; float z; int hp; int animState; }; struct sc_packet_monster{ BYTE size; BYTE type; float x; float y; float z; float tx; float ty; float tz; int monsterType; int state; bool alive; int hp; int id; }; #pragma pack (pop)<file_sep>/SkyBox.h #pragma once #include "CModel.h" class SkyBox { public: SkyBox(); ~SkyBox(); void loadModel(wchar_t* strFileName, LPDIRECT3DDEVICE9 pd3dDevice); void drawSkyBox(LPDIRECT3DDEVICE9 pd3dDevice, float timeDelta); private: CModel mSkyBoxModel; D3DXVECTOR3 mPos; }; <file_sep>/BoundingBox.cpp #include "BoundingBox.h" BoundingBox::BoundingBox() { // infinite small _min.x = Infinity; _min.y = Infinity; _min.z = Infinity; _max.x = Infinity; _max.y = Infinity; _max.z = Infinity; } bool BoundingBox::isPointInside(D3DXVECTOR3& p) { if (p.x >= _min.x && p.y >= _min.y && p.z >= _min.z && p.x <= _max.x && p.y <= _max.y && p.z <= _max.z) { return true; } else { return false; } }<file_sep>/Billboard.h #pragma once #include "d3dUtility.h" class Billboard { public: Billboard(); Billboard(float x, float y, float z); ~Billboard(); void createQuad(LPDIRECT3DDEVICE9 pd3dDevice, int indexNum, int width, int height); void setPos(D3DXVECTOR3 vec); void setMatrix(D3DXMATRIX* mat); void setWorldMatrix(D3DXMATRIX mat) { worldMatrix = mat; } void multiplyWorldMatrix(D3DXMATRIX mat) { worldMatrix = mat * worldMatrix; } void setVisible(bool setValue) { visible = setValue; } void setAnimTime(float time) { animTime = time; } HRESULT loadTexture(wchar_t* strTexName, LPDIRECT3DDEVICE9 pd3dDevice); void scaleBillboard(float x, float y, float z); void drawBillboard(LPDIRECT3DDEVICE9 pd3dDevice, float timeDelta); void drawBillboardOnce(LPDIRECT3DDEVICE9 pd3dDevice, float timeDelta); private: LPDIRECT3DTEXTURE9 tex; IDirect3DVertexBuffer9* quad = 0; IDirect3DIndexBuffer9* IB = 0; d3d::Vertex* v; D3DXMATRIX worldMatrix; float animTime; float frameNum; bool visible; }; <file_sep>/AlienSoldier.h #pragma once #include "StateMachine.h" #include "AlienOwnedStates.h" #include <stdlib.h> #define IDLE_STATE 4 #define ATTACK_STATE 3 #define TRACE_STATE 2 #define DYING_STATE 1 #define DAMAGED_STATE 0 class AlienSoldier { public: AlienSoldier(float x, float y, float z) : mHp(50) { mPos.x = x; mPos.y = y; mPos.z = z; mTraceSpeed = 10.0f; state = IDLE_STATE; is_alive = true; m_pStateMachine = new StateMachine<AlienSoldier>(this); m_pStateMachine->SetCurrentState(Stand::Instance()); } AlienSoldier() : mHp(50) { mPos.x = 0; mPos.y = 0; mPos.z = 0; stagePosition = 11; type = rand() % 3; is_alive = true; state = IDLE_STATE; mTraceSpeed = 10.0f; m_pStateMachine = new StateMachine<AlienSoldier>(this); m_pStateMachine->SetCurrentState(Stand::Instance()); } ~AlienSoldier() { delete m_pStateMachine; } void updateStateMachine(); StateMachine<AlienSoldier>* GetFSM()const{ return m_pStateMachine; } Vector3 getPos() { return mPos; } Vector3 getTracePlayerPos() { return mTracePlayerPos; } void moveAlien(Vector3 dest); void setTracePlayerPos(Vector3 pos) { mTracePlayerPos.x = pos.x; mTracePlayerPos.y = pos.y; mTracePlayerPos.z = pos.z; } int states(){ return state; } int changeState_idle() { state = IDLE_STATE; m_pStateMachine->ChangeState(Stand::Instance()); return state; } int changeState_trace(){ state = TRACE_STATE; m_pStateMachine->ChangeState(TraceEnemy::Instance()); return state; } int changeState_attack(){ state = ATTACK_STATE; m_pStateMachine->ChangeState(AttackEnemy::Instance()); return state; } int changeState_dead() { state = DYING_STATE; m_pStateMachine->ChangeState(Dead::Instance()); return state; } int changeState_damaged() { state = DAMAGED_STATE; m_pStateMachine->ChangeState(Damaged::Instance()); return state; } bool getAlive() { return is_alive; } void setAlive(bool setValue) { is_alive = setValue; } int getHp() { return mHp; } void setHp(int hp){ mHp = hp; } void decreaseHp(int setValue) { mHp -= setValue; } int getAttackPlayerId(){ return mAttackPlayerId; } void setAttackPlayerId(int setValue) { mAttackPlayerId = setValue; } Vector3 setPos(int x, int y, int z){ mPos.x = x, mPos.y = y; mPos.z = z; return mPos; }; int getStagePosition() { return stagePosition; } void setStagePosition(int setValue) { stagePosition = setValue; } int getType() { return type; } void setType(int setValue) { type = setValue; } std::vector<Node_2D *> m_path; private: StateMachine<AlienSoldier>* m_pStateMachine; int mHp; Vector3 mPos; Vector3 mTracePlayerPos; float mTraceSpeed; int type; int state; int stagePosition; bool is_alive; int mAttackPlayerId; }; <file_sep>/Player.h #pragma once #include "d3dUtility.h" #include "CModel.h" #define IDLE_ANIMATION 15 #define FRONT_WALK_ANIMATION 14 #define FIRE_ANIMATION 13 #define RUN_ANIMATION 12 #define RUN_FRONT_FIRE_ANIMATION 11 #define RUN_LEFT_FIRE_ANIMATION 10 #define RUN_RIGHT_FIRE_ANIMATION 9 #define DAMAGED_ANIMATION 8 #define DYING_ANIMATION 7 #define SHOOT_DELAY_TIME 0.3 #define PLAYER_STOP 0 #define PLAYER_FRONT_RUN 1 #define PLAYER_LEFT_RUN 2 #define PLAYER_RIGHT_RUN 3 #define PLAYER_DAMAGED 4 #define PLAYER_DEAD 5 #define NOT_RESPAWN 0 #define RESPAWNING 1 #define RESPAWN_NOW 2 const float RESPAWN_TIME = 8.0f; const float RESPAWN_WAITING_TIME = 3.0f; class CPlayer { public: CPlayer(); ~CPlayer(); void setPos(D3DXVECTOR3 setValue) { pos = setValue; mModel.setModelPosition(pos); } D3DXVECTOR3 getPos() { return pos; } void setSpeed(float setValue) { charSpeed = setValue; } float getSpeed() { return charSpeed; } void setDrawPlayer(bool setValue) { isDrawPlayer = setValue; } bool getDrawPlayer() { return isDrawPlayer; } void setSkelatonKeyDown(int setValue) { skelatonKeyDown = setValue; } int getSkelatonKeyDown() { return skelatonKeyDown; } void setSkelatonDirection(D3DXVECTOR3 setValue) { mSkelatonDirection = setValue; } D3DXVECTOR3 getSkelatonDirection() { return mSkelatonDirection; } void setState(int setValue) { mState = setValue; } int getState() { return mState; } void setIsFire(bool setValue) { mIsFire = setValue; } bool getIsFire() { return mIsFire; } int getHp() { return mHp; } void setHp(int setValue) { mHp = setValue; } int getCurrAnimNum() { return mModel.getCurrAnimNum(); } void loadModel(wchar_t* strFileName, LPDIRECT3DDEVICE9 pd3dDevice); void stopPlayer(int lastKey); void drawPlayer(LPDIRECT3DDEVICE9 pd3dDevice, float timeDelta); void drawSkelaton(LPDIRECT3DDEVICE9 pd3dDevice, float timeDelta); void movePlayerPos(float timeDelta); float rotateYPlayer(D3DXVECTOR3 cameraVec); void setSkelatonPosition(float timeDelta); void skelatonRotate(); void setMoveAnim(char animNum); void fireGun(bool fire, D3DXVECTOR3 cameraLookVec); int startRespawn(float timeDelta); void initPlayerModel(); D3DXMATRIX getWorldMatrix() { return mModel.getworldMatrix(); } private: CModel mModel; D3DXVECTOR3 pos; float charSpeed; bool isDrawPlayer; int skelatonKeyDown; D3DXVECTOR3 mSkelatonDirection; int mState; bool mIsFire; int mHp; }; <file_sep>/CModel.cpp #include "CModel.h" CModel::CModel() { D3DXMatrixIdentity(&worldMatrix); D3DXMatrixIdentity(&rotateMatrix); D3DXMatrixIdentity(&scaleMatrix); mIsEffect = false; mCurrAnimNum = 0; mAnimTime = 0.0f; } CModel::~CModel() { } IDirect3DVertexShader9* g_pIndexedVertexShader[4]; ID3DXEffect* g_pEffect = NULL; // D3DX effect interface D3DXMATRIXA16 g_matView; // View matrix DWORD g_dwBehaviorFlags; // Behavior flags of the 3D device METHOD g_SkinningMethod = D3DNONINDEXED; // Current skinning method D3DXMATRIXA16* g_pBoneMatrices = NULL; UINT g_NumBoneMatricesMax = 0; bool g_bUseSoftwareVP; // Flag to indicate whether software vp is void CModel::DrawMeshContainer(IDirect3DDevice9* pd3dDevice, LPD3DXMESHCONTAINER pMeshContainerBase, LPD3DXFRAME pFrameBase) { //HRESULT hr; D3DXMESHCONTAINER_DERIVED* pMeshContainer = (D3DXMESHCONTAINER_DERIVED*)pMeshContainerBase; D3DXFRAME_DERIVED* pFrame = (D3DXFRAME_DERIVED*)pFrameBase; UINT iMaterial; UINT NumBlend; UINT iAttrib; DWORD AttribIdPrev; LPD3DXBONECOMBINATION pBoneComb; UINT iMatrixIndex; UINT iPaletteEntry; D3DXMATRIXA16 matTemp; D3DCAPS9 d3dCaps; pd3dDevice->GetDeviceCaps(&d3dCaps); // first check for skinning if (pMeshContainer->pSkinInfo != NULL) { if (g_SkinningMethod == D3DNONINDEXED) { AttribIdPrev = UNUSED32; pBoneComb = reinterpret_cast<LPD3DXBONECOMBINATION>(pMeshContainer->pBoneCombinationBuf->GetBufferPointer ()); // Draw using default vtx processing of the device (typically HW) for (iAttrib = 0; iAttrib < pMeshContainer->NumAttributeGroups; iAttrib++) { NumBlend = 0; for (DWORD i = 0; i < pMeshContainer->NumInfl; ++i) { if (pBoneComb[iAttrib].BoneId[i] != UINT_MAX) { NumBlend = i; } } //////////////// if (d3dCaps.MaxVertexBlendMatrices >= NumBlend + 1) { // first calculate the world matrices for the current set of blend weights and get the accurate count of the number of blends for (DWORD i = 0; i < pMeshContainer->NumInfl; ++i) { iMatrixIndex = pBoneComb[iAttrib].BoneId[i]; if (iMatrixIndex != UINT_MAX) { D3DXMatrixMultiply(&matTemp, &pMeshContainer->pBoneOffsetMatrices[iMatrixIndex], pMeshContainer->ppBoneMatrixPtrs[iMatrixIndex]); pd3dDevice->SetTransform(D3DTS_WORLDMATRIX(i), &matTemp); } } pd3dDevice->SetRenderState(D3DRS_VERTEXBLEND, NumBlend); // lookup the material used for this subset of faces if ((AttribIdPrev != pBoneComb[iAttrib].AttribId) || (AttribIdPrev == UNUSED32)) { pd3dDevice->SetMaterial(&pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D); pd3dDevice->SetTexture(0, pMeshContainer->ppTextures[pBoneComb[iAttrib].AttribId]); AttribIdPrev = pBoneComb[iAttrib].AttribId; } // draw the subset now that the correct material and matrices are loaded pMeshContainer->MeshData.pMesh->DrawSubset(iAttrib); } /////////////////////// } // If necessary, draw parts that HW could not handle using SW if (pMeshContainer->iAttributeSW < pMeshContainer->NumAttributeGroups) { AttribIdPrev = UNUSED32; pd3dDevice->SetSoftwareVertexProcessing(TRUE); for (iAttrib = pMeshContainer->iAttributeSW; iAttrib < pMeshContainer->NumAttributeGroups; iAttrib++) { NumBlend = 0; for (DWORD i = 0; i < pMeshContainer->NumInfl; ++i) { if (pBoneComb[iAttrib].BoneId[i] != UINT_MAX) { NumBlend = i; } } if (d3dCaps.MaxVertexBlendMatrices < NumBlend + 1) { // first calculate the world matrices for the current set of blend weights and get the accurate count of the number of blends for (DWORD i = 0; i < pMeshContainer->NumInfl; ++i) { iMatrixIndex = pBoneComb[iAttrib].BoneId[i]; if (iMatrixIndex != UINT_MAX) { D3DXMatrixMultiply(&matTemp, &pMeshContainer->pBoneOffsetMatrices[iMatrixIndex], pMeshContainer->ppBoneMatrixPtrs[iMatrixIndex]); pd3dDevice->SetTransform(D3DTS_WORLDMATRIX(i), &matTemp); } } pd3dDevice->SetRenderState(D3DRS_VERTEXBLEND, NumBlend); // lookup the material used for this subset of faces if ((AttribIdPrev != pBoneComb[iAttrib].AttribId) || (AttribIdPrev == UNUSED32)) { pd3dDevice->SetMaterial(&pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D); pd3dDevice->SetTexture(0, pMeshContainer->ppTextures[pBoneComb[iAttrib].AttribId]); AttribIdPrev = pBoneComb[iAttrib].AttribId; } // draw the subset now that the correct material and matrices are loaded pMeshContainer->MeshData.pMesh->DrawSubset(iAttrib); } } pd3dDevice->SetSoftwareVertexProcessing(FALSE); } pd3dDevice->SetRenderState(D3DRS_VERTEXBLEND, 0); } else if (g_SkinningMethod == D3DINDEXED) { // if hw doesn't support indexed vertex processing, switch to software vertex processing if (pMeshContainer->UseSoftwareVP) { // If hw or pure hw vertex processing is forced, we can't render the // mesh, so just exit out. Typical applications should create // a device with appropriate vertex processing capability for this // skinning method. if (g_dwBehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING) return; pd3dDevice->SetSoftwareVertexProcessing(TRUE); } // set the number of vertex blend indices to be blended if (pMeshContainer->NumInfl == 1) { pd3dDevice->SetRenderState(D3DRS_VERTEXBLEND, D3DVBF_0WEIGHTS); } else { pd3dDevice->SetRenderState(D3DRS_VERTEXBLEND, pMeshContainer->NumInfl - 1); } if (pMeshContainer->NumInfl) pd3dDevice->SetRenderState(D3DRS_INDEXEDVERTEXBLENDENABLE, TRUE); // for each attribute group in the mesh, calculate the set of matrices in the palette and then draw the mesh subset pBoneComb = reinterpret_cast<LPD3DXBONECOMBINATION>(pMeshContainer->pBoneCombinationBuf->GetBufferPointer ()); for (iAttrib = 0; iAttrib < pMeshContainer->NumAttributeGroups; iAttrib++) { // first calculate all the world matrices for (iPaletteEntry = 0; iPaletteEntry < pMeshContainer->NumPaletteEntries; ++iPaletteEntry) { iMatrixIndex = pBoneComb[iAttrib].BoneId[iPaletteEntry]; if (iMatrixIndex != UINT_MAX) { D3DXMatrixMultiply(&matTemp, &pMeshContainer->pBoneOffsetMatrices[iMatrixIndex], pMeshContainer->ppBoneMatrixPtrs[iMatrixIndex]); pd3dDevice->SetTransform(D3DTS_WORLDMATRIX(iPaletteEntry), &matTemp); } } // setup the material of the mesh subset - REMEMBER to use the original pre-skinning attribute id to get the correct material id pd3dDevice->SetMaterial(&pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D); pd3dDevice->SetTexture(0, pMeshContainer->ppTextures[pBoneComb[iAttrib].AttribId]); // finally draw the subset with the current world matrix palette and material state pMeshContainer->MeshData.pMesh->DrawSubset(iAttrib); } // reset blending state pd3dDevice->SetRenderState(D3DRS_INDEXEDVERTEXBLENDENABLE, FALSE); pd3dDevice->SetRenderState(D3DRS_VERTEXBLEND, 0); // remember to reset back to hw vertex processing if software was required if (pMeshContainer->UseSoftwareVP) { pd3dDevice->SetSoftwareVertexProcessing(FALSE); } } else if (g_SkinningMethod == D3DINDEXEDVS) { // Use COLOR instead of UBYTE4 since Geforce3 does not support it // vConst.w should be 3, but due to COLOR/UBYTE4 issue, mul by 255 and add epsilon D3DXVECTOR4 vConst(1.0f, 0.0f, 0.0f, 765.01f); if (pMeshContainer->UseSoftwareVP) { // If hw or pure hw vertex processing is forced, we can't render the // mesh, so just exit out. Typical applications should create // a device with appropriate vertex processing capability for this // skinning method. if (g_dwBehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING) return; pd3dDevice->SetSoftwareVertexProcessing(TRUE); } pd3dDevice->SetVertexShader(g_pIndexedVertexShader[pMeshContainer->NumInfl - 1]); pBoneComb = reinterpret_cast<LPD3DXBONECOMBINATION>(pMeshContainer->pBoneCombinationBuf->GetBufferPointer ()); for (iAttrib = 0; iAttrib < pMeshContainer->NumAttributeGroups; iAttrib++) { // first calculate all the world matrices for (iPaletteEntry = 0; iPaletteEntry < pMeshContainer->NumPaletteEntries; ++iPaletteEntry) { iMatrixIndex = pBoneComb[iAttrib].BoneId[iPaletteEntry]; if (iMatrixIndex != UINT_MAX) { D3DXMatrixMultiply(&matTemp, &pMeshContainer->pBoneOffsetMatrices[iMatrixIndex], pMeshContainer->ppBoneMatrixPtrs[iMatrixIndex]); D3DXMatrixMultiplyTranspose(&matTemp, &matTemp, &g_matView); pd3dDevice->SetVertexShaderConstantF(iPaletteEntry * 3 + 9, (float*)&matTemp, 3); } } // Sum of all ambient and emissive contribution D3DXCOLOR color1(pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D.Ambient); D3DXCOLOR color2(.25, .25, .25, 1.0); D3DXCOLOR ambEmm; D3DXColorModulate(&ambEmm, &color1, &color2); ambEmm += D3DXCOLOR(pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D.Emissive); // set material color properties pd3dDevice->SetVertexShaderConstantF(8, (float*)&( pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D.Diffuse), 1); pd3dDevice->SetVertexShaderConstantF(7, (float*)&ambEmm, 1); vConst.y = pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D.Power; pd3dDevice->SetVertexShaderConstantF(0, (float*)&vConst, 1); pd3dDevice->SetTexture(0, pMeshContainer->ppTextures[pBoneComb[iAttrib].AttribId]); // finally draw the subset with the current world matrix palette and material state pMeshContainer->MeshData.pMesh->DrawSubset(iAttrib); } // remember to reset back to hw vertex processing if software was required if (pMeshContainer->UseSoftwareVP) { pd3dDevice->SetSoftwareVertexProcessing(FALSE); } pd3dDevice->SetVertexShader(NULL); } else if (g_SkinningMethod == D3DINDEXEDHLSLVS) { if (pMeshContainer->UseSoftwareVP) { // If hw or pure hw vertex processing is forced, we can't render the // mesh, so just exit out. Typical applications should create // a device with appropriate vertex processing capability for this // skinning method. if (g_dwBehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING) return; pd3dDevice->SetSoftwareVertexProcessing(TRUE); } pBoneComb = reinterpret_cast<LPD3DXBONECOMBINATION>(pMeshContainer->pBoneCombinationBuf->GetBufferPointer ()); for (iAttrib = 0; iAttrib < pMeshContainer->NumAttributeGroups; iAttrib++) { // first calculate all the world matrices for (iPaletteEntry = 0; iPaletteEntry < pMeshContainer->NumPaletteEntries; ++iPaletteEntry) { iMatrixIndex = pBoneComb[iAttrib].BoneId[iPaletteEntry]; if (iMatrixIndex != UINT_MAX) { D3DXMatrixMultiply(&matTemp, &pMeshContainer->pBoneOffsetMatrices[iMatrixIndex], pMeshContainer->ppBoneMatrixPtrs[iMatrixIndex]); D3DXMatrixMultiply(&g_pBoneMatrices[iPaletteEntry], &matTemp, &g_matView); } } g_pEffect->SetMatrixArray("mWorldMatrixArray", g_pBoneMatrices, pMeshContainer->NumPaletteEntries); // Sum of all ambient and emissive contribution D3DXCOLOR color1(pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D.Ambient); D3DXCOLOR color2(.25, .25, .25, 1.0); D3DXCOLOR ambEmm; D3DXColorModulate(&ambEmm, &color1, &color2); ambEmm += D3DXCOLOR(pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D.Emissive); // set material color properties g_pEffect->SetVector("MaterialDiffuse", (D3DXVECTOR4*)&( pMeshContainer->pMaterials[pBoneComb[iAttrib].AttribId].MatD3D.Diffuse)); g_pEffect->SetVector("MaterialAmbient", (D3DXVECTOR4*)&ambEmm); // setup the material of the mesh subset - REMEMBER to use the original pre-skinning attribute id to get the correct material id pd3dDevice->SetTexture(0, pMeshContainer->ppTextures[pBoneComb[iAttrib].AttribId]); // Set CurNumBones to select the correct vertex shader for the number of bones g_pEffect->SetInt("CurNumBones", pMeshContainer->NumInfl - 1); // Start the effect now all parameters have been updated UINT numPasses; g_pEffect->Begin(&numPasses, D3DXFX_DONOTSAVESTATE); for (UINT iPass = 0; iPass < numPasses; iPass++) { g_pEffect->BeginPass(iPass); // draw the subset with the current world matrix palette and material state pMeshContainer->MeshData.pMesh->DrawSubset(iAttrib); g_pEffect->EndPass(); } g_pEffect->End(); pd3dDevice->SetVertexShader(NULL); } // remember to reset back to hw vertex processing if software was required if (pMeshContainer->UseSoftwareVP) { pd3dDevice->SetSoftwareVertexProcessing(FALSE); } } else if (g_SkinningMethod == SOFTWARE) { D3DXMATRIX Identity; DWORD cBones = pMeshContainer->pSkinInfo->GetNumBones(); DWORD iBone; PBYTE pbVerticesSrc; PBYTE pbVerticesDest; // set up bone transforms for (iBone = 0; iBone < cBones; ++iBone) { D3DXMatrixMultiply ( &g_pBoneMatrices[iBone], // output &pMeshContainer->pBoneOffsetMatrices[iBone], pMeshContainer->ppBoneMatrixPtrs[iBone] ); } // set world transform D3DXMatrixIdentity(&Identity); pd3dDevice->SetTransform(D3DTS_WORLD, &Identity); pMeshContainer->pOrigMesh->LockVertexBuffer(D3DLOCK_READONLY, (LPVOID*)&pbVerticesSrc); pMeshContainer->MeshData.pMesh->LockVertexBuffer(0, (LPVOID*)&pbVerticesDest); // generate skinned mesh pMeshContainer->pSkinInfo->UpdateSkinnedMesh(g_pBoneMatrices, NULL, pbVerticesSrc, pbVerticesDest); pMeshContainer->pOrigMesh->UnlockVertexBuffer(); pMeshContainer->MeshData.pMesh->UnlockVertexBuffer(); for (iAttrib = 0; iAttrib < pMeshContainer->NumAttributeGroups; iAttrib++) { pd3dDevice->SetMaterial(&( pMeshContainer->pMaterials[pMeshContainer->pAttributeTable[iAttrib].AttribId].MatD3D)); pd3dDevice->SetTexture(0, pMeshContainer->ppTextures[pMeshContainer->pAttributeTable[iAttrib].AttribId]); pMeshContainer->MeshData.pMesh->DrawSubset(pMeshContainer->pAttributeTable[iAttrib].AttribId); } } else // bug out as unsupported mode { return; } } else // standard mesh, just draw it after setting material properties { pd3dDevice->SetTransform(D3DTS_WORLD, &pFrame->CombinedTransformationMatrix); for (iMaterial = 0; iMaterial < pMeshContainer->NumMaterials; iMaterial++) { if (mIsEffect) pd3dDevice->SetMaterial(&d3d::WHITE_MTRL); else pd3dDevice->SetMaterial(&pMeshContainer->pMaterials[iMaterial].MatD3D); pd3dDevice->SetTexture(0, pMeshContainer->ppTextures[iMaterial]); pMeshContainer->MeshData.pMesh->DrawSubset(iMaterial); } } } void CModel::DrawFrame(IDirect3DDevice9* pd3dDevice, LPD3DXFRAME pFrame) { LPD3DXMESHCONTAINER pMeshContainer; pMeshContainer = pFrame->pMeshContainer; while (pMeshContainer != NULL) { DrawMeshContainer(pd3dDevice, pMeshContainer, pFrame); pMeshContainer = pMeshContainer->pNextMeshContainer; } if (pFrame->pFrameSibling != NULL) { DrawFrame(pd3dDevice, pFrame->pFrameSibling); } if (pFrame->pFrameFirstChild != NULL) { DrawFrame(pd3dDevice, pFrame->pFrameFirstChild); } } HRESULT CModel::SetupBoneMatrixPointers(LPD3DXFRAME pFrame) { HRESULT hr; if (pFrame->pMeshContainer != NULL) { hr = SetupBoneMatrixPointersOnMesh(pFrame->pMeshContainer); if (FAILED(hr)) return hr; } if (pFrame->pFrameSibling != NULL) { hr = SetupBoneMatrixPointers(pFrame->pFrameSibling); if (FAILED(hr)) return hr; } if (pFrame->pFrameFirstChild != NULL) { hr = SetupBoneMatrixPointers(pFrame->pFrameFirstChild); if (FAILED(hr)) return hr; } return S_OK; } HRESULT CModel::SetupBoneMatrixPointersOnMesh(LPD3DXMESHCONTAINER pMeshContainerBase) { UINT iBone, cBones; D3DXFRAME_DERIVED* pFrame; D3DXMESHCONTAINER_DERIVED* pMeshContainer = (D3DXMESHCONTAINER_DERIVED*)pMeshContainerBase; // if there is a skinmesh, then setup the bone matrices if (pMeshContainer->pSkinInfo != NULL) { cBones = pMeshContainer->pSkinInfo->GetNumBones(); pMeshContainer->ppBoneMatrixPtrs = new D3DXMATRIX*[cBones]; if (pMeshContainer->ppBoneMatrixPtrs == NULL) return E_OUTOFMEMORY; for (iBone = 0; iBone < cBones; iBone++) { pFrame = (D3DXFRAME_DERIVED*)D3DXFrameFind(m_pFrameRoot, pMeshContainer->pSkinInfo->GetBoneName(iBone)); if (pFrame == NULL) return E_FAIL; pMeshContainer->ppBoneMatrixPtrs[iBone] = &pFrame->CombinedTransformationMatrix; } } return S_OK; } void CModel::LoadXFile(wchar_t* strFileName, LPDIRECT3DDEVICE9 pd3dDevice) { HRESULT hr; hr = D3DXLoadMeshHierarchyFromX(strFileName, D3DXMESH_MANAGED, pd3dDevice, &Alloc, NULL, &m_pFrameRoot, &m_pAnimController); if (hr == D3DERR_INVALIDCALL) { ::MessageBox(0, L"D3DXLoadMeshHierarchyFromX() - FAILED", 0, 0); } SetupBoneMatrixPointers(m_pFrameRoot); } void CModel::SelectAnimation(int n) { LPD3DXANIMATIONSET pAnimSet; m_pAnimController->GetAnimationSet(n, &pAnimSet); m_pAnimController->SetTrackAnimationSet(0, pAnimSet); m_pAnimController->ResetTime(); mCurrAnimNum = n; } void CModel::selectAnimationPlayOnce(int n, float timeDelta) { LPD3DXANIMATIONSET pAnimSet; m_pAnimController->GetAnimationSet(n, &pAnimSet); m_pAnimController->SetTrackAnimationSet(0, pAnimSet); m_pAnimController->ResetTime(); mCurrAnimNum = n; double d = pAnimSet->GetPeriod(); if (mAnimTime > pAnimSet->GetPeriod() - 0.05f) { m_pAnimController->SetTrackPosition(0, pAnimSet->GetPeriod() - 0.05f); } mAnimTime += timeDelta; } HRESULT GenerateSkinnedMesh(IDirect3DDevice9* pd3dDevice, D3DXMESHCONTAINER_DERIVED* pMeshContainer) { HRESULT hr = S_OK; D3DCAPS9 d3dCaps; pd3dDevice->GetDeviceCaps(&d3dCaps); if (pMeshContainer->pSkinInfo == NULL) return hr; g_bUseSoftwareVP = false; SAFE_RELEASE(pMeshContainer->MeshData.pMesh); SAFE_RELEASE(pMeshContainer->pBoneCombinationBuf); // if non-indexed skinning mode selected, use ConvertToBlendedMesh to generate drawable mesh if (g_SkinningMethod == D3DNONINDEXED) { hr = pMeshContainer->pSkinInfo->ConvertToBlendedMesh ( pMeshContainer->pOrigMesh, D3DXMESH_MANAGED | D3DXMESHOPT_VERTEXCACHE, pMeshContainer->pAdjacency, NULL, NULL, NULL, &pMeshContainer->NumInfl, &pMeshContainer->NumAttributeGroups, &pMeshContainer->pBoneCombinationBuf, &pMeshContainer->MeshData.pMesh ); if (FAILED(hr)) goto e_Exit; // If the device can only do 2 matrix blends, ConvertToBlendedMesh cannot approximate all meshes to it // Thus we split the mesh in two parts: The part that uses at most 2 matrices and the rest. The first is // drawn using the device's HW vertex processing and the rest is drawn using SW vertex processing. LPD3DXBONECOMBINATION rgBoneCombinations = reinterpret_cast<LPD3DXBONECOMBINATION>( pMeshContainer->pBoneCombinationBuf->GetBufferPointer()); // look for any set of bone combinations that do not fit the caps for (pMeshContainer->iAttributeSW = 0; pMeshContainer->iAttributeSW < pMeshContainer->NumAttributeGroups; pMeshContainer->iAttributeSW++) { DWORD cInfl = 0; for (DWORD iInfl = 0; iInfl < pMeshContainer->NumInfl; iInfl++) { if (rgBoneCombinations[pMeshContainer->iAttributeSW].BoneId[iInfl] != UINT_MAX) { ++cInfl; } } if (cInfl > d3dCaps.MaxVertexBlendMatrices) { break; } } // if there is both HW and SW, add the Software Processing flag if (pMeshContainer->iAttributeSW < pMeshContainer->NumAttributeGroups) { LPD3DXMESH pMeshTmp; hr = pMeshContainer->MeshData.pMesh->CloneMeshFVF(D3DXMESH_SOFTWAREPROCESSING | pMeshContainer->MeshData.pMesh->GetOptions(), pMeshContainer->MeshData.pMesh->GetFVF(), pd3dDevice, &pMeshTmp); if (FAILED(hr)) { goto e_Exit; } pMeshContainer->MeshData.pMesh->Release(); pMeshContainer->MeshData.pMesh = pMeshTmp; pMeshTmp = NULL; } } // if indexed skinning mode selected, use ConvertToIndexedsBlendedMesh to generate drawable mesh else if (g_SkinningMethod == D3DINDEXED) { DWORD NumMaxFaceInfl; DWORD Flags = D3DXMESHOPT_VERTEXCACHE; LPDIRECT3DINDEXBUFFER9 pIB; hr = pMeshContainer->pOrigMesh->GetIndexBuffer(&pIB); if (FAILED(hr)) goto e_Exit; hr = pMeshContainer->pSkinInfo->GetMaxFaceInfluences(pIB, pMeshContainer->pOrigMesh->GetNumFaces(), &NumMaxFaceInfl); pIB->Release(); if (FAILED(hr)) goto e_Exit; // 12 entry palette guarantees that any triangle (4 independent influences per vertex of a tri) // can be handled NumMaxFaceInfl = min(NumMaxFaceInfl, 12); if (d3dCaps.MaxVertexBlendMatrixIndex + 1 < NumMaxFaceInfl) { // HW does not support indexed vertex blending. Use SW instead pMeshContainer->NumPaletteEntries = min(256, pMeshContainer->pSkinInfo->GetNumBones()); pMeshContainer->UseSoftwareVP = true; g_bUseSoftwareVP = true; Flags |= D3DXMESH_SYSTEMMEM; } else { // using hardware - determine palette size from caps and number of bones // If normals are present in the vertex data that needs to be blended for lighting, then // the number of matrices is half the number specified by MaxVertexBlendMatrixIndex. pMeshContainer->NumPaletteEntries = min((d3dCaps.MaxVertexBlendMatrixIndex + 1) / 2, pMeshContainer->pSkinInfo->GetNumBones()); pMeshContainer->UseSoftwareVP = false; Flags |= D3DXMESH_MANAGED; } hr = pMeshContainer->pSkinInfo->ConvertToIndexedBlendedMesh ( pMeshContainer->pOrigMesh, Flags, pMeshContainer->NumPaletteEntries, pMeshContainer->pAdjacency, NULL, NULL, NULL, &pMeshContainer->NumInfl, &pMeshContainer->NumAttributeGroups, &pMeshContainer->pBoneCombinationBuf, &pMeshContainer->MeshData.pMesh); if (FAILED(hr)) goto e_Exit; } // if vertex shader indexed skinning mode selected, use ConvertToIndexedsBlendedMesh to generate drawable mesh else if ((g_SkinningMethod == D3DINDEXEDVS) || (g_SkinningMethod == D3DINDEXEDHLSLVS)) { // Get palette size // First 9 constants are used for other data. Each 4x3 matrix takes up 3 constants. // (96 - 9) /3 i.e. Maximum constant count - used constants UINT MaxMatrices = 26; pMeshContainer->NumPaletteEntries = min(MaxMatrices, pMeshContainer->pSkinInfo->GetNumBones()); DWORD Flags = D3DXMESHOPT_VERTEXCACHE; if (d3dCaps.VertexShaderVersion >= D3DVS_VERSION(1, 1)) { pMeshContainer->UseSoftwareVP = false; Flags |= D3DXMESH_MANAGED; } else { pMeshContainer->UseSoftwareVP = true; g_bUseSoftwareVP = true; Flags |= D3DXMESH_SYSTEMMEM; } SAFE_RELEASE(pMeshContainer->MeshData.pMesh); hr = pMeshContainer->pSkinInfo->ConvertToIndexedBlendedMesh ( pMeshContainer->pOrigMesh, Flags, pMeshContainer->NumPaletteEntries, pMeshContainer->pAdjacency, NULL, NULL, NULL, &pMeshContainer->NumInfl, &pMeshContainer->NumAttributeGroups, &pMeshContainer->pBoneCombinationBuf, &pMeshContainer->MeshData.pMesh); if (FAILED(hr)) goto e_Exit; // FVF has to match our declarator. Vertex shaders are not as forgiving as FF pipeline DWORD NewFVF = (pMeshContainer->MeshData.pMesh->GetFVF() & D3DFVF_POSITION_MASK) | D3DFVF_NORMAL | D3DFVF_TEX1 | D3DFVF_LASTBETA_UBYTE4; if (NewFVF != pMeshContainer->MeshData.pMesh->GetFVF()) { LPD3DXMESH pMesh; hr = pMeshContainer->MeshData.pMesh->CloneMeshFVF(pMeshContainer->MeshData.pMesh->GetOptions(), NewFVF, pd3dDevice, &pMesh); if (!FAILED(hr)) { pMeshContainer->MeshData.pMesh->Release(); pMeshContainer->MeshData.pMesh = pMesh; pMesh = NULL; } } D3DVERTEXELEMENT9 pDecl[MAX_FVF_DECL_SIZE]; LPD3DVERTEXELEMENT9 pDeclCur; hr = pMeshContainer->MeshData.pMesh->GetDeclaration(pDecl); if (FAILED(hr)) goto e_Exit; // the vertex shader is expecting to interpret the UBYTE4 as a D3DCOLOR, so update the type // NOTE: this cannot be done with CloneMesh, that would convert the UBYTE4 data to float and then to D3DCOLOR // this is more of a "cast" operation pDeclCur = pDecl; while (pDeclCur->Stream != 0xff) { if ((pDeclCur->Usage == D3DDECLUSAGE_BLENDINDICES) && (pDeclCur->UsageIndex == 0)) pDeclCur->Type = D3DDECLTYPE_D3DCOLOR; pDeclCur++; } hr = pMeshContainer->MeshData.pMesh->UpdateSemantics(pDecl); if (FAILED(hr)) goto e_Exit; // allocate a buffer for bone matrices, but only if another mesh has not allocated one of the same size or larger if (g_NumBoneMatricesMax < pMeshContainer->pSkinInfo->GetNumBones()) { g_NumBoneMatricesMax = pMeshContainer->pSkinInfo->GetNumBones(); // Allocate space for blend matrices delete[] g_pBoneMatrices; g_pBoneMatrices = new D3DXMATRIXA16[g_NumBoneMatricesMax]; if (g_pBoneMatrices == NULL) { hr = E_OUTOFMEMORY; goto e_Exit; } } } // if software skinning selected, use GenerateSkinnedMesh to create a mesh that can be used with UpdateSkinnedMesh else if (g_SkinningMethod == SOFTWARE) { hr = pMeshContainer->pOrigMesh->CloneMeshFVF(D3DXMESH_MANAGED, pMeshContainer->pOrigMesh->GetFVF(), pd3dDevice, &pMeshContainer->MeshData.pMesh); if (FAILED(hr)) goto e_Exit; hr = pMeshContainer->MeshData.pMesh->GetAttributeTable(NULL, &pMeshContainer->NumAttributeGroups); if (FAILED(hr)) goto e_Exit; delete[] pMeshContainer->pAttributeTable; pMeshContainer->pAttributeTable = new D3DXATTRIBUTERANGE[pMeshContainer->NumAttributeGroups]; if (pMeshContainer->pAttributeTable == NULL) { hr = E_OUTOFMEMORY; goto e_Exit; } hr = pMeshContainer->MeshData.pMesh->GetAttributeTable(pMeshContainer->pAttributeTable, NULL); if (FAILED(hr)) goto e_Exit; // allocate a buffer for bone matrices, but only if another mesh has not allocated one of the same size or larger if (g_NumBoneMatricesMax < pMeshContainer->pSkinInfo->GetNumBones()) { g_NumBoneMatricesMax = pMeshContainer->pSkinInfo->GetNumBones(); // Allocate space for blend matrices delete[] g_pBoneMatrices; g_pBoneMatrices = new D3DXMATRIXA16[g_NumBoneMatricesMax]; if (g_pBoneMatrices == NULL) { hr = E_OUTOFMEMORY; goto e_Exit; } } } else // invalid g_SkinningMethod value { // return failure due to invalid skinning method value hr = E_INVALIDARG; goto e_Exit; } e_Exit: return hr; } void CModel::Draw(IDirect3DDevice9* pd3dDevice, float timeDelta) { D3DXMatrixMultiply(&worldMatrix, &rotateMatrix, &worldMatrix); pd3dDevice->SetTransform(D3DTS_WORLD, &worldMatrix); if (m_pAnimController != NULL) m_pAnimController->AdvanceTime(timeDelta, NULL); UpdateFrameMatrices(m_pFrameRoot, &worldMatrix); DrawFrame(pd3dDevice, m_pFrameRoot); } void CModel::setScale(D3DXVECTOR3 setValue) { D3DXMatrixScaling(&scaleMatrix, setValue.x, setValue.y, setValue.z); D3DXMatrixMultiply(&worldMatrix, &scaleMatrix, &worldMatrix); } void CModel::setMeshData(LPD3DXFRAME frameRoot, LPD3DXANIMATIONCONTROLLER animController) { m_pFrameRoot = frameRoot; animController->CloneAnimationController(animController->GetMaxNumAnimationOutputs(), animController->GetMaxNumAnimationSets(), animController->GetMaxNumTracks(), animController->GetMaxNumEvents(), &m_pAnimController); SetupBoneMatrixPointers(m_pFrameRoot); } void CModel::initModel() { D3DXMatrixIdentity(&worldMatrix); D3DXMatrixIdentity(&rotateMatrix); D3DXMatrixIdentity(&scaleMatrix); mCurrAnimNum = 0; mAnimTime = 0.0f; }<file_sep>/d3dUtility.h ////////////////////////////////////////////////////////////////////////////////////////////////// // // File: d3dUtility.h // // Author: <NAME> (C) All Rights Reserved // // System: AMD Athlon 1800+ XP, 512 DDR, Geforce 3, Windows XP, MSVC++ 7.0 // // Desc: Provides utility functions for simplifying common tasks. // ////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef __d3dUtilityH__ #define __d3dUtilityH__ #define DIRECTINPUT_VERSION 0x0800 #include <WinSock2.h> #include <d3dx9.h> #include <dinput.h> #include <DxErr.h> #include <string> #include <limits> #include <assert.h> #include <windowsx.h> #define PI 3.14159265359 #define UP_KEY 1 #define DOWN_KEY 2 #define LEFT_KEY 3 #define RIGHT_KEY 4 #define NO_KEY_DOWN 5 #define UPPER_BODY_LOAD 1 #define LOWER_BODY_LOAD 2 #define ALL_LOAD 3 #define NANOSUIT_LOWER_BODY_BONES 9 namespace d3d { // // Init // HWND InitD3D( HINSTANCE hInstance, // [in] Application instance. int width, int height, // [in] Backbuffer dimensions. bool windowed, // [in] Windowed (true)or full screen (false). D3DDEVTYPE deviceType, // [in] HAL or REF IDirect3DDevice9** device, // [out]The created device. LPD3DXSPRITE* pSprite); int EnterMsgLoop( bool (*ptr_display)(float timeDelta)); LRESULT CALLBACK WndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); // // Cleanup // template<class T> void Release(T t) { if( t ) { t->Release(); t = 0; } } template<class T> void Delete(T t) { if( t ) { delete t; t = 0; } } // // Colors // const D3DXCOLOR WHITE( D3DCOLOR_XRGB(255, 255, 255) ); const D3DXCOLOR BLACK( D3DCOLOR_XRGB( 0, 0, 0) ); const D3DXCOLOR RED( D3DCOLOR_XRGB(255, 0, 0) ); const D3DXCOLOR GREEN( D3DCOLOR_XRGB( 0, 255, 0) ); const D3DXCOLOR BLUE( D3DCOLOR_XRGB( 0, 0, 255) ); const D3DXCOLOR YELLOW( D3DCOLOR_XRGB(255, 255, 0) ); const D3DXCOLOR CYAN( D3DCOLOR_XRGB( 0, 255, 255) ); const D3DXCOLOR MAGENTA( D3DCOLOR_XRGB(255, 0, 255) ); const D3DXCOLOR BEACH_SAND(D3DCOLOR_XRGB(255, 249, 157)); const D3DXCOLOR DESERT_SAND(D3DCOLOR_XRGB(250, 205, 135)); const D3DXCOLOR LIGHTGREEN(D3DCOLOR_XRGB(60, 184, 120)); const D3DXCOLOR PUREGREEN(D3DCOLOR_XRGB(0, 166, 81)); const D3DXCOLOR DARKGREEN(D3DCOLOR_XRGB(0, 114, 54)); const D3DXCOLOR LIGHT_YELLOW_GREEN(D3DCOLOR_XRGB(124, 197, 118)); const D3DXCOLOR PURE_YELLOW_GREEN(D3DCOLOR_XRGB(57, 181, 74)); const D3DXCOLOR DARK_YELLOW_GREEN(D3DCOLOR_XRGB(25, 123, 48)); const D3DXCOLOR LIGHTBROWN(D3DCOLOR_XRGB(198, 156, 109)); const D3DXCOLOR DARKBROWN(D3DCOLOR_XRGB(115, 100, 87)); // // Lights // D3DLIGHT9 InitDirectionalLight(D3DXVECTOR3* direction, D3DXCOLOR* color); D3DLIGHT9 InitPointLight(D3DXVECTOR3* position, D3DXCOLOR* color); D3DLIGHT9 InitSpotLight(D3DXVECTOR3* position, D3DXVECTOR3* direction, D3DXCOLOR* color); // // Materials // D3DMATERIAL9 InitMtrl(D3DXCOLOR a, D3DXCOLOR d, D3DXCOLOR s, D3DXCOLOR e, float p); const D3DMATERIAL9 WHITE_MTRL = InitMtrl(WHITE, WHITE, WHITE, BLACK, 2.0f); const D3DMATERIAL9 RED_MTRL = InitMtrl(RED, RED, RED, BLACK, 2.0f); const D3DMATERIAL9 GREEN_MTRL = InitMtrl(GREEN, GREEN, GREEN, BLACK, 2.0f); const D3DMATERIAL9 BLUE_MTRL = InitMtrl(BLUE, BLUE, BLUE, BLACK, 2.0f); const D3DMATERIAL9 YELLOW_MTRL = InitMtrl(YELLOW, YELLOW, YELLOW, BLACK, 2.0f); int CountFrame(float timeDelta); // // Fonts // LPD3DXFONT InitFont(IDirect3DDevice9* device, LPD3DXSPRITE &pSprite); // // Bounding Objects // struct BoundingBox { BoundingBox(); bool isPointInside(D3DXVECTOR3& p); D3DXVECTOR3 _min; D3DXVECTOR3 _max; }; struct BoundingSphere { BoundingSphere(); D3DXVECTOR3 _center; float _radius; }; struct Ray { D3DXVECTOR3 _origin; D3DXVECTOR3 _direction; }; // // Constants // const float Infinity = FLT_MAX; const float EPSILON = 0.001f; // // Drawing // // Function references "desert.bmp" internally. This file must // be in the working directory. bool DrawBasicScene( IDirect3DDevice9* device,// Pass in 0 for cleanup. float scale); // uniform scale // // Vertex Structures // struct Vertex { Vertex(){} Vertex(float x, float y, float z, float nx, float ny, float nz, float u, float v) { _x = x; _y = y; _z = z; _nx = nx; _ny = ny; _nz = nz; _u = u; _v = v; } float _x, _y, _z; float _nx, _ny, _nz; float _u, _v; static const DWORD FVF; }; // // Randomness // // Desc: Return random float in [lowBound, highBound] interval. float GetRandomFloat(float lowBound, float highBound); // Desc: Returns a random vector in the bounds specified by min and max. void GetRandomVector( D3DXVECTOR3* out, D3DXVECTOR3* min, D3DXVECTOR3* max); // // Conversion // DWORD FtoDw(float f); // // Interpolation // float Lerp(float a, float b, float t); } wchar_t* CharToWideChar(const char* str); //////////////////////////애니메이션 class CAllocateHierarchy : public ID3DXAllocateHierarchy { public: STDMETHOD(CreateFrame)(THIS_ LPCSTR Name, LPD3DXFRAME *ppNewFrame); STDMETHOD(CreateMeshContainer)(THIS_ LPCSTR Name, CONST D3DXMESHDATA *pMeshData, CONST D3DXMATERIAL *pMaterials, CONST D3DXEFFECTINSTANCE *pEffectInstances, DWORD NumMaterials, CONST DWORD *pAdjacency, LPD3DXSKININFO pSkinInfo, LPD3DXMESHCONTAINER *ppNewMeshContainer); STDMETHOD(DestroyFrame)(THIS_ LPD3DXFRAME pFrameToFree); STDMETHOD(DestroyMeshContainer)(THIS_ LPD3DXMESHCONTAINER pMeshContainerBase); CAllocateHierarchy() { } }; #ifndef SAFE_DELETE #define SAFE_DELETE(p) { if (p) { delete (p); (p)=NULL; } } #endif #ifndef SAFE_DELETE_ARRAY #define SAFE_DELETE_ARRAY(p) { if (p) { delete[] (p); (p)=NULL; } } #endif #ifndef SAFE_RELEASE #define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p)=NULL; } } #endif enum METHOD { D3DNONINDEXED, D3DINDEXED, SOFTWARE, D3DINDEXEDVS, D3DINDEXEDHLSLVS, NONE }; struct D3DXFRAME_DERIVED : public D3DXFRAME { D3DXMATRIXA16 CombinedTransformationMatrix; }; struct D3DXMESHCONTAINER_DERIVED : public D3DXMESHCONTAINER { LPDIRECT3DTEXTURE9* ppTextures; // array of textures, entries are NULL if no texture specified // SkinMesh info LPD3DXMESH pOrigMesh; LPD3DXATTRIBUTERANGE pAttributeTable; DWORD NumAttributeGroups; DWORD NumInfl; LPD3DXBUFFER pBoneCombinationBuf; D3DXMATRIX** ppBoneMatrixPtrs; D3DXMATRIX* pBoneOffsetMatrices; DWORD NumPaletteEntries; bool UseSoftwareVP; DWORD iAttributeSW; // used to denote the split between SW and HW if necessary for non-indexed skinning }; HRESULT GenerateSkinnedMesh(IDirect3DDevice9* pd3dDevice, D3DXMESHCONTAINER_DERIVED* pMeshContainer); void UpdateFrameMatrices(LPD3DXFRAME pFrameBase, LPD3DXMATRIX pParentMatrix); #endif // __d3dUtilityH__<file_sep>/Billboard.cpp #include "Billboard.h" Billboard::Billboard() { D3DXMatrixIdentity(&worldMatrix); animTime = 0.0f; frameNum = 0.0f; visible = false; } Billboard::Billboard(float x, float y, float z) { D3DXMatrixIdentity(&worldMatrix); animTime = 0.0f; frameNum = 0.0f; visible = false; } Billboard::~Billboard() { } void Billboard::createQuad(LPDIRECT3DDEVICE9 pd3dDevice, int indexNum, int width, int height) { pd3dDevice->CreateVertexBuffer(6 * indexNum * sizeof(d3d::Vertex), D3DUSAGE_WRITEONLY, d3d::Vertex::FVF, D3DPOOL_MANAGED, &quad, 0); frameNum = indexNum; quad->Lock(0, 0, (void**)&v, 0); for (int i = 0; i < indexNum * 6; i += 6) { v[i] = d3d::Vertex(-100.0f, -100.0f, 0.0f, 0.0f, 0.0f, -100.0f, ((float)(i) / (float)(width * 6)) - (i / (width * 6)), ((float)(1 + (i / (width * 6))) / (float)height)); v[i + 1] = d3d::Vertex(-100.0f, 100.0f, 0.0f, 0.0f, 0.0f, -100.0f, ((float)(i) / (float)(width * 6)) - (i / (width * 6)), ((float)(i / (width * 6)) / (float)height)); v[i + 2] = d3d::Vertex(100.0f, 100.0f, 0.0f, 0.0f, 0.0f, -100.0f, ((float)(i + 6) / (float)(width * 6)) - (i / (width * 6)), ((float)(i / (width * 6)) / (float)height)); v[i + 3] = d3d::Vertex(-100.0f, -100.0f, 0.0f, 0.0f, 0.0f, -100.0f, ((float)(i) / (float)(width * 6)) - (i / (width * 6)), ((float)(1 + (i / (width * 6))) / (float)height)); v[i + 4] = d3d::Vertex(100.0f, 100.0f, 0.0f, 0.0f, 0.0f, -100.0f, ((float)(i + 6) / (float)(width * 6)) - (i / (width * 6)), ((float)(i / (width * 6)) / (float)height)); v[i + 5] = d3d::Vertex(100.0f, -100.0f, 0.0f, 0.0f, 0.0f, -100.0f, ((float)(i + 6) / (float)(width * 6)) - (i / (width * 6)), ((float)(1 + (i / (width * 6))) / (float)height)); } quad->Unlock(); pd3dDevice->CreateIndexBuffer(6 * indexNum * sizeof(WORD), D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_MANAGED, &IB, 0); WORD* indices = 0; IB->Lock(0, 0, (void**)&indices, 0); for (int i = 0; i < indexNum * 6; i += 6) { indices[i] = 0; indices[i + 1] = 1; indices[i + 2] = 2; indices[i + 3] = 3; indices[i + 4] = 4; indices[i + 5] = 5; } IB->Unlock(); } void Billboard::setPos(D3DXVECTOR3 vec) { worldMatrix._41 = vec.x; worldMatrix._42 = vec.y; worldMatrix._43 = vec.z; } void Billboard::setMatrix(D3DXMATRIX* mat) { worldMatrix._11 = mat->_11; worldMatrix._21 = mat->_21; worldMatrix._31 = mat->_31; worldMatrix._13 = mat->_13; worldMatrix._23 = mat->_23; worldMatrix._23 = mat->_23; } HRESULT Billboard::loadTexture(wchar_t* strTexName, LPDIRECT3DDEVICE9 pd3dDevice) { HRESULT hr; hr = D3DXCreateTextureFromFile(pd3dDevice, strTexName, &tex); return hr; } void Billboard::scaleBillboard(float x, float y, float z) { D3DXMATRIX mat; D3DXMatrixIdentity(&mat); D3DXMatrixScaling(&mat, x, y, z); worldMatrix = mat * worldMatrix; } void Billboard::drawBillboard(LPDIRECT3DDEVICE9 pd3dDevice, float timeDelta) { pd3dDevice->SetTexture(0, tex); pd3dDevice->SetStreamSource(0, quad, 0, sizeof(d3d::Vertex)); pd3dDevice->SetIndices(IB); pd3dDevice->SetFVF(d3d::Vertex::FVF); pd3dDevice->SetTransform(D3DTS_WORLD, &worldMatrix); static float countTimer = 0.0f; float runningTime = animTime; static int frameIndex = 0; if (countTimer > ((float)frameIndex / frameNum) * runningTime) frameIndex += 1; if ((float)frameIndex / frameNum >= 1.0f) { frameIndex = 0.0f; countTimer = 0.0f; } else countTimer += timeDelta; pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 6 * frameIndex, 0, 6, 0, 2); } void Billboard::drawBillboardOnce(LPDIRECT3DDEVICE9 pd3dDevice, float timeDelta) { pd3dDevice->SetTexture(0, tex); pd3dDevice->SetStreamSource(0, quad, 0, sizeof(d3d::Vertex)); pd3dDevice->SetIndices(IB); pd3dDevice->SetFVF(d3d::Vertex::FVF); pd3dDevice->SetTransform(D3DTS_WORLD, &worldMatrix); static float countTimer = 0.0f; float runningTime = animTime; static int frameIndex = 0; if (visible) { if (countTimer > ((float)frameIndex / frameNum) * runningTime) frameIndex += 1; if ((float)frameIndex / frameNum >= 1.0f) { frameIndex = 0.0f; countTimer = 0.0f; visible = false; } else countTimer += timeDelta; pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 6 * frameIndex, 0, 6, 0, 2); } } <file_sep>/SkyBox.cpp #include "SkyBox.h" SkyBox::SkyBox() { mPos = D3DXVECTOR3(0.0f, 1000.0f, 0.0f); } SkyBox::~SkyBox() { } void SkyBox::loadModel(wchar_t* strFileName, LPDIRECT3DDEVICE9 pd3dDevice) { mSkyBoxModel.LoadXFile(strFileName, pd3dDevice); } void SkyBox::drawSkyBox(LPDIRECT3DDEVICE9 pd3dDevice, float timeDelta) { mSkyBoxModel.setModelPosition(mPos); mSkyBoxModel.Draw(pd3dDevice, timeDelta); } <file_sep>/AlienSoldier.cpp #include "AlienSoldier.h" void AlienSoldier::updateStateMachine() { m_pStateMachine->Update(); } void AlienSoldier::moveAlien(Vector3 dest) { mPos.x += dest.x * mTraceSpeed; mPos.y += dest.y * mTraceSpeed; mPos.z += dest.z * mTraceSpeed; }<file_sep>/CModel.h #pragma once #include "d3dUtility.h" class CModel { public: CModel(); ~CModel(); void setworldMatrix(D3DXMATRIX setValue) { worldMatrix = setValue; } void setroateMatrix(D3DXMATRIX setValue) { rotateMatrix = setValue; } D3DXMATRIX getworldMatrix() { return worldMatrix; } D3DXMATRIX getrotateMatrix() { return rotateMatrix; } LPD3DXANIMATIONCONTROLLER getAnimController() { return m_pAnimController; } void initModel(); void initRotateMatrix() { D3DXMatrixIdentity(&rotateMatrix); } void rotateMatrixMultiply(D3DXMATRIX mat) { D3DXMatrixMultiply(&rotateMatrix, &mat, &rotateMatrix); } void SelectAnimation(int n); void selectAnimationPlayOnce(int n, float timeDelta); void Draw(IDirect3DDevice9* pd3dDevice, float timeDelta); void LoadXFile(wchar_t* strFileName, LPDIRECT3DDEVICE9 pd3dDevice); void setMeshData(LPD3DXFRAME frameRoot, LPD3DXANIMATIONCONTROLLER animController); void setModelPosition(D3DXVECTOR3 pos) { worldMatrix._41 = pos.x; worldMatrix._42 = pos.y; worldMatrix._43 = pos.z; } void setIsEffect(bool setValue) { mIsEffect = setValue; } void setScale(D3DXVECTOR3 setValue); LPD3DXFRAME getFrameData() { return m_pFrameRoot; } int getCurrAnimNum() { return mCurrAnimNum; } private: CAllocateHierarchy Alloc; LPD3DXANIMATIONCONTROLLER m_pAnimController; LPD3DXFRAME m_pFrameRoot; void DrawMeshContainer(IDirect3DDevice9* pd3dDevice, LPD3DXMESHCONTAINER pMeshContainerBase, LPD3DXFRAME pFrameBase); void DrawFrame(IDirect3DDevice9* pd3dDevice, LPD3DXFRAME pFrame); HRESULT SetupBoneMatrixPointers(LPD3DXFRAME pFrame); HRESULT SetupBoneMatrixPointersOnMesh(LPD3DXMESHCONTAINER pMeshContainerBase); D3DXMATRIX worldMatrix; D3DXMATRIX rotateMatrix; D3DXMATRIX scaleMatrix; bool mIsEffect; int mCurrAnimNum; float mAnimTime; };<file_sep>/Effect.h #pragma once #include "CModel.h" class Effect { public: Effect(); ~Effect(); CModel* getModel() { return &effect; } void setVisible(bool setValue) { visible = setValue; } bool getVisible() { return visible; } void setWorldMatrix(D3DXMATRIX mat) { effect.setworldMatrix(mat); } void rotateYawToCamera(D3DXVECTOR3 cameraPos); void rotatePitchToCamera(D3DXVECTOR3 cameraPos); void rotateY(float angle); void loadEffect(wchar_t* strFileName, LPDIRECT3DDEVICE9 pd3dDevice); void setPos(D3DXVECTOR3 pos) { effect.setModelPosition(pos); } void drawEffect(LPDIRECT3DDEVICE9 pd3dDevice, float timeDelta); private: CModel effect; bool visible; };
bab030e5efbe6189d9b61434bb92f1f6cd4cb218
[ "C", "C++" ]
27
C++
di8735/Access
ed2c9a6e5f24a95fe46158838f4f7abba8ebf3e4
adc3a3bae5b048a19638797da6facefc7f79b25d
refs/heads/master
<repo_name>Alexis0308/Brive<file_sep>/EvaluacionTecnica/Pantallas/Login.aspx.cs using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace EvaluacionTecnica.Pantallas { public partial class Login : System.Web.UI.Page { SqlConnection conexion = new SqlConnection("Data source=DESKTOP-LRRUQCG; Initial Catalog=Empresa; User=sae; Password=sae"); protected void Page_Load(object sender, EventArgs e) { } protected void btnInicio_Click(object sender, EventArgs e) { Inicio(); } protected void Inicio() { string script = "alert('Usuario o contraseña incorrecto')"; if (txtUsuario.Text.Length > 0 && txtPassword.Text.Length > 0) { string usuario = Convert.ToString(txtUsuario.Text); string password = Convert.ToString(txtPassword.Text); string user="", pass=""; int ID = 0; try { conexion.Open(); string query = "select * from sucursales where Nombre_suc = '" + usuario + "' and Contraseña = '" + password + "'"; SqlCommand selec = new SqlCommand(query, conexion); SqlDataReader registros = selec.ExecuteReader(); if (registros.Read()) { ID = Convert.ToInt32(registros["ID_Sucursal"]); Session["ID_s"] = ID; user = Convert.ToString(registros["Nombre_suc"]); pass = Convert.ToString(registros["Contraseña"]); } conexion.Close(); if (user.Length > 0 && pass.Length > 0) { HttpContext.Current.Response.Redirect("../Pantallas/Inventario.aspx"); } else { ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", script, true); } } catch (Exception ex) { ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", script+ex, true); } } else { ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", script, true); } } protected void btnAgregar_Click(object sender, EventArgs e) { lblTitulo.Visible = false; lblTitulo2.Visible = true; btnCrear.Visible = true; btnRegresa.Visible = true; btnInicio.Visible = false; btnAgregar.Visible = false; } protected void btnRegresa_Click(object sender, EventArgs e) { btnCrear.Visible = false; btnRegresa.Visible = false; btnInicio.Visible = true; btnAgregar.Visible = true; } protected void btnCrear_Click(object sender, EventArgs e) { string usuario = Convert.ToString(txtUsuario.Text); string pass = Convert.ToString(txtPassword.Text); conexion.Open(); string query = "insert into sucursales (Nombre_suc,Contraseña) values ('"+usuario+"','"+pass+"')"; SqlCommand insertar = new SqlCommand (query, conexion); insertar.ExecuteNonQuery(); conexion.Close(); } } }<file_sep>/EvaluacionTecnica/Pantallas/Inventario.aspx.cs using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; namespace EvaluacionTecnica.Pantallas { public partial class Inventario : System.Web.UI.Page { SqlConnection conexion = new SqlConnection("Data source=DESKTOP-LRRUQCG; Initial Catalog=Empresa; User=sae; Password=sae"); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { AgregarGrid(); DrSucursalMe(); } } protected void AgregarGrid() { List<string> Lista = new List<string>(); string Codigo="", Nombre="", Cantidad="", Sucursal="",con1 =""; string Precio_unitario = ""; DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[5] {new DataColumn("Codigo de barras",typeof(string)), new DataColumn("Nombre",typeof(string)), new DataColumn("Cantidad",typeof(string)), new DataColumn("Precio unitario",typeof(string)), new DataColumn("Sucursal",typeof(string))}); conexion.Open(); string query = "select * from v_productos where ID_Sucursal = "+Session["ID_s"]; SqlCommand productos = new SqlCommand(query,conexion); SqlDataReader registros = productos.ExecuteReader(); while (registros.Read()) { con1 = registros[0].ToString(); Lista.Add(con1); for (int i = 0; i < Lista.Count; i++) { Codigo = Convert.ToString(registros["Codigo_deBarras"]); Nombre = Convert.ToString(registros["Nombre"]); Cantidad = Convert.ToString(registros["Cantidad"]); Precio_unitario = Convert.ToString(registros["Precio_unitario"]); Sucursal = Convert.ToString(registros["Nombre_suc"]); } dt.Rows.Add(Codigo,Nombre,Cantidad,"$"+decimal.Parse(Precio_unitario).ToString("N"),Sucursal); grProductos.DataSource = dt; grProductos.DataBind(); } conexion.Close(); } protected void grProductos_SelectedIndexChanged(object sender, EventArgs e) { lblNombre.Visible = true; txtNombre.Visible = true; txtNombre.Enabled = false; lblCantidad.Visible = true; txtCantidad.Visible = true; lblCodigo.Visible = true; txtCodigo.Visible = true; txtCodigo.Enabled = false; lblPrecio.Visible = true; txtPrecio.Visible = true; txtPrecio.Enabled = false; lblSucursal.Visible = true; DrSucursal.Visible = true; DrSucursal.Enabled = false; btnActualizar.Visible = true; btnAgregar.Visible = false; string nombre = "", Codigo = "", Cantidad = "", Precio = ""; int Sucursal = 0; GridViewRow row = grProductos.SelectedRow; int id = Convert.ToInt32(grProductos.DataKeys[row.RowIndex].Value); conexion.Open(); string query = "select * from productos where Codigo_deBarras = '"+id+"'"; SqlCommand productos = new SqlCommand(query,conexion); SqlDataReader registros = productos.ExecuteReader(); if (registros.Read()) { nombre = Convert.ToString(registros["Nombre"]); Codigo = Convert.ToString(registros["Codigo_deBarras"]); Cantidad = Convert.ToString(registros["Cantidad"]); Precio = Convert.ToString(registros["Precio_unitario"]); Sucursal = Convert.ToInt32(registros["Sucursal"]); } conexion.Close(); txtNombre.Text = nombre; txtCodigo.Text = Codigo; txtCantidad.Text = Cantidad; txtPrecio.Text = "$" + decimal.Parse(Precio).ToString("N"); DrSucursal.SelectedIndex = Sucursal; } private void DrSucursalMe() { DrSucursal.DataSource = Consultar("select * from sucursales"); DrSucursal.DataTextField = "Nombre_suc"; DrSucursal.DataValueField = "ID_Sucursal"; DrSucursal.DataBind(); DrSucursal.Items.Insert(0, new ListItem("Seleccionar..", "0")); } public DataSet Consultar(string strSQL) { string conexion = "Data source=DESKTOP-LRRUQCG; Initial Catalog=Empresa; User=sae; Password=sae"; SqlConnection con = new SqlConnection(conexion); con.Open(); SqlCommand cmd = new SqlCommand(strSQL, con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); con.Close(); return ds; } protected void btnActualizar_Click(object sender, EventArgs e) { string script = "alert('Producto Actualizado')"; string cantidad = txtCantidad.Text; string codigo = txtCodigo.Text; conexion.Open(); string query = "update productos set Cantidad = "+cantidad+" where Codigo_deBarras='"+codigo+"' and Sucursal = "+ Session["ID_s"]; SqlCommand productos = new SqlCommand(query, conexion); productos.ExecuteNonQuery(); ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", script, true); conexion.Close(); AgregarGrid(); } protected void btnInsertar_Click(object sender, EventArgs e) { lblNombre.Visible = true; txtNombre.Visible = true; txtNombre.Enabled = true; txtNombre.Text = ""; lblCantidad.Visible = true; txtCantidad.Visible = true; txtCantidad.Text = ""; lblCodigo.Visible = true; txtCodigo.Visible = true; txtCodigo.Enabled = true; txtCodigo.Text = ""; lblPrecio.Visible = true; txtPrecio.Visible = true; txtPrecio.Enabled = true; txtPrecio.Text = ""; lblSucursal.Visible = true; DrSucursal.Visible = true; DrSucursal.Enabled = true; DrSucursal.SelectedIndex = 0; btnAgregar.Visible = true; btnActualizar.Visible = false; } protected void btnAgregar_Click(object sender, EventArgs e) { string script = "alert('Producto Agregado')"; string nombre = Convert.ToString(txtNombre.Text); string codigo = Convert.ToString(txtCodigo.Text); string cantidad = Convert.ToString(txtCantidad.Text); string Precio = Convert.ToString(txtPrecio.Text); int sucursal = Convert.ToInt32(DrSucursal.SelectedValue); conexion.Open(); string query = "insert into productos (Nombre,Codigo_deBarras,Cantidad,Precio_unitario,Sucursal) " + "values ('" + nombre + "','" + codigo + "'," + cantidad + "," + Precio + "," + sucursal + ")"; SqlCommand insertar = new SqlCommand(query, conexion); insertar.ExecuteNonQuery(); ScriptManager.RegisterStartupScript(this, typeof(Page), "alerta", script, true); conexion.Close(); txtNombre.Text = ""; txtCantidad.Text = ""; txtCodigo.Text = ""; txtPrecio.Text = ""; DrSucursal.SelectedIndex = 0; } protected void btnCerrarSesion_Click(object sender, EventArgs e) { FormsAuthentication.SignOut(); Session.Clear(); Session.Abandon(); Response.Redirect("~/Pantallas/Login.aspx"); } } }
ca123c2e7b54c1dbc813f632d13b448b5bde8890
[ "C#" ]
2
C#
Alexis0308/Brive
fdbef6a611d7358ba5dd6f1751dd45e8ca31c58c
10fbe308f541ec37fd2e736b89989c0c6f807f46
refs/heads/master
<repo_name>iSnakeBuzz/labymod-server-api<file_sep>/common/src/main/java/net/labymod/serverapi/LabyEmotes.java package net.labymod.serverapi; import java.util.Arrays; import java.util.Random; public enum LabyEmotes { STOP_EMOTE(-1), BACKFLIP(2), DAB(3), HELLO(4), BOW_THANKS(5), HYPE(6), TRYINGTOFLY(7), INFINITY_SIT(8), ZOMBIE(11), HULA_HOOP(13), CALLING(14), FACEPALM(15), BRUSH_YOUR_SHOULDERS(18), SPLIT(19), SALUTE(20), BALARINA(22), HANDSTAND(31), HELICOPTER(32), HOLY(33), WAVEOVER(34), DEEPER_DEEPER(36), KARATE(37), MOON_WALK(38), FREEZING(40), JUBILATION(41), TURTLE(43), HEADSPIN(45), INFINITY_DAB(46), CHICKEN(47), THE_FLOSS(49), THE_MEGA_THRUST(50), THE_CLEANER(51), BRIDGE(52), MILK_THE_COW(53), RURIK(54), WAVE(55), MONEY_RAIN(57), THE_POINTER(59), FRIGHTENING(60), SAD(61), AIR_GUITAR(62), WITCH(63), LEFT(69), RIGHT(70), BUUUH(74), SPITTING_BARS(75), COUNT_MONEY(76), HUG(77), APPLAUSE(78), BOXING(79), SHOOT(83), THE_POINTING_MAN(84), HEART(85), NEAR_THE_FALL(86), WAITING(89), PRAISE_YOUR_ITEM(92), LOOK(93), I_LOVE_YOU(97), SARCASTIC_CLAP(98), YOU(101), HEAD_ON_WALL(105), BALANCE(112), LEVEL_UP(113), TAKE_THE_L(114), MY_IDOL(121), AIRPLANE(122), EAGLE(124), JOB_WELL_DONE(126), ELEPHANT(128), PRESENT(130), EYES_ON_YOU(131), BOW_DOWN(133), MANEKI_NEKO(134), CONDUCTOR(135), DIDI_CHALLENGE(136), SNOW_ANGLE(137), SNOWBALL(138), SPRINKLER(139), CALCULATED(140), ONE_ARMED_HANDSTAND(141), EAT(142), SHY(143), SIT_UPS(145), BREAKDANCE(146), MINDBLOW(148), FALL(149), T_POSE(150), JUMPING_JACK(153), BACKSTOKE(154), ICE_HOCKEY(156), LOOK_AT_FIREWORKS(157), FINISH_THE_TREE(158), ICE_SKATING(159), FANCY_FEET(161), RONALDO(162), TRUE_HEART(163), PUMPERNICKEL(164), BABY_SHARK(166), OPEN_PRESENT(167), DJ(170), Sneeze(173); int emoteID; LabyEmotes(int id) { this.emoteID = id; } public int getEmoteID() { return emoteID; } public static LabyEmotes findById(int id) { return Arrays.stream(LabyEmotes.values()).filter(labyEmotes -> labyEmotes.getEmoteID() == id).findAny().orElse(null); } public LabyEmotes randomEmote() { return Arrays.asList(LabyEmotes.values()).get(new Random().nextInt(LabyEmotes.values().length)); } }
a947baeb40a527c4be5ea63ece93bbfa5280717b
[ "Java" ]
1
Java
iSnakeBuzz/labymod-server-api
e712b6e31aa0397684b2aef4d2c6dacc3786acb9
4bfb2571aab9aff628fdb136e424cf2d7671acbd
refs/heads/master
<repo_name>wangyahong423/carousel<file_sep>/index.js (function(){ var htmlContent = '<div class="slider" id="slider">' + '<div class="slide"><img src="img/b5.png" alt=""></div>' + '<div class="slide"><img src="img/b1.png" alt=""></div>' + '<div class="slide"><img src="img/b2.png" alt=""></div>' + '<div class="slide"><img src="img/b3.png" alt=""></div>' + '<div class="slide"><img src="img/b4.png" alt=""></div>' + '<div class="slide"><img src="img/b5.png" alt=""></div>' + '<div class="slide"><img src="img/b1.png" alt=""></div>' + '</div>' + '<span id="left"><</span>' + '<span id="right">></span>' + '<ul class="nav" id="navs">' + '<li>1</li>' + '<li>2</li>' + '<li>3</li>' + '<li>4</li>' + '<li>5</li>' + '</ul>'; var $box = $('#box') $box.append(htmlContent);//添加到html页面 // 获取图片 var images = document.getElementsByClassName('slide'), imagesNum = images.length-2; // 获取按钮 var navs = document.getElementById('navs').children; navsActive(0);//初始第一个圆点按钮css设置为active // 获取当前正在轮播的图片的索引值 var index = 0; // 设置一个轮播的定时器 var timerCarousel = setInterval(nextPage,3000); // 鼠标移入显示左右按钮并停止轮播事件:通过改变按钮的opacity值显示按钮,清楚定时器停止轮播 $box.mouseover(function(){ $('#left').css('opacity',0.6); $('#right').css('opacity',0.6); clearInterval(timerCarousel); }) // 鼠标移出不显示左右按钮且轮播 $box.mouseout(function(){ $('#left').css('opacity',0); $('#right').css('opacity',0); timerCarousel = setInterval(nextPage,3000); }) // 左右按钮点击切换图片 $('#left').click(lastPage); $('#right').click(nextPage); // 上一页:function lastPage(){}:如果当前页面是第一张图片,那点击左按钮时应切换到第五张图片,所以图片box的left值向左移动1200*imagesNum // 如果不是第一张图片,则直接将box的left值减少1200 function lastPage(){ if(index == 0){ $('#slider').animate({left:'+=' + 1200},1000,function(){ $('#slider').css('left',-1200*imagesNum); }) navsActive(imagesNum-1);//此时显示的是第五张图片,他的索引值是imagesNum-1=4 index = imagesNum - 1; } else{ $('#slider').animate({left:'+=' + 1200},1000); navsActive(index - 1); index--; } } // 下一页:function nextPage(){}:如果当前图片是第五章图片(索引值为4),则点击右按钮时应切换到第一张图片,即box的left减少1200即可 function nextPage(){ if(index == imagesNum-1){ $('#slider').animate({left:'-=' + 1200},1000,function(){ $('#slider').css('left',-1200); }) navsActive(0);//此时显示的是第五张图片,他的索引值是imagesNum-1=4 index = 0; } else{ $('#slider').animate({left:'-=' + 1200},1000); navsActive(index + 1); index++; } } // 圆点按钮的切换事件 function navsActive(idx){ for(var i = 0; i < navs.length; i++){ navs[i].removeAttribute("class","active"); } navs[idx].setAttribute("class","active"); } // 圆点按钮的点击事件 for(var i=0;i<imagesNum;i++){ (function (j) { navs[j].onclick = function(){ if(j-index > 0){ $('#slider').animate({left:'-=' + 1200*(j-index)},1000); } else if(j-index < 0){ $('#slider').animate({left:'+=' + 1200*(index-j)},1000); } else{ return true; } navsActive(j); index=j; } })(i) } })();
a722adde47900fe310abe320909e135402034688
[ "JavaScript" ]
1
JavaScript
wangyahong423/carousel
bb0dfbb5c1ebd8540b0cde3691be7633eac4c681
bd1f5d0dea6551679c803841a45183ff59781a20
refs/heads/main
<file_sep>#include <stdio.h> #define N 4 #define M 5 int main() { int i = 0, j = 0; int A[N][M] = { {3,-16,2,12,-5}, {0,8,-9,2,2}, {28 - 18,1,1,1}, {0,17,0,14,0 }, }; int k = 0; for (j = 0; j < M; j++) { for (i = 0; i < N; i++) { if (A[i][j] == 0) { k++; break; } } } printf("Kolichestvo stolbtsov s 0=%d\n", k); int r = 0, index; i = 0, j = 0; for (i = 0; i < N; i++) { for ( j = 0; j < M; j++) { int counter = 0, z = 0; for ( z = 0; z < N; z++) if (A[i][j] == A[i][z]) counter++; if (counter > r) { r = counter; index = i; } } } printf("Index stroki s naibolishim chislom povtoreaiushikhsea elementov=%d", index); return 0; }
e197f96a79e5c91d0dd45c47403a4990fc84e639
[ "C" ]
1
C
tischina/martaa
32031f04471c6889783770f836ba9c996b4eca30
836120c84ea45df469f5c887042b9fb1fdaf636c
refs/heads/master
<file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }]) # Mayor.create(:name => 'Daley', :city => cities.first) dan = Member.create(:name => '<NAME>', :bio => "Carles etsy raw denim 3 wolf moon viral iphone. Raw denim stumptown iphone helvetica beard keffiyeh organic art party bicycle rights, chambray letterpress terry richardson ethical biodiesel. Scenester 3 wolf moon art party blog raw denim etsy PBR echo park, williamsburg food truck whatever. Synth Austin mlkshk mustache whatever organic carles", :twitter => "DanGodfrey", :github => "DanGodfrey", :weapon => "Blue Shells", :specialty => "being a dick", :catch_phrase => "weeeeeeee", :profile_pic_url => "/images/useravatar.png") stat1 = Stat.create(:name => "awesomeness", :number => 10, :member_id => dan) stat2 = Stat.create(:name => "SQL Hackery", :number => 8, :member_id => dan) stat2 = Stat.create(:name => "Javascript Wizardry", :number => 9, :member_id => dan) stat1 = Stat.create(:name => "averageness", :number => 5, :member_id => dan) stat1 = Stat.create(:name => "photography", :number => 2, :member_id => dan) carson = Member.create(:name => '<NAME>', :bio => "Carles etsy raw denim 3 wolf moon viral iphone. Raw denim stumptown iphone helvetica beard keffiyeh organic art party bicycle rights, chambray letterpress terry richardson ethical biodiesel. Scenester 3 wolf moon art party blog raw denim etsy PBR echo park, williamsburg food truck whatever. Synth Austin mlkshk mustache whatever organic carles", :twitter => "DanGodfrey", :github => "DanGodfrey", :weapon => "Blue Shells", :specialty => "being a dick", :catch_phrase => "weeeeeeee", :profile_pic_url => "/images/useravatar.png")
3954824056977c37d686dde65308709c21dc1e12
[ "Ruby" ]
1
Ruby
DanGodfrey/Citation-Needed
382bbe8202394c3d30a74f43159428ed902ce1b2
b3dce8b2c66c7805a1afbb1973ae3435ea3c152b
refs/heads/master
<repo_name>Patrick-Doucet/connect-4-online<file_sep>/README.md # Connect 4 Online Connect 4 server and client that enables anyone to host a server and connect to it using the client. All new users enter the client with a new name and enter a lobby where they can challenge any other user to a game. <file_sep>/Client-Side/Connect-4-Client/Connect-4-Client/AcceptForm.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Connect_4_Client { public partial class AcceptForm : Form { Socket clientServerSocket; // Reference to server socket string[] uInfo; // user information public bool wantsToPlay = false; // boolean representing if you clicked accept:true or reject:false /// <summary> /// Constructor of accept form, shows who wants to play vs you and the options accept/reject /// </summary> /// <param name="s">Reference to server socket</param> /// <param name="userInfo">Information of the user that wants to play vs you</param> public AcceptForm(Socket s, string userInfo) { // Initial config InitializeComponent(); CenterToScreen(); // Save class reference to server socket clientServerSocket = s; // split user info into uInfo[0] = name and uInfo[1] = IP uInfo = userInfo.Split(':'); // Put the name of the user to display label1.Text = label1.Text.Insert(0, uInfo[0]); } /// <summary> /// Accept button click event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { // Send an accept message to server socket string sendString = "##accept##"; byte[] bytesToSend = Encoding.ASCII.GetBytes(sendString); clientServerSocket.Send(bytesToSend); // Affect wantsToPlay = true so the parent window can know what button was pressed wantsToPlay = true; // Close this window this.Close(); } /// <summary> /// Reject button click event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { // Send an reject message to server socket string sendString = "##reject##"; byte[] bytesToSend = Encoding.ASCII.GetBytes(sendString); clientServerSocket.Send(bytesToSend); // Close this window this.Close(); } } } <file_sep>/Client-Side/Connect-4-Client/Connect-4-Client/WinForm.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Connect_4_Client { public partial class WinForm : Form { private GameForm game; // Reference to the gameform parent window private bool win; // Contains if we won or not private int playerWinCount; // Contains how many times you have won private int opponentWinCount; // Contains how many times the opponent has won /// <summary> /// Constructor for the WinForm /// </summary> /// <param name="gameForm">Reference to the parent GameForm</param> public WinForm(GameForm gameForm) { // Initial configs InitializeComponent(); CenterToScreen(); // Keep class references to the values from the parent form (gameForm) game = gameForm; win = game.turn; // Who won playerWinCount = game.playerWins; // how many times you won opponentWinCount = game.opponentWins; // how many times opponent has won updateLabels(); // update all the text labels } /// <summary> /// Update all the labels shown on the window /// </summary> private void updateLabels() { // Show "You Won!" if you won, and "You Lost!" if you did not win if (win) { label1.Text = "You Won!"; } else { label1.Text = "You Lost!"; } // Update playerWin - opponentWin labels with current scores label5.Text = opponentWinCount.ToString(); label3.Text = playerWinCount.ToString(); } /// <summary> /// Play Again button click event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { // Send message to other user that he wishes to play again string playAgain = "##play##"; // call isReset method from parent GameForm game.isReset(playAgain); // close the current form this.Close(); } /// <summary> /// Leave button event click event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { // Send message to other user that he doesn't wish to play again string stopPlaying = "##stop##"; // call isReset method from parent GameForm game.isReset(stopPlaying); // close the current form this.Close(); } } } <file_sep>/Client-Side/Connect-4-Client/Connect-4-Client/MainForm.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; using System.Net; namespace Connect_4_Client { public partial class MainForm : Form { // Try connecting to server before even opening a form // First create a socket (so we can keep a reference throughout the program) // Create a TCP/IP socket. // Since the server uses AF_INET (IPV4 address), AddressFamily.InterNetwork is used to force IPV4 on client side Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Thread for client to listen to server socket on Thread myThread; // Possible opponent information public static string opponentIp; // ip public static string oName; // name // Your name public static string pName; // player name public string usernameText // getter setter for the username text found inside label3 (the label beside the words "welcome:") { get { return label3.Text; } set { label3.Text = value; } } /// <summary> /// Constructor for the main window of the application /// </summary> public MainForm() { // Initial configurations for the window InitializeComponent(); // Center the window to the middle of your screen CenterToScreen(); // event notification when closing the window this.FormClosing += MainForm_FormClosing; try { // Start Socket connection towards server StartClientSocket(socketClient); // Create the form asking the user his name WelcomeForm welcomeForm = new WelcomeForm(); welcomeForm.ShowDialog(this); // giving "this" here means we pass a reference of the parent window to the new child window // Fetch the player name from the welcomeForm text box and insert it in the label of the main window // Also save it in pName for later use this.label3.Text = welcomeForm.nameText; pName = welcomeForm.nameText; try { // Send your name to the server sendNameToServer(); // Fetch all the other users that are connected fetchClientListFromServer(); } catch { // Throw if it fails throw new Exception(); } // Since the socket needs to be always listening for information from the server // Launch listen function on thread // Here the thread calls AlwaysListening with the socket to listen on myThread = new Thread(new ThreadStart(() => ThreadMethods.AlwaysListening(socketClient, listBox1) /*Call method*/)); myThread.IsBackground = true; // With this flag Application.Exit() will kill the thread myThread.Start(); // Start the thread } catch { // The connection was not able to be made. MessageBox.Show("Can't connect to server."); throw new Exception(); } } /// <summary> /// Check the status of the connection of a given socket to see if you are still connected to the server /// </summary> /// <param name="s">Socket to check if connected</param> /// <returns>If is connected</returns> public static bool IsSocketConnected(Socket s) { // Check the status of the connection to see if you are still connected // Directly check if it is connected (TCP only) if (!s.Connected) return false; else return true; } /// <summary> /// Creating the client socket and connecting to server /// </summary> /// <param name="s">Socket to start connection</param> public static void StartClientSocket(Socket s) { // Data buffer for incoming data. byte[] bytes = new byte[1024]; // Connect to a remote device. try { // Establish the remote endpoint for the socket. // connects to ip given from DNS "nicepepito.crabdance.com" // uses port 10123 IPHostEntry ipHostInfo = Dns.GetHostEntry("nicepepito.crabdance.com"); IPAddress ipAddress = ipHostInfo.AddressList[0]; // Get first ip from list int port = 10123; // port number IPEndPoint remoteEP = new IPEndPoint(ipAddress, port); // create endpoint // Connect the socket to the remote endpoint. Catch any errors. try { s.Connect(remoteEP); // connect socket s to remoteEP MessageBox.Show("Socket connected"); } catch (ArgumentNullException ane) { Console.WriteLine("ArgumentNullException : {0}", ane.ToString()); } catch (SocketException se) { Console.WriteLine("SocketException : {0}", se.ToString()); } catch (Exception e) { Console.WriteLine("Unexpected exception : {0}", e.ToString()); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } /// <summary> /// Closes the socket if it is still connected /// </summary> /// <param name="s">Socket to close</param> public static void CloseClientSocket(Socket s) { // Check if the socket is still connected to the server if (IsSocketConnected(s)) { // Send message to server saying that the socket is closing // Encode the data string into a byte array. byte[] msg = Encoding.ASCII.GetBytes("##bye##"); // Send the data through the socket. try { s.Send(msg); } catch { } } // Closing socket towards the server // Release the socket. s.Shutdown(SocketShutdown.Both); // disable read and write s.Close(); // close socket } /// <summary> /// When double clicking a user, ask that user to play a game /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void listBox1_MouseDoubleClick(object sender, MouseEventArgs e) { // Check if table index exists in table int index = this.listBox1.IndexFromPoint(e.Location); if (index != ListBox.NoMatches) { // Get the person info string personInfo = listBox1.GetItemText(listBox1.SelectedItem); // Split the personInfo into Username (words[0]) and IP (words[1]) string[] words = personInfo.Split(':'); oName = words[0]; opponentIp = words[1]; // Send to server socket the username of the potential opponent byte[] nameInBytes = System.Text.Encoding.ASCII.GetBytes(words[0]); socketClient.Send(nameInBytes); } } /// <summary> /// Close the application if X is clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainForm_FormClosing(object sender, EventArgs e) { Application.Exit(); // Close application and threads CloseClientSocket(socketClient); // Close socket towards the server } /// <summary> /// Repopulates the list of users in the table /// </summary> /// <param name="entries">All users to be added to list</param> private void updateList(string[] entries) { // First clear the listBox before adding all the clients if (listBox1.Items.Count != 0) { listBox1.Items.Clear(); } // Add every entry found inside the listBox for (int i = 0; i < entries.Length; i++) { listBox1.Items.Add(entries[i]); } } /// <summary> /// Send your username to the server through the clientServerSocket /// </summary> private void sendNameToServer() { // Send to server socket the client username byte[] nameInBytes = System.Text.Encoding.ASCII.GetBytes(usernameText); socketClient.Send(nameInBytes); } /// <summary> /// Receive the client list from the server through the clientServerSocket /// </summary> private void fetchClientListFromServer() { // Initializing byte array for retrieval of data from server byte[] bytes = new byte[1024]; int bytesRec; // Receive data telling the client how many users to expect bytesRec = socketClient.Receive(bytes); string lobbyInfo = Encoding.ASCII.GetString(bytes, 0, bytesRec); // convert to string // Clear byte array for next message Array.Clear(bytes, 0, bytes.Length); // Add every client received inside a list of strings string[] entries = lobbyInfo.Split('!'); // split string into array of users entries = entries.Skip(1).ToArray(); // Remove first element since it only shows how many clients are connected // Update the listBox updateList(entries); } /// <summary> /// Create the game instance /// </summary> public static void createGame() { // start the gameForm and start first GameForm gameForm = new GameForm(true, pName, oName); // no need for the ip, this user will wait for the other one gameForm.ShowDialog(); } /// <summary> /// Join the game instance /// </summary> public static void joinGame() { // start the gameForm and start second GameForm gameForm = new GameForm(false, pName, oName, opponentIp); // need the opponentIp to connect to his listener gameForm.ShowDialog(); } // Class containing all the methods for the socket thread public class ThreadMethods { /// <summary> /// Always listen for messages coming from the server /// </summary> /// <param name="clientServerSocket">socket to listen on</param> /// <param name="lobbyBox">reference to the box where the user entries are</param> public static void AlwaysListening(Socket clientServerSocket, ListBox lobbyBox) { // Initializing byte array for retrieval of data from server byte[] bytes = new byte[1024]; int bytesRec = 0; while (true) { try { // Receive bytes from server bytesRec = clientServerSocket.Receive(bytes); } catch { } // Convert bytes to string string recvString = Encoding.ASCII.GetString(bytes, 0, bytesRec); // Possible pre-defined responses string accept = "##accept##\0"; string reject = "##reject##\0"; string disconnect = "##disconnect##\0"; // If client list is received // Add every client received inside a list of strings string[] entries = recvString.Split('!'); // Clear byte array for next message Array.Clear(bytes, 0, bytes.Length); // Either receive an accept or reject from the opponent // Or, the socket receive a number -> this means the client update the table because a new user connected // Or, a username is sent -> this means someone wants to play vs the client // Or, the server has disconnected and sends disconnect to client // Case accept if (recvString == accept) { // Stop listening to the server CloseClientSocket(clientServerSocket); joinGame(); Application.Exit(); } // Case reject else if (recvString == reject) { // Do nothing } // Case disconnect else if (recvString == disconnect) { // Close client because the server is no longer running // Show prompt first to why you are closing MessageBox.Show("The server was closed. You have been disconnected..."); CloseClientSocket(clientServerSocket); Application.Exit(); } // Case client list sent else if (entries.Length > 1) { entries = entries.Skip(1).ToArray(); // Remove first element since it only shows how many clients are connected // Update the listBox updateLobby(entries, lobbyBox); } // Special case, sending user list, but there are no users connected except yourself else if(recvString == "0\0") { // Clear the listBox if (lobbyBox.Items.Count != 0) { lobbyBox.Items.Clear(); } } // Case where user wants to play vs you else { // Add all users from the lobby to list List<string> allEntries = new List<string>(); foreach (string s in lobbyBox.Items) { allEntries.Add(s); } // Check if the username you received is a valid user (Look through list of users) if(allEntries.Any(recvString.Contains)) { // User was found, save his name string[] opInfo = recvString.Split(':'); oName = opInfo[0]; // Open new window asking you if you'd like to play vs this user AcceptForm acceptForm = new AcceptForm(clientServerSocket, recvString); // pass reference to socket and username acceptForm.ShowDialog(); // If the user had clicked "accept" close the socket to the server and start the game if(acceptForm.wantsToPlay) { Thread.Sleep(100); // To avoid sending too many strings in the buffer before the server can read them // Stop listening to the server CloseClientSocket(clientServerSocket); // Start the game createGame(); // When the game is completed, close the application Application.Exit(); } } } } } /// <summary> /// Repopulates the list of users in the table (Thread version of function) /// This exists twice because the thread class isn't in the scope to use the other updateList function /// </summary> public static void updateLobby(string[] entries, ListBox lobbyBox) { // First clear the listBox before adding all the clients if (lobbyBox.Items.Count != 0) { lobbyBox.Items.Clear(); } // Add every entry found inside the listBox for (int i = 0; i < entries.Length; i++) { lobbyBox.Items.Add(entries[i]); } } } } } <file_sep>/Client-Side/Connect-4-Client/Connect-4-Client/GameForm.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Connect_4_Client { public partial class GameForm : Form { private Rectangle[] gameBoardColumns; // Columns of the gameboard private int rows = 6; // Number of rows for the gameboard private int columns = 7; // Number of columns for the gameboard private int[,] boardState; // Initialized at 0 (State.Blank) private enum State { Blank, Red, Black }; // The possible states a square can be (Blank = 0, Red = 1, Black = 2) public bool turn; // Is it your turn? private bool isStarting; // If you have first turn private State color; // What color you are playing (Red|Black) public string pName; // Your username public string oName; // The opponents username public int playerWins = 0; // How many times you have won public int opponentWins = 0; // How many times the opponent has won TcpClient client; // The Tcp socket from client to client int port = 11123; // The port to connet to string ipToConnect; // The ip to connect to if you were the one who joined the game public bool isClosed = false; // Was the game closed? NetworkStream nwStream; // The network stream to read/write the data to /// <summary> /// Constructor for the GameForm /// </summary> /// <param name="starting">If you have the first move</param> /// <param name="playerName">Your name</param> /// <param name="opponentName">Opponent name</param> /// <param name="ip">If you are joining the game, you will have the ip of the socket to connect to</param> public GameForm(bool starting, string playerName, string opponentName, string ip = null) { // Initial configs InitializeComponent(); CenterToScreen(); // Class references to passed in parameters isStarting = starting; ipToConnect = ip; pName = playerName; oName = opponentName; updateLabelText(); // update all text labels // Initialize gameboard state logic gameBoardColumns = new Rectangle[7]; boardState = new int[rows, columns]; // initialized at 0 // if you are starting, you have to create the listener to let your opponent connect to you if (isStarting) { // listener for the opponent TcpListener listener; listener = new TcpListener(IPAddress.Any, port); // listen for any type of ip on the given port (11123) listener.Start(); // start listener try { // accept client and keep socket reference client = listener.AcceptTcpClient(); } catch { // if an issue occur, put socket to null and output message client = null; MessageBox.Show("Something went wrong"); } turn = true; // You are starting, so it is your turn color = State.Red; // You play as red as default } else if (ipToConnect != null) { // Establish the remote endpoint for the socket. // connects to ipToConnect // uses port 11123 client = new TcpClient(); try { client.Connect(ipToConnect, port); // connect to listener } catch (Exception ex) { MessageBox.Show("Something went wrong"); } turn = false; // You start second color = State.Black; // You play as black } nwStream = client.GetStream(); // Create stream binded to the client socket nwStream.ReadTimeout = 100; // Read for data every 100 milliseconds // If it isn't your turn, listen at the beginning if(!turn) { // If the game was closed, don't try to read if (!isClosed) { //---get the incoming data through a network stream--- byte[] buffer = new byte[client.ReceiveBufferSize]; int bytesRead = 0; // try to read data every 100 milliseconds, leave once you receive something while (bytesRead == 0) { try { //---read incoming stream--- bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize); } catch { //MessageBox.Show("Waiting for player move"); } } //---convert the data received into a int--- string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead); // Convert to string int column = -1; int.TryParse(dataReceived, out column); // parse string and convert to int // update board drawMove(column); } } } /// <summary> /// Update all window labels /// </summary> private void updateLabelText() { // Labels change based on if you are red or black if(isStarting) { // Show correct player names label1.Text = "Red: " + pName + " - " + playerWins; label2.Text = "Black: " + oName + " - " + opponentWins; } else { // Show correct player names label1.Text = "Red: " + oName + " - " + opponentWins; label2.Text = "Black: " + pName + " - " + playerWins; } } /// <summary> /// Draw the graphics on the window (gets called after form constructor) /// </summary> /// <param name="e"></param> protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); // override base function // Create blue background e.Graphics.FillRectangle(Brushes.CornflowerBlue, 50, 20, 700, 500); // For each column/row, draw circles to represent each possible playable square of the grid for (int i = 0; i < columns; i++) { for (int j = 0; j < rows; j++) { // 0 means we need to draw White -> State.Blank = 0 if(boardState[j, i] == 0) { // Draw the white circles on the gameBoard e.Graphics.FillEllipse(Brushes.White, 70 + 100 * i, 40 + 80 * j, 60, 60); } // 1 means we need to draw Red -> State.Red = 1 else if(boardState[j, i] == 1) { // Draw the red circles on the gameBoard e.Graphics.FillEllipse(Brushes.Red, 70 + 100 * i, 40 + 80 * j, 60, 60); } // 2 means we need to draw Black -> State.Black = 2 else if (boardState[j, i] == 2) { // Draw the black circles on the gameBoard e.Graphics.FillEllipse(Brushes.Black, 70 + 100 * i, 40 + 80 * j, 60, 60); } // Set the bounds of each column gameBoardColumns[i] = new Rectangle(70 + 100 * i, 20, 70, 500); // This sets the clickable bound of the columns (so we know which column was clicked) } } } /// <summary> /// Detected where in the column the move should be drawn, and draw it /// </summary> /// <param name="clickedColumn">The column to draw the move</param> public void drawMove(int clickedColumn) { // Draw chip on click column if it is not full for (int i = rows - 1; i >= 0; i--) { // First detected blank state in board if (boardState[i, clickedColumn] == 0) { // Get the State to draw State drawingColor = getTurnState(); // Change state of board boardState[i, clickedColumn] = (int)drawingColor; // Draw colored chip inside of it Graphics g = CreateGraphics(); Brush currentColor = getTurnColor(drawingColor); // If an invalid turn if (currentColor == null) throw new Exception("Expected a State.Red or State.Black turn"); // If the turn is valid, draw the associated colored chip g.FillEllipse(currentColor, 70 + 100 * clickedColumn, 40 + 80 * i, 60, 60); // Check if it was a winning move if (isWin(i, clickedColumn)) { // Increment the score of whoever won the game if (turn) playerWins++; else opponentWins++; // Open the win form openWinForm(); return; } turn = !turn; // Flip who's turn it is break; } } } /// <summary> /// GameForm mouse click event (if you clicked the board) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void GameForm_MouseClick(object sender, MouseEventArgs e) { // Check if it's your turn, if so, send your move if (turn) { // Check which column we have click (if we did click one) int clickedColumn = findClickedColumnIndex(e.Location); // Invalid move if (clickedColumn == -1) return; // Send your move to the other player //---get the incoming data through a network stream--- byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(clickedColumn.ToString()); // write to networkstream nwStream.Write(bytesToSend, 0, bytesToSend.Length); // draw the move on your end drawMove(clickedColumn); } // If the game was closed, don't try to read if (!isClosed) { //---get the incoming data through a network stream--- byte[] buffer = new byte[client.ReceiveBufferSize]; int bytesRead = 0; // Wait for the other player's move while (bytesRead == 0) { try { //---read incoming stream--- bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize); } catch { //MessageBox.Show("Waiting for player move"); } } //---convert the data received into a int--- string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead); // Convert to string int column = -1; int.TryParse(dataReceived, out column); // parse string and convert to int // Update move drawMove(column); } } /// <summary> /// Check if we need to reset the board or close the game /// </summary> /// <param name="answer">The answer to if the player wants to play again</param> public void isReset(string answer) { // send response to the other player byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(answer); nwStream.Write(bytesToSend, 0, bytesToSend.Length); //---get the incoming data through a network stream--- byte[] buffer = new byte[client.ReceiveBufferSize]; int bytesRead = 0; // Wait for the other player's answer while (bytesRead == 0) { try { //---read incoming stream--- bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize); } catch { //MessageBox.Show("Waiting for player move"); } } //---convert the data received into a int--- string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead); // 4 possible cases // - play/play -> reset board and play again // - play/leave -> leave game // - leave/play -> leave game // - leave/leave -> leave game if (answer == "##play##") { if(dataReceived == "##play##") { // reset board resetGameBoard(); } else { isClosed = true; // set that we closed the game // received leave, close the game closeGame(); } } else if (answer == "##stop##") { isClosed = true; // set that we closed the game // close the game closeGame(); } } /// <summary> /// Reset the drawn game board and the game board state, also flip the turn/color of the player /// </summary> public void resetGameBoard() { // reinitialize to 0 Array.Clear(boardState, 0, boardState.Length); isStarting = !isStarting; // flip turn turn = isStarting; //Change sides if (color == State.Red) color = State.Black; else if (color == State.Black) color = State.Red; // Update all text label updateLabelText(); this.Refresh(); // This forces a call to OnPaint which means we repaint the board } /// <summary> /// Close the stream, the socket and the GameForm /// </summary> private void closeGame() { // Close the network stream nwStream.Close(); // Close the tcpclient client.Close(); // Close the window this.Close(); } /// <summary> /// Check what your color is to set the brush color /// </summary> /// <returns>Brush color</returns> private Brush getTurnColor(State drawingColor) { if (drawingColor == State.Red) return Brushes.Red; else if (drawingColor == State.Black) return Brushes.Black; return null; } /// <summary> /// Check if it is your turn and what color you have to return the correct state logic /// </summary> /// <returns></returns> private State getTurnState() { if (turn && color == State.Red) return State.Red; else if (turn && color == State.Black) return State.Black; else if (!turn && color == State.Red) return State.Black; else if (!turn && color == State.Black) return State.Red; else return State.Blank; } /// <summary> /// Find which column was clicked on the game board /// </summary> /// <param name="location"></param> /// <returns>Clicked Column index</returns> private int findClickedColumnIndex(Point location) { // Go through all the gameBoardColumn rectangles that were set, and check if you clicked inside their pixel ranges for(int i = 0; i < columns; i++) { if (location.X >= gameBoardColumns[i].X && Location.Y >= gameBoardColumns[i].Y) { if (location.X <= (gameBoardColumns[i].X + gameBoardColumns[i].Width) && Location.Y <= gameBoardColumns[i].Y + gameBoardColumns[i].Height) { // if so, return the column that was clicked return i; } } } // If you clicked out of the bounds of the game board return -1 return -1; } /// <summary> /// Checks vertically downwards from the current chip to see if the game is won /// </summary> /// <param name="row">Row of the current chip</param> /// <param name="column">Column of the current chip</param> /// <param name="currentColor">Current Color of the chip</param> /// <returns>If the game is won</returns> private bool checkVerticalWin(int row, int column, int currentColor) { int counter = 0; // Check the chips below the newly placed one to see if there is a match of 4 for (int i = row; i < rows; i++) { // Same State found if (boardState[i, column] == currentColor) { counter++; } // Different State found else { break; } // If at any point the counter becomes 4, there is a victory if (counter == 4) { return true; } } return false; } /// <summary> /// Checks the 2 directions [left, right] of the current chip to see if the game is won /// </summary> /// <param name="row">Row of the current chip</param> /// <param name="column">Column of the current chip</param> /// <param name="currentColor">Current Color of the chip</param> /// <returns>If the game is won</returns> private bool checkHorizontalWin(int row, int column, int currentColor) { // Horizontal case // Check if there is a connect 4 using the left and right of the placed chip int counter = 1; // includes the current dropped chip int leftOffset = 1; int rightOffset = 1; // Check for same state chips on the left side while (true) { // Off of the board if (column - leftOffset <= 0) { break; } // Same State found to the left if (boardState[row, column - leftOffset] == currentColor) { leftOffset++; counter++; } // Different State found to the left else { break; } } // Check for same state chips on the right side while (true) { // Off of the board if (column + rightOffset >= columns) { break; } // Same State found to the right if (boardState[row, column + rightOffset] == currentColor) { rightOffset++; counter++; } // Different State found to the right else { break; } } // If at any point the counter becomes 4, there is a victory if (counter == 4) { return true; } return false; } /// <summary> /// Checks the 2 diagonals [topleft-bottomright, topright-bottomleft] of the current chip to see if the game is won /// </summary> /// <param name="row">Row of the current chip</param> /// <param name="column">Column of the current chip</param> /// <param name="currentColor">Current Color of the chip</param> /// <returns>If the game is won</returns> private bool checkDiagonalWin(int row, int column, int currentColor) { int topLeftOffset = 1; int bottomRightOffset = 1; int topRightOffset = 1; int bottomLeftOffset = 1; #region topLeftBottomRight // Check top-left/bottom-right for a connect 4 int counter = 1; // includes the current dropped chip // Check for same state chips on the top-left side while (true) { // Off of the board if (column - topLeftOffset <= 0 || row - topLeftOffset <= 0) { break; } // Same State found to the top-left if (boardState[row - topLeftOffset, column - topLeftOffset] == currentColor) { topLeftOffset++; counter++; } // Different State found to the top-left else { break; } } // Check for same state chips on the bottom-right side while (true) { // Off of the board if (column + bottomRightOffset >= columns || row + bottomRightOffset >= rows) { break; } // Same State found to the bottom-right if (boardState[row + bottomRightOffset, column + bottomRightOffset] == currentColor) { bottomRightOffset++; counter++; } // Different State found to the bottom-right else { break; } } // If at any point the counter becomes 4, there is a victory if (counter == 4) { return true; } #endregion #region topRightBottomLeft // Reset counter and check top-right/bottom-left counter = 1; // includes the current dropped chip // Check for same state chips on the top-right side while (true) { // Off of the board if (column + topRightOffset >= columns || row - topRightOffset <= 0) { break; } // Same State found to the top-right if (boardState[row - topRightOffset, column + topRightOffset] == currentColor) { topRightOffset++; counter++; } // Different State found to the top-right else { break; } } // Check for same state chips on the bottom-left side while (true) { // Off of the board if (column - bottomLeftOffset <= 0 || row + bottomLeftOffset >= rows) { break; } // Same State found to the bottom-left if (boardState[row + bottomLeftOffset, column - bottomLeftOffset] == currentColor) { bottomLeftOffset++; counter++; } // Different State found to the bottom-left else { break; } } // If at any point the counter becomes 4, there is a victory if (counter == 4) { return true; } #endregion return false; } /// <summary> /// Check if a win was caused on the boardState with the added chip /// </summary> /// <returns>Boolean depicting if there is a winner</returns> private bool isWin(int row, int column) { // Initialize which color to check for int currentColor = boardState[row, column]; // if there is one of the following cases, the match is won // - 4 chips of the same color directly touching each other in a vertical line // - 4 chips of the same color directly touching each other in a horizontal line // - 4 chips of the same color directly touching each other in a diagonal line // Vertical case if(checkVerticalWin(row, column, currentColor) || checkHorizontalWin(row, column, currentColor) || checkDiagonalWin(row, column, currentColor)) { return true; } return false; } /// <summary> /// Create and show a win form with the correct values when the game enters the "win" state /// </summary> private void openWinForm() { WinForm wForm = new WinForm(this); wForm.ShowDialog(this); // give reference to current Game Form } } } <file_sep>/Server-Side/Connect-4-Server.cpp #include <iostream> #include <string.h> #include <string> #include <netinet/in.h> #include <sys/socket.h> #include <arpa/inet.h> #include <thread> #include <unistd.h> #include <vector> #include <mutex> #include <signal.h> #define PORT_NUM 10123 #define MAX_LISTEN 23 #define BUFFER_SIZE 1024 struct User { uint32_t sockfd; std::string ip; std::string username; }; // GLOBALS std::vector<User> g_user_list; // Contient tous les clients connectés et leurs info std::mutex mtx_user_list; // Mutex pour éviter la corruption lorsque g_user_list est utilisé par les threads uint32_t g_asker = 0; // Moyen pour envoyer de l'info entre les threads. Contient le client_s de celui qui demande à jouer std::mutex mtx_asker; // Mutex pour éviter la corruption lorsque g_asker est utilisé par les threads uint32_t server_s; // Remettre un buffer à 0 pour ne pas avoir du texte qui reste d'un message precédent void clear_buffer(char buf[]) { for(auto i = 0; i < BUFFER_SIZE; i++) buf[i] = '\0'; } // Passe tous les clients connectés, et leur donne un string avec le nombre d'autre clients, puis leur nom et leur IP en utilisant des délimiteurs. // Ex: "2!username:IP!username:IP" // Appellée lorsqu'un client connecte ou déconnecte. void inform_of_new_client() { std::cout << "Updating client list." << std::endl; char out_buf[BUFFER_SIZE]; mtx_user_list.lock(); // On passe tous les clients connectés for(auto user_to : g_user_list) { std::string msg = std::to_string(g_user_list.size() - 1) + '!'; // Le nombres de clients connectés, moins lui-même for(auto user_about : g_user_list) // On prend l'info des autres if(user_to.sockfd != user_about.sockfd) // On ne veut pas envoyer au client sa propre info. msg += user_about.username + ':' + user_about.ip + '!'; // On génère le string à envoyer msg.pop_back(); // On enlève le '!' de surplus à la fin. strcpy(out_buf, msg.c_str()); send(user_to.sockfd, out_buf, (strlen(out_buf)+1), 0); // On envoie le string au client clear_buffer(out_buf); } mtx_user_list.unlock(); } // Ajoute le nouvel utilisateur au vecteur de clients, puis informe tous ceux connecté du nouveau client. void new_user(uint32_t sockfd, std::string ip, std::string username) { std::cout << "User " << username << " is connected." << std::endl; mtx_user_list.lock(); g_user_list.emplace_back(User{sockfd, ip, username}); mtx_user_list.unlock(); inform_of_new_client(); } // Petite fonction pour pouvoir trouver le client_s de l'utilisateur dans notre vecteur de clients uint32_t find_user_sockfd(std::string username) { mtx_user_list.lock(); for(auto u : g_user_list) if (u.username == username) { uint32_t socket = u.sockfd; mtx_user_list.unlock(); return socket; } mtx_user_list.unlock(); return 0; } // Petite fonction pour pouvoir trouver le nom d'utilisateur avec son client_s dans notre vecteur de clients std::string find_user_name(uint32_t sockfd) { mtx_user_list.lock(); for (auto u : g_user_list) if (u.sockfd == sockfd) { std::string user = u.username; mtx_user_list.unlock(); return user; } mtx_user_list.unlock(); return ""; } // Petite fonction pour pouvoir trouver le IP de l'utilisateur avec son client_s dans notre vecteur de clients std::string find_user_ip(uint32_t sockfd) { mtx_user_list.lock(); for (auto u : g_user_list) if (u.sockfd == sockfd) { std::string ip = u.ip; mtx_user_list.unlock(); return ip; } mtx_user_list.unlock(); return ""; } // Fonction qui ferme la connection du client, puis le retire du vecteur de clients void disconnect_client(uint32_t sockfd) { std::string username = find_user_name(sockfd); close(sockfd); mtx_user_list.lock(); for(auto user = g_user_list.begin(); user != g_user_list.end(); user++) { if(user->sockfd == sockfd) { g_user_list.erase(user); std::cout << "User " << username << " has disconnected." << std::endl; break; } } mtx_user_list.unlock(); } // Fonction qui écoute pour des messages du client. void listen_for_msg(uint32_t user1_s) { char in_buf[BUFFER_SIZE]; char out_buf[BUFFER_SIZE]; while(1) { // On attend de receoir un message. int val = recv(user1_s, in_buf, sizeof(in_buf), 0); if(val == -1) // Si le socket ferme de façon innatendue, on enlève le client de notre liste. { disconnect_client(user1_s); return; } std::string input = std::string(in_buf); // Le message reçi // Message du client pour avertir qu'il se déconnecte. if (input == "##bye##") { disconnect_client(user1_s); inform_of_new_client(); } // La réponse à la demande de jeu else if(input == "##accept##" || input == "##reject##") { mtx_asker.lock(); uint32_t user2_s = g_asker; // Trouver c'est qui qui avait demandé de jouer g_asker = 0; mtx_asker.unlock(); //user2 answers yes or no strcpy(out_buf, input.c_str()); send(user2_s, out_buf, (strlen(out_buf) + 1), 0); if (input == "##accept##") std::cout << find_user_name(user1_s) << " accepted the game with " << find_user_name(user2_s) << "." << std::endl; else std::cout << find_user_name(user1_s) << " rejected the game with " << find_user_name(user2_s) << "." << std::endl; } // Le client demande de jouer avec un autre. Il envoie son nom d'utilisateur. else { // request to user2 uint32_t user2_s = find_user_sockfd(input); std::string user1_name = find_user_name(user1_s) + ':' + find_user_ip(user1_s); std::cout << find_user_name(user1_s) << " is asking " << find_user_name(user2_s) << " to play." << std::endl; // On stock qui demande pour que le thread de celui qui se fait demander save qui c'est. // On ne veut pas que l'information se perd si deux joueurs demandent en même temps donc on lock avec un mutex. Une seule demande peut se faire à la fois. // La seconde demande se fera lorsque la première est acceptée ou refusée mtx_asker.lock(); while(g_asker != 0) { mtx_asker.unlock(); mtx_asker.lock(); } g_asker = user1_s; mtx_asker.unlock(); // On envoie le nom d'utilisateur et le IP de celui qui demande au client demandé strcpy(out_buf, user1_name.c_str()); send(user2_s, out_buf, (strlen(out_buf) + 1), 0); } input.clear(); clear_buffer(out_buf); clear_buffer(in_buf); } } // Fonction qui est appellé lorsqu'on appuis sur CTRL+C dans l'execusion du serveur void interrupt_handler(int sig) { char out_buf[BUFFER_SIZE] = {'\0'}; strcpy(out_buf, "##disconnect##"); // Message à envoyer aux clients pour leur dire que le client se ferme et qu'ils doivent se déconnecter std::cout << std::endl << "Server is closing. Disconnecting everyone." << std::endl; mtx_user_list.lock(); for(auto user : g_user_list) { // Pour chaque client on envoie le message, puis on ferme leur connection send(user.sockfd, out_buf, (strlen(out_buf)+1), 0); close(user.sockfd); std::cout << "Disconnected " << user.username << "." << std::endl; } mtx_user_list.unlock(); // On ferme le socket du serveur puis un exit close(server_s); exit(0); } int main() { signal(SIGINT, &interrupt_handler); // Intercepter CTRL+C struct sockaddr_in server_addr; server_s = socket(AF_INET, SOCK_STREAM, 0); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(PORT_NUM); server_addr.sin_addr.s_addr = htonl(INADDR_ANY); bind(server_s, (struct sockaddr *)&server_addr, sizeof(server_addr)); listen(server_s, MAX_LISTEN); uint32_t client_s; struct sockaddr_in client_addr; struct in_addr client_ip_addr; uint32_t addr_len = sizeof(client_addr); std::cout << "Server started." << std::endl; std::vector<std::thread> client_threads; // Structure pour tiendre compte des threads qu'on créer. while(1) { client_s = accept(server_s, (struct sockaddr *) &client_addr, &addr_len); memcpy(&client_ip_addr, &client_addr.sin_addr.s_addr, 4); // IP du client //Receive username from client char in_buf[BUFFER_SIZE] = {'\0'}; int val = recv(client_s, in_buf, sizeof(in_buf), 0); // On reçoie le nom d'utilisateur if(val == -1) continue; // On créer un thread afin d'ajouter un client pour revenir écouter le plus vite possible. Le thread se termine vite. client_threads.emplace_back(&new_user, client_s, inet_ntoa(client_ip_addr), std::string(in_buf)); // Pour chaque client on a un thread qui écoute pour les messages qu'il peut envoyer. client_threads.emplace_back(&listen_for_msg, client_s); } // Précaution en cas où le while(1) se termine. for(auto &t : client_threads) t.join(); for(auto user : g_user_list) close(user.sockfd); close(server_s); return 0; } <file_sep>/Client-Side/Connect-4-Client/Connect-4-Client/WelcomeForm.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Connect_4_Client { public partial class WelcomeForm : Form { public string nameText = ""; // Contains the name given by the user /// <summary> /// Constructor to the WelcomeForm /// </summary> public WelcomeForm() { // Initial configs InitializeComponent(); CenterToScreen(); } /// <summary> /// Every time the text is changed in the text box, save the contents in the nameText variable /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void textBox1_TextChanged(object sender, EventArgs e) { TextBox objTextBox = (TextBox)sender; // Create temporary textbox with the content of the textbox on screen nameText = objTextBox.Text; // save its content } /// <summary> /// Close the application if X is clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void WelcomeForm_FormClosing(object sender, EventArgs e) { Application.Exit(); } /// <summary> /// When the enter button is clicked, close the current window (not the whole application) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { this.Close(); } } }
c2a2f3a6305ac0d58ff5e73f7061c78049644697
[ "Markdown", "C#", "C++" ]
7
Markdown
Patrick-Doucet/connect-4-online
4c020855c9cbd8c91252711e67d253bf57aba69d
e9de8e9f16470b54c28fc5051cb30b4791fc41be
refs/heads/master
<repo_name>cesarnicola/nodefront<file_sep>/commands/compile.js var fs = require('fs'); var q = require('q'); var jade = require('jade'); var stylus = require('stylus'); var pathLib = require('path'); var utils = require('../lib/utils'); var coffeeScript = require('coffee-script'); // files with these extensions need to be compiled var compiledExtensions = { 'coffee': undefined, 'jade': undefined, 'styl': undefined, 'stylus': undefined }; // compile functions for each file; file name => function map var compileFns = {}; // what files are dependent on a given file; file => dependents map var dependents = {}; // what are a given file's dependencies; file => dependencies map; inverse of // above map var dependencies = {}; // regular expressions for finding dependencies var rJadeInclude = /^[ \t]*include[ \t]+([^\n]+)/gm; var rJadeExtends = /^[ \t]*extends?[ \t]+([^\n]+)/gm; var rStylusInclude = /^[ \t]*@import[ \t]+([^\n]+)/gm; /** * Node Module Export * ------------------ * Exports the compile command for nodefront. This finds all *.jade, *.styl, * *.stylus, and *.coffee target files in the current directory and compiles * them to corresponding *.html, *.css, and *.js. * * @param env - the command-line environment * If the -r/--recursive flag is specified, the current directory is * recursively searched for target files. * * If the -w/--watch flag is specified, target files are recompiled upon * modification. Dependencies are also evaluated so that if, for example, * layout.jade includes index.jade, when index.jade is modified, both * index.jade and layout.jade are recompiled. This is referred to as * "dependency-intelligent" recompilation * * If the -s/--serve <port> flag is specified, the files in the current * directory are served on localhost at the given port number, which * defaults to 3000. * * If the -l/--live <port> flag is specified, -w/--watch and -s/--serve <port> * are implied. Not only are files recompiled upon modification, but the * browser is also automatically updated when corresponding HTML/CSS/JS/Jade/ * Stylus files are altered. In the case of CSS/Stylus, link tags on the page * are simply removed and re-added. For HTML/JS/Jade, the browser is refreshed * entirely. * * @param shouldPromise - if true, returns a promise that yields completion */ module.exports = exports = function(env, shouldPromise) { var server; var io; if (env.serve || env.live) { // serve the files on localhost if (typeof env.serve == 'number') { server = serveFilesLocally(env.serve, env.live); } else { server = serveFilesLocally(3000, env.live); } } if (env.live) { // initiate the socket connection io = require('socket.io').listen(server); io.sockets.on('connection', function(socket) { socket.on('resolvePaths', function(paths) { var resolvedPaths = []; var absPath; // use path library to resolve paths resolvedPaths[0] = pathLib.resolve('.' + paths[0]); resolvedPaths[1] = {}; resolvedPaths[2] = {}; // resolve each path in the latter two arrays, keeping track of the new // path and original in a map of new => original for (var i = 1; i <= 2; i++) { for (var j = 0; j < paths[i].length; j++) { absPath = pathLib.resolve('.' + paths[i][j]); resolvedPaths[i][absPath] = paths[i][j]; } } // let the client know socket.emit('pathsResolved', resolvedPaths); }); }); } var promise = findFilesToCompile(env.recursive) .then(function(compileData) { var promises = []; // process each file to compile compileData.forEach(function(compileDatum) { // compileDatum is in the form [file_name_without_extension, extension, // contents]; extract this information var fileNameSansExtension = compileDatum[0]; var extension = compileDatum[1]; var contents = compileDatum[2]; var fileName = fileNameSansExtension + '.' + extension; // compile the current file and record this function var compileFn = generateCompileFn(fileNameSansExtension, extension, contents, env.live); compileFns[fileName] = compileFn; promises.push(compileFn()); if (env.watch || env.live) { // record dependencies for dependency-intelligent recompilation recordDependencies(fileName, extension, contents); recompileUponModification(fileName, extension, io); } }); return q.all(promises); }); if (shouldPromise) { return promise; } else { promise.end(); } if (env.live) { // communicate to client whenever file is modified trackModificationsLive(io, env.recursive); } }; /** * Function: trackModificationsLive * -------------------------------- * Watch all HTML, CSS, and JS files for modifications. Emit a fileModified * event to the client upon modification to allow for live refreshes. * * @param io - socket.io connection if this is live mode * @param recursive - true to watch all files in subdirectories as well */ function trackModificationsLive(io, recursive) { utils.readDirWithFilter('.', true, /\.(html|css|js)$/, true) .then(function(files) { files.forEach(function(fileName) { // use a small interval for quick live refreshes utils.watchFileForModification(fileName, 200, function() { io.sockets.emit('fileModified', fileName); }); }); }); } /** * Function: serveFilesLocally * --------------------------- * Serves the files in the current directory on localhost at the given port * number. * * @param port - the port number to serve the files on * @param live - true if this is live mode * * @return the node HTTP server */ function serveFilesLocally(port, live) { var http = require('http'); var mime = require('mime'); if (live) { // scripts to dynamically insert into html pages var scripts = '<script src="/socket.io/socket.io.js"></script>' + '<script src="/nodefront/live.js"></script>'; } var server = http.createServer(function(request, response) { if (request.method == 'GET') { // file path in current directory var path = '.' + request.url.split('?')[0]; var mimeType = mime.lookup(path, 'text/plain'); var charset = mime.charsets.lookup(mimeType, ''); var binary = charset !== 'UTF-8'; // redirect /nodefront/live.js request to nodefront's live.js if (live && path === './nodefront/live.js') { path = pathLib.resolve(__dirname + '/../live.js'); } // if file exists, serve it; otherwise, return a 404 utils.readFile(path, binary) .then(function(contents) { // find this file's mime type or default to text/plain response.writeHead(200, {'Content-Type': mimeType}); if (live && mimeType === 'text/html') { // add scripts before end body tag contents = contents.replace('</body>', scripts + '</body>'); // if no end body tag is present, just append scripts if (contents.indexOf(scripts) === -1) { contents = contents + scripts; } } if (binary) { response.end(contents, 'binary'); } else { response.end(contents); } }, function(err) { response.writeHead(404, {'Content-Type': 'text/plain'}); response.end('File not found.'); }) .end(); } else { // bad request error code response.writeHead(400, {'Content-Type': 'text/plain'}); response.end('Unsupported request type.'); } }).listen(port, '127.0.0.1'); console.log('Serving your files at http://127.0.0.1:' + port + '/.'); return server; } /** * Function: recompileUponModification * ----------------------------------- * Recompiles the given file upon modification. This also recompiles any files * that depend on this file. * * @param fileName - the name of the file * @param extension - the extension of the file */ function recompileUponModification(fileName, extension, io) { utils.watchFileForModification(fileName, 1000, function() { q.ncall(fs.readFile, fs, fileName, 'utf8') .then(function(contents) { // this may be a static file that doesn't have a compile function, but // is a dependency for some other compiled file if (compileFns[fileName]) { compileFns[fileName]() .end(); // reset dependencies clearDependencies(fileName); recordDependencies(fileName, extension, contents); } // compile all files that depend on this one for (var dependentFile in dependents[fileName]) { console.log('Compiling dependent:', dependentFile); if (compileFns[dependentFile]) { compileFns[dependentFile]() .end(); } } }) .end(); }); } /** * Function: recordDependencies * ---------------------------- * Given a file's name, extension and contents, records its compilation * dependencies for use while watching it for changes. * * @param fileName - the name of the file * @param extension - the extension of the file * @param contents - the contents of the file */ function recordDependencies(fileName, extension, contents) { var dirName = pathLib.dirname(fileName); var matches; var dependencyFile; // find dependencies switch (extension) { case 'jade': while ((matches = rJadeInclude.exec(contents)) || (matches = rJadeExtends.exec(contents))) { dependencyFile = matches[1]; // if no extension is provided, use .jade if (dependencyFile.indexOf('.') === -1) { dependencyFile += '.jade'; } dependencyFile = pathLib.resolve(dirName, dependencyFile); // this file is dependent upon dependencyFile // TODO: this currently only works with .jade dependency // files; add support for static files later on addDependency(dependencyFile, fileName); } break; case 'styl': case 'stylus': while ((matches = rStylusInclude.exec(contents))) { dependencyFile = matches[1]; // if no extension is provided, use .styl if (dependencyFile.indexOf('.') === -1) { dependencyFile += '.styl'; dependencyFile = pathLib.resolve(dirName, dependencyFile); // this may be an index include; resolve it try { fs.statSync(dependencyFile); } catch (e) { // actually including /index.styl dependencyFile = matches[1] + '/index.styl'; } } addDependency(dependencyFile, fileName); } break; } } /** * Function: generateCompileFn * --------------------------- * Given a file name and its extension, returns a function that compiles this * file based off of its type (jade, stylus, coffee, etc.). * * @param fileNameSansExtension - file name without extension * @param extension - the extension of the file name * @param live - true if this is live mode * * @return function to compile this file that takes no parameters */ function generateCompileFn(fileNameSansExtension, extension, live) { return function() { var fileName = fileNameSansExtension + '.' + extension; var contents = fs.readFileSync(fileName, 'utf8'); var promise; switch (extension) { case 'coffee': // run coffee-script's compile promise = q.fcall(function() { return coffeeScript.compile(contents); }) .then(function(outputJS) { var compiledFileName = fileNameSansExtension + '.js'; var compiledFileDisplay = pathLib.relative('.', compiledFileName); return utils.writeFile(compiledFileName, outputJS) .then(function() { console.log('Compiled ' + compiledFileDisplay + '.'); }); }); break; case 'jade': // run jade's render promise = q.ncall(jade.render, jade, contents, { filename: fileName }) .then(function(outputHTML) { var compiledFileName = fileNameSansExtension + '.html'; var compiledFileDisplay = pathLib.relative('.', compiledFileName); return utils.writeFile(compiledFileName, outputHTML) .then(function() { console.log('Compiled ' + compiledFileDisplay + '.'); }); }); break; case 'styl': case 'stylus': // run stylus' render promise = q.ncall(stylus.render, stylus, contents, { filename: fileName, compress: true }) .then(function(outputCSS) { var compiledFileName = fileNameSansExtension + '.css'; var compiledFileDisplay = pathLib.relative('.', compiledFileName); return utils.writeFile(compiledFileName, outputCSS) .then(function() { console.log('Compiled ' + compiledFileDisplay + '.'); }); }); break; } return promise .fail(function(error) { console.error(error.message); }); }; } /** * Function: findFilesToCompile * ---------------------------- * Reads the current directory and promises a list of files along with their * contents. * * @param recursive - true to read the current directory recursively * @return promise that yields an array of arrays in the form * [ [file_name_1_without_extension, file_name_1_extension, contents_1], * [file_name_2_without_extension, file_name_2_extension, contents_2], ... ]. */ function findFilesToCompile(recursive) { var rsFilter = '\\.('; for(var extension in compiledExtensions) { rsFilter += extension + '|'; } rsFilter = rsFilter.substr(0, rsFilter.length - 1) + ')$'; return utils.readDirWithFilter('.', recursive, new RegExp(rsFilter), true) .then(function(files) { var deferred = q.defer(); // contains arrays of [file name sans extension, extension, contents] // i.e. for index.jade, array would be ['index', 'jade', contents of // index.jade] var compileData = []; var numFiles = files.length; files.forEach(function(file, index) { // extract extension and contents of current file var extensionLoc = file.lastIndexOf('.'); var extension = file.substr(extensionLoc + 1); q.ncall(fs.readFile, fs, file, 'utf8') .then(function(contents) { compileData.push([file.substr(0, extensionLoc), extension, contents]); // done? if so, resolve with compileData if (index == numFiles - 1) { deferred.resolve(compileData); } }) .end(); }); return deferred.promise; }); } /** * Function: addDependency * ----------------------- * Records a compilation dependency. * * @param fileName - the file name that dependent depends upon * @param dependent - the file name that is dependent on fileName */ function addDependency(fileName, dependent) { // add to dependents map if (!dependents[fileName]) { dependents[fileName] = {}; } dependents[fileName][dependent] = true; // add to dependencies map if (!dependencies[dependent]) { dependencies[dependent] = {}; } dependencies[dependent][fileName] = true; } /** * Function: clearDependencies * --------------------------- * Clear the dependencies of the given file. * * @param fileName - the name of the file */ function clearDependencies(fileName) { // clear dependents map for (var dependency in dependencies[fileName]) { delete dependents[dependency][fileName]; } // clear dependency map delete dependencies[fileName]; } <file_sep>/Changelog.md 0.0.5 / 2012-08-09 ================== * Catch compilation errors to prevent crashes. Addresses issue #2. 0.0.4 / 2012-08-08 ================== * Add support to compile CoffeeScript. Addresses issue #1. * Display cleaner relative paths. <file_sep>/Makefile test: @./node_modules/.bin/mocha --reporter list test-fetch: @./node_modules/.bin/mocha test/test.fetch.js --reporter list test-minify: @./node_modules/.bin/mocha test/test.minify.js --reporter list test-insert: @./node_modules/.bin/mocha test/test.insert.js --reporter list test-compile: @./node_modules/.bin/mocha test/test.compile.js --reporter list .PHONY: test <file_sep>/live.js // file and dir path of currently-viewed HTML page var currentFilePath = location.pathname; var currentDirPath = location.pathname.substr(0, location.pathname.lastIndexOf('/')); // socket communication var socket = io.connect('http://localhost:' + location.port); // link tag information var linkTags = document.querySelectorAll('link'); var linkTag; var linkHref; // map of absolute source path => [link tag, original source path] var linkSources = {}; var linkSourceList = []; // script tag information var scriptTags = document.querySelectorAll('script'); var scriptTag; var scriptSrc; // map of absolute source path => [script tag, original source path] var scriptSources = {}; var scriptSourceList = []; // record sources of all JS files for (i = 0; i < scriptTags.length; i++) { scriptTag = scriptTags[i]; scriptSrc = scriptTag.getAttribute('src'); // record only if src exists if (scriptSrc) { scriptSrc = scriptSrc.split('?')[0]; origScriptSrc = scriptSrc; // make path relative to root if (scriptSrc[0] !== '/') { scriptSrc = currentDirPath + '/' + scriptSrc; } scriptSources[scriptSrc] = [scriptTag, origScriptSrc]; } } // record sources of all CSS files for (i = 0; i < linkTags.length; i++) { linkTag = linkTags[i]; linkHref = linkTag.getAttribute('href'); // record only if href exists if (linkHref) { linkHref = linkHref.split('?')[0]; origLinkHref = linkHref; // make path relative to root if (linkHref[0] !== '/') { linkHref = currentDirPath + '/' + linkHref; } linkSources[linkHref] = [linkTag, origLinkHref]; } } // extract keys to get a list of link/script sources for (var linkSource in linkSources) { linkSourceList.push(linkSource); } for (var scriptSource in scriptSources) { scriptSourceList.push(scriptSource); } // paths need to be normalized; have the server make them absolute socket.emit('resolvePaths', [currentFilePath, linkSourceList, scriptSourceList]); socket.on('pathsResolved', function(paths) { // paths is now an array of absolute file paths var origSource; currentFilePath = paths[0]; // paths[1] and paths[2] are objects of the form: // { // absolute path 1: original path 1, // absolute path 2: original path 2, // ... // } for (var linkSource in paths[1]) { origSource = paths[1][linkSource]; linkSources[linkSource] = linkSources[origSource]; delete linkSources[origSource]; } for (var scriptSource in paths[2]) { origSource = paths[2][scriptSource]; scriptSources[scriptSource] = scriptSources[origSource]; delete scriptSources[origSource]; } console.log(currentFilePath, linkSources, scriptSources); }); socket.on('fileModified', function(filePath) { if (filePath in linkSources) { linkTag = linkSources[filePath][0]; // add cache-busting query string to force the browser to reload this css linkTag.setAttribute('href', linkSources[filePath][1] + '?' + new Date().getTime()); } else if (filePath in scriptSources || filePath == currentFilePath) { // true parameter forces browser to skip cache location.reload(true); } }); <file_sep>/test/lib/utils.js var fs = require('fs'); var should = require('should'); var utils = require('../../lib/utils'); /** * Function: expectFilesToMatch * ---------------------------- * Expects the contents of the two given files to match. * * @param fileNameA - the first file * @param fileNameB - the second file * * @return promise that yields success if the contents match or an error * otherwise */ exports.expectFilesToMatch = function(fileNameA, fileNameB) { var expected; return utils.readFile(fileNameA) .then(function(contents) { expected = contents; return utils.readFile(fileNameB); }) .then(function(contents) { try { contents.should.eql(expected); } catch (error) { // don't print out contents and expected because they are too large throw new Error("Contents don't match expected."); } }); };
8bcbfda8621b833def688688102909d9d04b023f
[ "JavaScript", "Makefile", "Markdown" ]
5
JavaScript
cesarnicola/nodefront
24eb59f4bb4a88470b104bc6d0b5b4854bc4004f
f5683c98e5054e0e351d0a79dc72bc4f885afc45
refs/heads/master
<file_sep>import os from haproxy_stats import HaproxyStats from vrouter.loadbalancer.ttypes import \ UveLoadbalancerTrace, UveLoadbalancer, UveLoadbalancerStats LB_BASE_DIR = '/var/lib/contrail/loadbalancer/' def _uve_get_stats(stats): obj_stats = UveLoadbalancerStats() obj_stats.obj_name = stats['name'] obj_stats.uuid = stats['name'] obj_stats.status = stats['status'] for attr in dir(obj_stats): if attr in stats and stats[attr].isdigit(): setattr(obj_stats, attr, int(stats[attr])) return [obj_stats] def _uve_get_member_stats(stats): member_stats = [] for stat in stats: obj_stats = UveLoadbalancerStats() obj_stats.obj_name = stat['name'] obj_stats.uuid = stat['name'] obj_stats.status = stat['status'] for attr in dir(obj_stats): if attr in stat and stat[attr].isdigit(): setattr(obj_stats, attr, int(stat[attr])) member_stats.append(obj_stats) return member_stats def _send_loadbalancer_uve(driver): for pool_uuid in os.listdir(LB_BASE_DIR): stats = driver.get_stats(pool_uuid) if not len(stats) or not stats.get('vip') or not stats.get('pool'): continue uve_lb = UveLoadbalancer() uve_lb.name = pool_uuid uve_lb.virtual_ip_stats = _uve_get_stats(stats['vip']) uve_lb.pool_stats = _uve_get_stats(stats['pool']) uve_lb.member_stats = _uve_get_member_stats(stats['members']) uve_trace = UveLoadbalancerTrace(data=uve_lb) uve_trace.send() def send_loadbalancer_stats(): driver = HaproxyStats() _send_loadbalancer_uve(driver) <file_sep>/* * Copyright (c) 2013 <NAME>, Inc. All rights reserved. */ #ifndef vnsw_agent_uve_test_h #define vnsw_agent_uve_test_h #include <uve/agent_uve.h> class AgentUveBaseTest : public AgentUve { public: AgentUveBaseTest(Agent *agent, uint64_t intvl, uint32_t default_intvl, uint32_t incremental_intvl); virtual ~AgentUveBaseTest(); private: DISALLOW_COPY_AND_ASSIGN(AgentUveBaseTest); }; #endif //vnsw_agent_uve_test_h <file_sep>/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #include <base/cpuinfo.h> #include <db/db.h> #include <cmn/agent_cmn.h> #include <oper/interface_common.h> #include <oper/interface.h> #include <uve/stats_collector.h> #include <uve/agent_uve.h> #include <uve/stats_interval_types.h> #include <init/agent_param.h> #include <oper/mirror_table.h> #include <uve/vrouter_stats_collector.h> #include <uve/vm_uve_table.h> #include <uve/vn_uve_table.h> #include <uve/vrouter_uve_entry.h> #include <uve/interface_uve_stats_table.h> AgentUve::AgentUve(Agent *agent, uint64_t intvl, uint32_t default_intvl, uint32_t incremental_intvl) : AgentUveBase(agent, intvl, false, default_intvl, incremental_intvl), stats_manager_(new StatsManager(agent)) { //Override vm_uve_table_ to point to derived class object vn_uve_table_.reset(new VnUveTable(agent, default_intvl)); vm_uve_table_.reset(new VmUveTable(agent, default_intvl)); vrouter_uve_entry_.reset(new VrouterUveEntry(agent)); interface_uve_table_.reset(new InterfaceUveStatsTable(agent, default_intvl)); } AgentUve::~AgentUve() { } StatsManager *AgentUve::stats_manager() const { return stats_manager_.get(); } void AgentUve::Shutdown() { AgentUveBase::Shutdown(); stats_manager_->Shutdown(); } void AgentUve::RegisterDBClients() { AgentUveBase::RegisterDBClients(); stats_manager_->RegisterDBClients(); } // The following is deprecated and is present only for backward compatibility void GetStatsInterval::HandleRequest() const { StatsIntervalResp_InSeconds *resp = new StatsIntervalResp_InSeconds(); resp->set_agent_stats_interval(0); resp->set_flow_stats_interval(0); resp->set_context(context()); resp->Response(); return; }
3ad286d602eb257140caf9ce2425760eb73a2a4a
[ "Python", "C++" ]
3
Python
anshprat/contrail-controller
16e9e119f3f9e9b5370e1ff4627f31acc8c43b71
848e21f4f364a09ffc8f2538592cd09bfb832e9e
refs/heads/master
<repo_name>tomasz-kaczorek/genetic-algorithm<file_sep>/engine.h #ifndef ENGINE_H #define ENGINE_H #include <boost/random.hpp> #include <stddef.h> class Engine { private: struct Chromosome; double (* m_f)(double const *, size_t); void (* m_x)(double *, size_t); size_t m_n; size_t m_mu; size_t m_lambda; int m_generations; int m_maxGenerations; double m_epsilon; double m_crossoverProbability; double m_mutationProbability; boost::mt19937 m_generator; boost::random::discrete_distribution<> m_draw; boost::random::uniform_01<> m_uniform; boost::random::normal_distribution<> m_normal; Chromosome ** m_population; public: Engine(double (* f)(double const *, size_t), void (* x)(double *, size_t), size_t n, size_t mu = 10, size_t lambda = 20, int maxGenerations = 10000, double epsilon = 0.01, double crossoverProbability = 0.95, double mutationProbability = 0.05); size_t draw(); double uniform(); double normal(); void step(); double error(); void crossover(Chromosome *, Chromosome *); void mutate(Chromosome *); void rate(Chromosome *); void duplicate(Chromosome *, Chromosome *); double nthFitness(size_t n); double * nthAlleles(size_t n); static int compare(const void *, const void *); }; struct Engine::Chromosome { double m_fitness; double * m_alleles; double * m_sigma; Chromosome(size_t n, void (* alleles)(double *, size_t), void (* sigma)(double *, size_t) = nullptr); }; #endif // ENGINE_H <file_sep>/main.cpp #include "engine.h" #include <QDebug> double f(double const * X, size_t n) { double result = 0.0; for(size_t i = 2; i < n; ++i) { result += 100 * (pow(X[i], 2) + pow(X[i-1], 2)) + pow(X[i-2], 2); } return result; } void x(double * X, size_t n) { for(size_t i = 0; i < n; ++i) { X[i] = 3.0; } } int main(int argc, char *argv[]) { Engine engine(f, x, 10); for(int i = 0; i < 1000; ++i) { engine.step(); qDebug("Function evaluatiob: %f\nError: %f\nAlleles: ", engine.nthFitness(0), engine.error()); for(size_t j = 0; j < 10; ++j) { qDebug("%f ", engine.nthAlleles(0)[j]); } qDebug("\n"); } return 0; } <file_sep>/engine.cpp #include "engine.h" #include <stdlib.h> #include <QDebug> Engine::Engine(double (* f)(double const *, size_t), void (* x)(double *, size_t), size_t n, size_t mu, size_t lambda, int maxGenerations, double epsilon, double crossoverProbability, double mutationProbability) : m_f(f), m_x(x), m_n(n), m_mu(mu), m_lambda(lambda), m_generations(0), m_maxGenerations(maxGenerations), m_epsilon(epsilon), m_crossoverProbability(crossoverProbability), m_mutationProbability(mutationProbability), m_generator(time(nullptr)) { std::vector<double> weights(n); for(size_t i = 0; i < n; ++i) weights[i] = n - i; m_draw = boost::random::discrete_distribution<>(weights.begin(), weights.end()); m_population = new Chromosome * [mu + lambda]; for(size_t i = 0; i < mu + lambda; ++i) { m_population[i] = new Chromosome(n, x); rate(m_population[i]); } } size_t Engine::draw() { return m_draw(m_generator); } double Engine::uniform() { return m_uniform(m_generator); } double Engine::normal() { return m_normal(m_generator); } void Engine::step() { for(size_t i = m_mu; i < m_mu + m_lambda; i += 2) { duplicate(m_population[i], m_population[draw()]); duplicate(m_population[i + 1], m_population[draw()]); crossover(m_population[i], m_population[i + 1]); mutate(m_population[i]); mutate(m_population[i + 1]); rate(m_population[i]); rate(m_population[i + 1]); } std::qsort(m_population, m_mu + m_lambda, sizeof(Chromosome *), compare); } double Engine::error() { double alleles[m_n]; double h; double t; double result; result = 0.0; memcpy(alleles, m_population[0]->m_alleles, m_n * sizeof(double)); for(size_t i = 0; i < m_n; ++i) { t = alleles[i]; h = sqrt(DBL_EPSILON) * fmax(1.0, fabs(t)); alleles[i] += h; result += pow((m_f(alleles, m_n) - m_f(m_population[0]->m_alleles, m_n)) / h, 2.0); alleles[i] = t; } return sqrt(result); return 0.0; } void Engine::crossover(Engine::Chromosome * chromosome1, Engine::Chromosome * chromosome2) { if(uniform() < m_crossoverProbability) { int a = uniform(); for(size_t i = 0; i < m_n; ++i) { double allele1 = chromosome1->m_alleles[i]; double allele2 = chromosome2->m_alleles[i]; chromosome1->m_alleles[i] = a * allele1 + (1.0 - a) * allele2; chromosome2->m_alleles[i] = (1.0 - a) * allele1 + a * allele2; } } } void Engine::mutate(Engine::Chromosome * chromosome) { static double tau1 = 1.0 / sqrt(2.0 * m_n); static double tau2 = 1.0 / sqrt(2.0 * sqrt(m_n)); double tau = tau1 * normal(); for(size_t i = 0; i < m_n; ++i) { if(uniform() < m_mutationProbability) { chromosome->m_alleles[i] = chromosome->m_alleles[i] * chromosome->m_sigma[i] * normal(); chromosome->m_sigma[i] = chromosome->m_sigma[i] * exp(tau + tau2 * normal()); } } } void Engine::rate(Engine::Chromosome * chromosome) { chromosome->m_fitness = m_f(chromosome->m_alleles, m_n); } void Engine::duplicate(Engine::Chromosome * destination, Engine::Chromosome * source) { destination->m_fitness = source->m_fitness; for(size_t i = 0; i < m_n; ++i) { destination->m_alleles[i] = source->m_alleles[i]; destination->m_sigma[i] = source->m_sigma[i]; } } double Engine::nthFitness(size_t n) { return m_population[n]->m_fitness; } double * Engine::nthAlleles(size_t n) { return m_population[n]->m_alleles; } int Engine::compare(const void * ptr1, const void * ptr2) { Chromosome * chromosome1 = *((Chromosome **) ptr1); Chromosome * chromosome2 = *((Chromosome **) ptr2); if(chromosome1->m_fitness < chromosome2->m_fitness) return -1; if(chromosome1->m_fitness > chromosome2->m_fitness) return 1; return 0; } Engine::Chromosome::Chromosome(size_t n, void (* alleles)(double *, size_t), void (* sigma)(double *, size_t)) { m_alleles = new double[n]; alleles(m_alleles, n); m_sigma = new double[n]; if(sigma != nullptr) sigma(m_sigma, n); else { for(size_t i = 0; i < n; ++i) { m_sigma[i] = 1.0; } } } /* double Engine::Chromosome::error(double (*f)(double * x)) { }*/
b553c2a81f8486b0437811f22a854bbaffbc84da
[ "C++" ]
3
C++
tomasz-kaczorek/genetic-algorithm
a9eb72a94f7ebf8f0a62a526a432c4b893aaa2c6
21a30392b24e09d57ea2730e4e046462b6e721f8
refs/heads/master
<file_sep>from django.shortcuts import render, redirect from django.urls import reverse_lazy from django.views import generic from django.contrib.auth.forms import UserCreationForm, UserChangeForm, PasswordChangeForm from django.contrib.auth import authenticate, login, update_session_auth_hash from .models import Hall, Video from .forms import VideoForm, SearchForm, EditProfileForm from django.forms import formset_factory from django.http import Http404, JsonResponse from django.forms.utils import ErrorList from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin import urllib import requests YOUTUBE_API_KEY = '<KEY>' # Create your views here. def home(request): recent_fav = Hall.objects.all().order_by('-id')[:3] popular_fav = [Hall.objects.get(pk=1),Hall.objects.get(pk=2)] return render(request, 'halls/home.html', {'recent_fav':recent_fav, 'popular_fav':popular_fav}) @login_required def dashboard(request): halls = Hall.objects.filter(user=request.user) return render(request, 'halls/dashboard.html', {'halls':halls}) @login_required def add_video(request, pk): VideoFormSet = formset_factory(VideoForm, extra=3) form = VideoForm() search_form = SearchForm() hall = Hall.objects.get(pk=pk) # if someone tries to add somdthing and they are not the correct owner if not hall.user == request.user: raise Http404 if request.method == 'POST': # form validation making the video objects form = VideoForm(request.POST) if form.is_valid(): video = Video() video.hall = hall video.url = form.cleaned_data['url'] parsed_url = urllib.parse.urlparse(video.url) video_id = urllib.parse.parse_qs(parsed_url.query).get('v') if video_id: video.youtube_id = video_id[0] response = requests.get(f'https://www.googleapis.com/youtube/v3/videos?part=snippet&id={ video_id[0] }&key={ YOUTUBE_API_KEY }') json = response.json() title = json['items'][0]['snippet']['title'] video.title = title video.save() return redirect('detail_fav', pk) else: errors = form._errors.setdefault('url', ErrorList()) errors.append('The url you entered MUST be from youtube.com') # template below return render(request, 'halls/add_video.html', {'form':form, 'search_form':search_form, 'hall':hall}) @login_required def video_search(request): search_form = SearchForm(request.GET) if search_form.is_valid(): encoded_search_term = urllib.parse.quote(search_form.cleaned_data['search_term']) response = requests.get(f'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=6&q={ encoded_search_term }&key={ YOUTUBE_API_KEY }') return JsonResponse(response.json()) else: return JsonResponse({'error':'unable to validate form'}) class DeleteVideo(LoginRequiredMixin, generic.DeleteView): model = Video template_name='halls/delete_video.html' success_url = reverse_lazy('dashboard') def get_object(self): video = super(DeleteVideo, self).get_object() if not video.hall.user == self.request.user: raise Http404 else: return video @login_required def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect ('home') else: form = EditProfileForm(instance=request.user) context={'form':form} return render(request, 'registration/edit_profile.html', context) @login_required def change_password(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return redirect ('home') else: form = PasswordChangeForm(user=request.user) context={'form':form} return render(request, 'registration/change_password.html', context) class SignUp(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('dashboard') template_name = 'registration/signup.html' ################################################### # this function customizes the class and logs # the user in automatically after they sign up ################################################### def form_valid(self, form): view = super(SignUp, self).form_valid(form) username, password = form.cleaned_data.get('username'), form.cleaned_data.get('password1') user = authenticate(username=username, password=<PASSWORD>) login(self.request, user) return view class CreateFav(LoginRequiredMixin, generic.CreateView): model = Hall fields = ['title'] template_name = 'halls/create_fav.html' success_url = reverse_lazy('dashboard') ################################################### # the funciton below connects/saves a user to the title # hall that the user created, in the admin database ################################################### def form_valid(self, form): form.instance.user = self.request.user super(CreateFav, self).form_valid(form) return redirect('dashboard') class DetailFav(generic.DetailView): model = Hall template_name='halls/detail_fav.html' class UpdateFav(LoginRequiredMixin, generic.UpdateView): model = Hall template_name='halls/update_fav.html' fields = ['title'] success_url = reverse_lazy('dashboard') def get_object(self): hall = super(UpdateFav, self).get_object() if not hall.user == self.request.user: raise Http404 else: return hall class DeleteFav(LoginRequiredMixin, generic.DeleteView): model = Hall template_name='halls/delete_fav.html' success_url = reverse_lazy('dashboard') def get_object(self): hall = super(DeleteFav, self).get_object() if not hall.user == self.request.user: raise Http404 else: return hall <file_sep>from .models import Video,Hall from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm class EditProfileForm(UserChangeForm): class Meta: model = User fields = ('username',) exclude = ('password',) # model based form class VideoForm(forms.ModelForm): class Meta: model = Video fields = ['url'] labels = {'url':'YouTube URL'} class SearchForm(forms.Form): search_term = forms.CharField(max_length=255, label='Search for Videos') <file_sep>"""hallvids URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin, auth from django.contrib.auth import views as auth_views from django.urls import path from halls import views from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('dashboard', views.dashboard, name='dashboard'), # AUTH path('signup', views.SignUp.as_view(),name='signup'), path('login', auth_views.LoginView.as_view(), name='login'), path('logout', auth_views.LogoutView.as_view(), name='logout'), path('edit_profile', views.edit_profile, name='edit_profile'), path('change_password', views.change_password, name='change_password'), # hall favorite video thread path('favoritevideos/create', views.CreateFav.as_view(), name='create_fav'), path('favoritevideos/<int:pk>', views.DetailFav.as_view(), name='detail_fav'), path('favoritevideos/<int:pk>/update', views.UpdateFav.as_view(), name='update_fav'), path('favoritevideos/<int:pk>/delete', views.DeleteFav.as_view(), name='delete_fav'), # Video path('favoritevideos/<int:pk>/addvideo', views.add_video, name='add_video'), path('video/search', views.video_search, name='video_search'), path('video/<int:pk>/delete', views.DeleteVideo.as_view(), name='delete_video'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
e5d45f7db42f2fab13484bc99ac9b39e48c02634
[ "Python" ]
3
Python
goldbossstatus/hallvids_project
3ff5185ffdc3ef562fab9204e1e6b6f9cff654f9
67d65ad9ab5512e5c6884451ebda8db7fd7725a5
refs/heads/master
<repo_name>ccnguyen/table-app<file_sep>/api.py import time import os from flask import Flask from flask_restful import Resource, Api from flask_pymongo import PyMongo from flask import make_response from bson.json_util import dumps MONGO_URL = os.environ.get('MONGO_URL') if not MONGO_URL: MONGO_URL = "mongodb://localhost:27017/rest"; app = Flask(__name__, static_folder='build', static_url_path='/') app.config['MONGO_URI'] = MONGO_URL mongo = PyMongo(app) def output_json(obj, code, headers=None): resp = make_response(dumps(obj), code) resp.headers.extend(headers or {}) return resp DEFAULT_REPRESENTATIONS = {'application/json': output_json} api = Api(app) api.representations = DEFAULT_REPRESENTATIONS @app.route('/') def index(): return app.send_static_file('index.html') @app.route('/api/time') def get_current_time(): return {'time': time.time()} import flask_rest_service.resources<file_sep>/requirements.txt Babel==2.7.0 backports.functools-lru-cache==1.5 backports.os==0.1.1 backports.shutil-get-terminal-size==1.0.0 backports.tempfile==1.0 backports.weakref==1.0.post1 Bottleneck==1.2.1 dj-database-url==0.5.0 Django==3.0.4 django-heroku==0.3.1 Flask==1.1.2 Flask-API==2.0 Flask-PyMongo==2.3.0 Flask-RESTful==0.3.8 flask-sqlalchemy==2.4.1 gunicorn==20.0.4 Jinja2==2.10.1 MarkupSafe==0.23 mysql-connector-python==8.0.19 numpy==1.16.4 pandas==0.24.2 psycopg2==2.8.4 psycopg2-binary==2.8.4 pygame==1.9.6 pyOpenSSL==19.0.0 PyYAML==5.1.1 requests==2.22.0 requests-oauthlib==1.3.0 sqlparse==0.3.1 Werkzeug==0.15.4 aniso8601==0.82 itsdangerous==0.24 pymongo==3.10.1 pytz==2014.4 six==1.10.0
f3b9cb62e8f111c9ab1b8b32142f292ff0fb914c
[ "Python", "Text" ]
2
Python
ccnguyen/table-app
81fc8c08c3ba2dee2c95b9d6d9d01b28c09b3220
7182051926665bcff7ee52c053f356d7eb25da17
refs/heads/master
<repo_name>dayshajones/SQL-bear-organizer-lab-online-web-sp-000<file_sep>/lib/insert.sql INSERT INTO bears (id, name, age, gender, color, temperament, alive) VALUES (1, "Mr.Chocolate", 5, "M", "White", "Happy", "true"), (2, "Rowdy", 4, "F", "Black", "Silly", "true"), (3, "Tabitha", 3, "F", "Brown", "Warm", "true"), (4, "<NAME>", 6, "M", "White", "Strict", "true"), (5, "Melissa", 5, "F", "Black", "Good", "true"), (6, "Grinch", 3, "M", "Green", "Mean", "true"), (7, "Wendy", 5, "F", "White", "Happy", "true"), (8, null, 5, "M", "White", "Agressive", "false");
468bce61746e15d0582c55663a6a70e8c18febf8
[ "SQL" ]
1
SQL
dayshajones/SQL-bear-organizer-lab-online-web-sp-000
dae4cd9049046066cbb403d02e3e0b0e3cdb4bbf
3312faba5694c744bff553975d2d0b7a55bbd2e4
refs/heads/main
<repo_name>Jordan6271/bootcamp-project-week10<file_sep>/noteable/src/Noteable/Note/NewNote.js import React from "react"; import Colour from "./Colour"; import Stamp from "./Stamp"; import toastr from "toastr"; import "toastr/build/toastr.min.css"; import Form from "react-bootstrap/Form"; import Text from "react-bootstrap/FormText"; import Button from "react-bootstrap/Button"; class NewNote extends React.Component { constructor(props) { super(props); this.state = { username: ``, title: ``, description: ``, stamps: Math.floor(Math.random() * 101), stamped: false, stampStyle: Stamp[0], currentTime: ``, id: 2, colour: Colour[0], }; toastr.options = { closeButton: true, debug: false, extendedTimeOut: "1000", hideDuration: "1000", hideEasing: "linear", hideMethod: "slideUp", newestOnTop: false, onclick: null, positionClass: "toast-bottom-full-width", preventDuplicates: true, progressBar: true, showDuration: "300", showEasing: "swing", showMethod: "slideDown", timeOut: "5000", }; } updateTime() { this.setState({ currentTime: `${new Date().toLocaleString()}`, }); } updateId() { const lastNote = this.props.notes.slice(-1)[0]; const lastNoteId = lastNote.id; if (lastNoteId >= this.state.id) { this.setState({ id: lastNoteId + 1 }); } } updateVariables() { this.updateId(); this.updateTime(); } handleColour(event) { const value = event.target.value; switch (value) { case "2": this.setState({ colour: Colour[1], }); break; case "3": this.setState({ colour: Colour[2], }); break; case "4": this.setState({ colour: Colour[3], }); break; case "5": this.setState({ colour: Colour[4], }); break; case "6": this.setState({ colour: Colour[5], }); break; default: this.setState({ colour: Colour[0], }); break; } } handleChange(event) { const newState = {}; newState[event.target.name] = event.target.value; this.setState(newState); if (newState.username !== ``) { document.getElementById(`username-error`).innerHTML = ``; } if (newState.title !== ``) { document.getElementById(`title-error`).innerHTML = ``; } if (newState.description !== ``) { document.getElementById(`description-error`).innerHTML = ``; } this.updateVariables(); } submitHandler(event) { event.preventDefault(); if (this.state.username === ``) { document.getElementById(`username-error`).innerHTML = "You must enter a username!"; } else if (this.state.title === ``) { document.getElementById(`title-error`).innerHTML = "You must enter a title!"; } else if (this.state.description === ``) { document.getElementById(`description-error`).innerHTML = "You must enter a description!"; } else { this.formSubmit(); } } formSubmit() { this.props.onsubmit( this.state.username, this.state.title, this.state.description, this.state.stamps, this.state.stamped, this.state.stampStyle, this.state.currentTime, this.state.id, this.state.colour ); toastr.success(`Note pinned`); this.setState({ username: ``, title: ``, description: ``, currentTime: ``, stamps: Math.floor(Math.random() * 101), stamped: false, stampStyle: Stamp[0], colour: Colour[0], }); } render() { return ( <div className="p-5 mt-5" id="new-note" style={{ fontWeight: "bold", fontSize: "1.25rem", }} > <Form onSubmit={(event) => this.submitHandler(event)} className="p-4" style={{ backgroundColor: "rgba(255,255,255,0.25)", }} > <Form.Group controlId="noteUsername"> <Form.Label>Username:</Form.Label> <Form.Control onChange={(event) => this.handleChange(event)} name="username" type="text" value={this.state.username} /> <span className="error" style={{ color: "#9A0000", }} > <p id="username-error"></p> </span> </Form.Group> <Form.Group controlId="noteTitle"> <Form.Label>Title:</Form.Label> <Form.Control onChange={(event) => this.handleChange(event)} name="title" type="text" value={this.state.title} /> <span className="error" style={{ color: "#9A0000", }} > <p id="title-error"></p> </span> </Form.Group> <Form.Group controlId="noteDescription"> <Form.Label>Description:</Form.Label> <Form.Control onChange={(event) => this.handleChange(event)} name="description" type="text" value={this.state.description} /> <span className="error" style={{ color: "#9A0000", }} > <p id="description-error"></p> </span> </Form.Group> <Form.Group controlId="noteColour"> <Form.Label>Note Colour:</Form.Label> <br /> <select className="form-select" aria-label="Selection of note colours" onChange={(event) => this.handleColour(event)} defaultValue="1" > <option value="1">Yellow</option> <option value="2">Blue</option> <option value="3">Green</option> <option value="4">Orange</option> <option value="5">Pink</option> <option value="6">Purple</option> </select> </Form.Group> <Form.Group controlId="noteStatic"> <Text type="hidden" value={this.state.stamps} /> <Text type="hidden" value={this.state.currentTime} /> <Text type="hidden" value={this.state.id} /> <Text type="hidden" value={this.state.colour} /> </Form.Group> <div className="justify-content-center mx-auto"> <Button onClick={() => this.updateVariables()} variant="danger" type="submit" > Pin </Button> </div> </Form> </div> ); } } export default NewNote; <file_sep>/noteable/src/App.js import "./App.css"; import Corkboard from "./Noteable/Images/corkboard.png"; import Noteable from "./Noteable/Noteable"; function App() { return ( <div className="App" style={{ backgroundImage: `url(${Corkboard})`, fontFamily: "PullMeOut, sans-serif", minHeight: "100vh", }} > <Noteable /> </div> ); } export default App; <file_sep>/README.md # bootcamp-project-week10 <file_sep>/noteable/src/Noteable/Note/Stamp.js import Unstamped from "../Images/unstamped.png"; import Stamped from "../Images/stamped.png"; const Stamp = [Unstamped, Stamped]; export default Stamp;
6a6c35c97ee70615f81c4ac88195668475f20a16
[ "JavaScript", "Markdown" ]
4
JavaScript
Jordan6271/bootcamp-project-week10
0a4d7353f0064fa9f396c277605db06399aba0fe
361e9754557fa91b8a9261df4ce913e30fd5c8d7
refs/heads/master
<repo_name>VioletTape/ArchValidation<file_sep>/ArchValidation_Types/NoStaticUsageChecks/NoStaticExample.cs namespace ArchValidation.NoStaticUsageChecks { /* * Try to add "static" keyword to class/prop/method * to the MyUglyEnterprise class and see what happens */ public class MyUglyEnterprise { public static string Greetings = "Hello world!"; public int Prop { get; set; } private void Foo() { } } /* * But aspect [NoStatic] recognize extension methods * as valid usage of static modificator */ public static class StringExtension { public static bool IsEmpty(this string s) { return true; } } }<file_sep>/UsagesConstraints/InternalForIoC.cs using FluentAssertions; using NUnit.Framework; using PostSharp.Constraints; using PostSharp.Extensibility; using StructureMap; namespace DomainA { public class MyServiceForIoCUsage { public string Name { get; } /* * Applying [Internal] to the constructor, makes it internal within * assembly. Technically it's available for 3rd party elements, that * requires public ctor/method/property, but we don't want to expose it */ [Internal(Severity = SeverityType.Error)] public MyServiceForIoCUsage(string name) { Name = name; } } public class Registry { public Container container; public void Setup() { container = new Container(x => x.For<MyServiceForIoCUsage>() .Use<MyServiceForIoCUsage>() .Ctor<string>() .Is("hey!")); } } [TestFixture] public class Test { [Test] public void CheckInstantiation() { // arrange var registry = new Registry(); // act registry.Setup(); // assert registry.container.GetInstance<MyServiceForIoCUsage>() .Should() .NotBeNull(); } } }<file_sep>/ArchValidation_Types/NHibernate/Aspect/NoExplicitOverride.cs using System; using System.Linq; using System.Reflection; using PostSharp.Constraints; using PostSharp.Extensibility; using PostSharp.Reflection; namespace ArchValidation.NHibernate.Aspect { /* * Checks that virtual property wasn't override in any derrived class. * * There is nuances in implementation: * 1) If use ScalarConstraint it will check overrides only in assembly where * attribute was applied. For instance, it will not catch override in * other projects. * - For the implementation remove Assembly parameter in the ValidationCode * method. * - The second part resides in the project Service. In case of * ScalarConstraint in should not be detected. Make sure that you * uncommented those code snippet. * 2) To make life easier in a sense of discoverability in other projects, * there is Inheritance property setted to Multicast. */ [MulticastAttributeUsage(MulticastTargets.Class | MulticastTargets.Assembly , Inheritance = MulticastInheritance.Multicast)] public class NoExplicitOverride : ReferentialConstraint { public override void ValidateCode(object target, Assembly assembly) { var type = target as Type; if(type == null) return; var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); var virtuals = properties.Where(IsVirtual).Select(p => p.Name).ToList(); var derrivedTypes = ReflectionSearch.GetDerivedTypes(type, ReflectionSearchOptions.IncludeDerivedTypes); foreach (var derrivedType in derrivedTypes) { var propertyInfos = derrivedType.DerivedType .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); var names = propertyInfos.Select(p => p.Name).Intersect(virtuals).Select(n => n).ToList(); if (names.Any()) { var violations = propertyInfos.Where(p => names.Contains(p.Name)).Select(p => p).ToList(); foreach (var vp in violations) { Message.Write(vp // location of violation in code , SeverityType.Error , "vir001" , $"Property {vp.Name} declared in {vp.DeclaringType} should override base property."); } } } } // method extracted for the sake of readability private bool IsVirtual(PropertyInfo property) { return property.GetMethod != null && property.GetMethod.IsVirtual || property.SetMethod != null && property.SetMethod.IsVirtual; } } // for the example with virtual properties to illustrate how // it might looks in production code public class NHibernate { } }<file_sep>/ArchValidation_Types/README.txt Presentation for the code: - https://1drv.ms/p/s!AsVpK9m-ptKRss0euF_ScGK7qwEEJQ Gang of Four patterns with PostSharp: - https://github.com/VioletTape/GoF_PostSharp <file_sep>/DAL/UserRepository.cs using PostSharp.Constraints; using PostSharp.Extensibility; namespace DAL { [InternalImplement] public interface IUserRepository { void GetX(); } /* public class Customer : NHibernate { [NoExplicitOverride] public virtual int Age { get; set; } } */ // public class UserRepository : IUserRepository { // [Internal(Severity = SeverityType.Error)] // public void GetX() { } // } }<file_sep>/ArchValidation_Types/ClassInterfaceExtensionChecks/Aspects/BattleStuff.cs using System; using System.Collections.Generic; using System.Linq; using PostSharp.Aspects; using PostSharp.Extensibility; namespace ArchValidation.ClassInterfaceExtensionChecks.Aspects { [Serializable] [AttributeUsage(AttributeTargets.Class)] [MulticastAttributeUsage(MulticastTargets.Class, Inheritance = MulticastInheritance.Multicast)] public class BattleStuffAttribute : TypeLevelAspect { private readonly List<Type> types; public BattleStuffAttribute() { types = new List<Type> { typeof(IWeapon), typeof(IShield), typeof(IItem) }; } public override bool CompileTimeValidate(Type type) { var notAllowed = type.GetInterfaces() .Except(types) .Select(i => i.Name) .ToList(); if (notAllowed.Any()) { var messageLocation = MessageLocation.Of(type.GetConstructors().First()); var messageText = $"There should be only IWeapon/IShield implementation in the {type.Name} class (was found {string.Join(",", notAllowed)})"; var message = new Message(messageLocation, SeverityType.Error, "f001", messageText, "", "file", null); Message.Write(message); return false; } return base.CompileTimeValidate(type); } } }<file_sep>/ServiceLayer/PostCardUsage.cs using System.IO; using System.Text; using System.Xml.Serialization; using DomainA; using FluentAssertions; using NUnit.Framework; namespace ServiceLayer { public class PostOffice { public string Send(PostCard card) { var serializer = new XmlSerializer(typeof(PostCard)); var stringWriter = new StringWriter(new StringBuilder()); serializer.Serialize(stringWriter, card); stringWriter.Close(); return stringWriter.ToString(); } public PostCard Recieve(string cardData) { var serializer = new XmlSerializer(typeof(PostCard)); var stream = new StringReader(cardData); return (PostCard)serializer.Deserialize(stream); } } [TestFixture] public class SerizalizationTest { [Test] public void CheckSendAndRecieve() { // arrange var postOffice = new PostOffice(); var postCard = new PostCard("Hello CodeEurope!"); // act var message = postOffice.Send(postCard); var card = postOffice.Recieve(message); // assert postCard.Destination.Should() .Be(card.Destination); } } }<file_sep>/DomainB/ServicesA/ServiceLocator.cs using DomainB.Aspects; using DomainB.ServicesA; namespace DomainB.ServicesA { /* * Aspect [ServiceLocatorUsagePolicy] prevent usage of IoC/DI * methods directly in code */ [ServiceLocatorUsagePolicy] public class ServiceLocator { /* * Aspect [ServiceLocatorPolicy] prevent usage of Container directly, * because this is dangerous, and considered as anti-pattern */ [ServiceLocatorPolicy] public static ServiceLocator Container = new ServiceLocator(); public void Add(string typeName) { } public void Get(string typeName) { } } public class DependencyManager { [ServiceLocatorPolicy.Allow] public DependencyManager() { var serviceLocator = ServiceLocator.Container; serviceLocator.Add("ServiceA"); serviceLocator.Add("ServiceB"); serviceLocator.Add("ServiceC"); } } public class MySuperService { public MySuperService() { /* * Uncomment to see [ServiceLocatorPolicy] in action */ // var serviceLocator = ServiceLocator.Container; } [ServiceLocatorPolicy.Allow] public void PrintHello(ServiceLocator serviceLocator) { /* * Uncomment to see [ServiceLocatorPolicy] in action */ // serviceLocator.Get("HelloService"); } } } namespace SomeOtherNamespace { public class MyOtherSuperService { public MyOtherSuperService() { /* * Uncomment to see [ServiceLocatorPolicy] in action * with validation by namespace. */ // var serviceLocator = ServiceLocator.Container; } } }<file_sep>/README.md # ArchValidation Presentation for the code in the root folder. Gang of Four patterns with PostSharp: - https://github.com/VioletTape/GoF_PostSharp <file_sep>/ArchValidation_Types/ClassInterfaceExtensionChecks/Item.cs using ArchValidation.ClassInterfaceExtensionChecks.Aspects; using PostSharp.Patterns.Model; namespace ArchValidation.ClassInterfaceExtensionChecks { public interface IItem { } public interface IPotion : IItem { } public interface IWeapon : IItem { decimal Damage { get; set; } } public interface IShield : IItem { decimal Defence { get; set; } } public interface IWear : IItem { } public class Bow : IWeapon { public decimal Damage { get; set; } } public class Dagger : IWeapon { public decimal Damage { get; set; } } public class Wand : IWeapon { public decimal Damage { get; set; } } public class Sword : IWeapon { public SwordType Type { get; } public Sword(SwordType swordType) { Type = swordType; } public decimal Damage { get; set; } } public class Excalibur : Sword { public Excalibur(SwordType swordType) : base(swordType) { Damage = 9000; } } public enum SwordType { OneHanded, Bastard, TwoHanded } /* * What to do next, if I want to use Shield as Weapon? * - Add non suitable interface (IPotion) */ [BattleStuff] public class CaptAmericasShield : IShield, IWeapon { public CaptAmericasShield() { Damage = 5000; Defence = 9000; } public decimal Defence { get; set; } public decimal Damage { get; set; } } [NotifyPropertyChanged] public class Hero { public IWeapon Weapon { get; set; } public IShield Shield { get; set; } public IWear Protection { get; set; } public string GetStats() { return $"Stats for hero: \n\tWeapon:{Weapon?.Damage}\n\tShield:{Shield?.Defence}\n\tWear:{Protection}"; } } }<file_sep>/DomainB/Aspects/ServiceLocatorPolicy.cs using System; using System.Linq; using System.Reflection; using PostSharp.Constraints; using PostSharp.Extensibility; using PostSharp.Reflection; namespace DomainB.Aspects { /* * Set of validation aspects that prevent usage of IoC/DI as * ServiceLocator anti-pattern. * ServiceLocator can't be passed or called directly outside * allowed places. */ [MulticastAttributeUsage(MulticastTargets.Class, Inheritance = MulticastInheritance.Strict)] public class ServiceLocatorUsagePolicy : ReferentialConstraint { public override void ValidateCode(object target, Assembly assembly) { var targetType = (Type) target; var methodInfos = targetType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); foreach (var method in methodInfos) { var usages = ReflectionSearch.GetMethodsUsingDeclaration(method); foreach (var usage in usages) { var parameterInfos = usage.UsingMethod.GetParameters(); var any = parameterInfos.Any(info => info.ParameterType == targetType); if (any) { Message.Write(usage.UsingMethod, SeverityType.Error, "re001", "Passing ServiceLocator as paramter is prohibited"); } } } } } [MulticastAttributeUsage(MulticastTargets.Field)] public class ServiceLocatorPolicy : ReferentialConstraint { public string TargetNamespace; public override void ValidateCode(object target, Assembly assembly) { var targetType = (FieldInfo) target; var usages = ReflectionSearch.GetMethodsUsingDeclaration(targetType); foreach (var usage in usages) { if (!string.IsNullOrWhiteSpace(TargetNamespace) && !usage.UsingMethod.DeclaringType.Namespace.Contains(TargetNamespace)) continue; if(usage.UsingMethod.DeclaringType == targetType.DeclaringType) continue; if(usage.UsingMethod.GetCustomAttribute<Allow>() != null) continue; Message.Write(usage.UsingMethod, SeverityType.Error, "re001", "Ref: No ServiceLocator anti-pattern in my code!"); } base.ValidateCode(target, assembly); } public class Allow : Attribute { }; } }<file_sep>/ArchValidation_Types/Properties/AssemblyInfo.cs using System.Reflection; using System.Runtime.InteropServices; using ArchValidation.NHibernate.Aspect; using ArchValidation.NoStaticUsageChecks; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ArchValidation_Game")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ArchValidation_Game")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("471cfaf4-426c-4fba-b7d3-1198fe0bedb2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] // with conditional compilation symbols ones can speedup execution. // Aspects can be easily turned on/off #if GATEDIN // It is possible to use * as wildcard or start the pattern string from regex: [assembly: NoStatic(AttributeTargetTypes = "ArchValidation.NoStaticUsageChecks.*")] [assembly: NoExplicitOverride(AttributeTargetTypes = "ArchValidation.NHibernate.Entities.*")] #endif<file_sep>/RC_Domain/Class1.cs using System; using System.Linq; using System.Net.Configuration; using System.Reflection; using PostSharp.Constraints; using PostSharp.Extensibility; using PostSharp.Reflection; using RC_Domain; namespace RC_Domain { [MulticastAttributeUsage(MulticastTargets.Interface, Inheritance = MulticastInheritance.Multicast)] public class NoExplicitInstantiaionPolicy : ReferentialConstraint { public override void ValidateCode(object target, Assembly assembly) { var targetType = (Type) target; var usages = ReflectionSearch.GetDerivedTypes(targetType); foreach (var usage in usages) { var constructorInfos = usage.DerivedType.GetConstructors(BindingFlags.Instance | BindingFlags.Public); foreach (var ctr in constructorInfos) { var illeagalUsage = ReflectionSearch.GetMethodsUsingDeclaration(ctr); foreach (var usageRefs in illeagalUsage) Message.Write(usageRefs.UsingMethod, SeverityType.Error, "re001", "There should be no explicit instantiations for {0}", usageRefs.UsingMethod.DeclaringType); } } base.ValidateCode(target, assembly); } } public class MyService : IMyService { public void Boo() { } } [NoExplicitInstantiaionPolicy] public interface IMyService { void Boo(); } public class MySuperService { public MySuperService() { } public void Foo(MyService myService) { // var service = new MyService(); // uncomment for error myService.Boo(); } public void Foo2(MyService myService) { // var service = new MyService(); // uncomment for error myService.Boo(); } } } <file_sep>/ServiceLayer/Adapter/OrderAdapter.cs namespace ServiceLayer.Adapter { /* * Rule for checking name convention [NamingConvention] is in AssemblyInfo * and applied for all classes in provided namespace */ public class OrderAdapter { } }<file_sep>/ArchValidation_Types/NoStaticUsageChecks/NoStatic.cs using System; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using PostSharp.Aspects; using PostSharp.Extensibility; namespace ArchValidation.NoStaticUsageChecks { /* * This constraint check that public/internal class/property/method * not declared with static keyword. * The only exception is extension methods that requires that * syntax construction. */ [Serializable] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly)] [MulticastAttributeUsage(MulticastTargets.Class, Inheritance = MulticastInheritance.Multicast)] public class NoStatic : TypeLevelAspect { public override bool CompileTimeValidate(Type type) { var isStatic = type.IsAbstract && type.IsSealed; var hasStaticProperties = type .GetProperties(BindingFlags.Static | BindingFlags.Public) .Any(); var methodInfos = type.GetMethods(BindingFlags.Static | BindingFlags.Public); var extensionMethods = methodInfos.Where(m => m.GetCustomAttribute<ExtensionAttribute>() != null) .Select(m => m) .ToList(); var hasStaticMethods = methodInfos.Except(extensionMethods).Any(); if (isStatic && extensionMethods.Any() && !hasStaticMethods && !hasStaticProperties) return false; if (isStatic ||hasStaticProperties ||hasStaticMethods) { var location = MessageLocation.Of(type); var msg = "Looks like you are increasing chaos on a project using static modificator"; Message.Write(location , SeverityType.Error , "f001" , msg); return false; } return base.CompileTimeValidate(type); } } }<file_sep>/ServiceLayer/EstimationCalculator.cs using DomainA; namespace ServiceLayer { public class EstimationCalculator { public EstimationCalculator(IPaymentStrategy paymentStrategy) { paymentStrategy.Calculate(); } } /* * Uncomment following code to see [InternalImplement] constraint * for IPaymentStrategy from DomainA in action. * You should see Error or Warning, depening of severity type provided * for [InternalImplement] */ // public class SomeLocalReimplementation : IPaymentStrategy { // public decimal Calculate() { // return 100; // } // } }<file_sep>/ArchValidation_Types/NHibernate/Entities/Entity.cs namespace ArchValidation.NHibernate.Entities { /* * Consider the following example, when you create class * to represent SQL data with NHibernate. * In this case properties should be virtual and it's * unlikely that someone override those propeties. * * Validation aspect applied on assembly level, so any * type in specific project/namespace will be checked. */ public class Customer : Aspect.NHibernate{ public string Id; public virtual int Age { get; set; } public virtual int MarkA { get; } public virtual int MarkB { set { var a = value; } } public string Name { get; set; } } public class VipCustomer : Customer { /* * Uncomment following code to see [NoExplicitOverride] validation * in action. Attribute applied on assembly level. */ // public override int Age { get; set; } public int MarkC { get; set; } } public class SuperVipCustomer : VipCustomer { /* * Uncomment following code to see [NoExplicitOverride] validation * in action. Attribute applied on assembly level. */ // public override int Age { get; set; } public int MarkC { get; set; } } }<file_sep>/ArchValidation_Types/ClassInterfaceExtensionChecks/ClassInheritance/Item.cs namespace ArchValidation.ClassInheritance { public class Item { } public class Potion : Item { } public class Weapon : Item { public int Damage { get; protected set; } public override string ToString() { return Damage.ToString(); } } public class Shield : Item { public int Armor { get; protected set; } public override string ToString() { return Armor.ToString(); } } public class Wear : Item { public int Protection { get; protected set; } public override string ToString() { return Protection.ToString(); } } public class Bow : Weapon { } public class Dagger : Weapon { } public class Wand : Weapon { } public class Sword : Weapon { public SwordType Type { get; } public Sword(SwordType swordType) { Type = swordType; } } public enum SwordType { OneHanded, Bastard, TwoHanded } public class Excalibur : Sword { public Excalibur(SwordType swordType) : base(swordType) { Damage = 9000; } } /* * What to do next, if I want to use Shield as Weapon? */ public class CaptAmericasShield : Shield { public int Damage { get; } = 300; public CaptAmericasShield() { Armor = 500; } } public class Hero { public Weapon Weapon { get; set; } public Shield Shield { get; set; } public Wear Protection { get; set; } public string GetStats() { return $"Stats for hero: \n\tWeapon:{Weapon}\n\tShield:{Shield}\n\tWear:{Protection}"; } } }<file_sep>/Services/CustomerEx.cs using ArchValidation.NHibernate.Entities; namespace Services { /* * Uncomment property to see [NoExplicitOverride] in action, * if it's declared as ReferentialConstraint. * Attribute applied to the Customer class on assembly level * from the other project - ArchValidation_Types/NHibernate * */ public class CustomerEx : Customer { // public override int Age { get; set; } } } <file_sep>/UsagesConstraints/IPaymentStrategy.cs using PostSharp.Constraints; using PostSharp.Extensibility; namespace DomainA { /* * Following example is about [InternalImplement] * * No one can implement interface in other projects */ // // Payment strategise should be implemented within // the same project, but other project should be able // use interface, without ability to reimplement it. [InternalImplement(Severity = SeverityType.Error)] public interface IPaymentStrategy { decimal Calculate(); } internal class PaymentStrategyA : IPaymentStrategy { public decimal Calculate() { return 0; } } internal class PaymentStrategyB : IPaymentStrategy { public decimal Calculate() { return 0; } } }<file_sep>/DomainB/Aspects/NoExplicitInstantiaionPolicy.cs using System; using System.Reflection; using PostSharp.Aspects; using PostSharp.Constraints; using PostSharp.Extensibility; using PostSharp.Reflection; namespace DomainB.Aspects { /* * Validation aspect prevent direct instantiation of any classes * that was instrumented. Was developed with IoC/DI frameworks in * mind, to force proper usage of IoC/DI. */ [MulticastAttributeUsage(MulticastTargets.Interface , Inheritance = MulticastInheritance.Multicast)] public class NoExplicitInstantiaionPolicy : ReferentialConstraint { public override void ValidateCode(object target, Assembly assembly) { var targetType = (Type)target; var usages = ReflectionSearch.GetDerivedTypes(targetType); foreach (var usage in usages) { var constructorInfos = usage.DerivedType .GetConstructors(BindingFlags.Instance | BindingFlags.Public); foreach (var ctr in constructorInfos) { var illeagalUsage = ReflectionSearch.GetMethodsUsingDeclaration(ctr); foreach (var usageRefs in illeagalUsage) Message.Write(usageRefs.UsingMethod , SeverityType.Error , "re001" , "There should be no explicit instantiations for {0}" , usageRefs.UsingMethod.DeclaringType); } } base.ValidateCode(target, assembly); } } public class MyConstraint : ReferentialConstraint { public override void ValidateCode(object target, Assembly assembly) { base.ValidateCode(target, assembly); } public override bool ValidateConstraint(object target) { return base.ValidateConstraint(target); } } public class TypeLevelConstraint : TypeLevelAspect { public override bool CompileTimeValidate(Type type) { return base.CompileTimeValidate(type); } } }<file_sep>/UsagesConstraints/Serialization.cs using System; using System.IO; using System.Text; using System.Xml.Serialization; using FluentAssertions; using NUnit.Framework; using PostSharp.Constraints; using PostSharp.Extensibility; namespace DomainA { /* * Following example is about [Protected] attribute * * No one can use protected ctor/method * except internal implementation */ [Serializable] public class PostCard { public string Destination { get; set; } public PostCard(string destination) { Destination = destination; } /* * Uncomment, to remove errors of serialization * The Internal keyword wouldn't help to protect ctor */ // [Protected(Severity = SeverityType.Error)] protected PostCard() { } } public class PostOffice { public string Send(PostCard card) { var serializer = new XmlSerializer(typeof(PostCard)); var stringWriter = new StringWriter(new StringBuilder()); serializer.Serialize(stringWriter, card); stringWriter.Close(); return stringWriter.ToString(); } public PostCard Recieve(string cardData) { var serializer = new XmlSerializer(typeof(PostCard)); var stream = new StringReader(cardData); return (PostCard) serializer.Deserialize(stream); } } [TestFixture] public class SerizalizationTest { [Test] public void CheckSendAndRecieve() { // arrange var postOffice = new PostOffice(); var postCard = new PostCard("Hello CodeEurope!"); // act var message = postOffice.Send(postCard); var card = postOffice.Recieve(message); // assert postCard.Destination.Should() .Be(card.Destination); } } }<file_sep>/DomainB/ServicesB/IMyService.cs using DomainB.Aspects; namespace DomainB.ServicesB { /* * Validation aspect [NoExplicitInstantiaionPolicy] checks, * that classes implementing that interface won't be * instantiated explicitly */ [NoExplicitInstantiaionPolicy] public interface IMyService { void Boo(); } public class MyService : IMyService { public void Boo() { } } public class MyConsumingService { public void Foo(MyService myService){ /* * Uncomment folling code to see [NoExplicitInstantiaionPolicy] * in action */ // var service = new MyService(); myService.Boo(); } public void Foo2(MyService myService){ /* * Uncomment folling code to see [NoExplicitInstantiaionPolicy] * in action */ // var service = new MyService(); myService.Boo(); } } }<file_sep>/StandardFeatures/Views/LoginView.cs using DAL; using PostSharp.Constraints; namespace StandardFeatures.Views { // What wildcards are possible: * or regex: // public class LoginView { // public void LoginView22() { // var userRepository = new UserRepository(); // userRepository.GetX(); // } // } // public class IlleagalRepo : IUserRepository { // public void GetX() { // // } // } }<file_sep>/ArchValidation_Types/ClassInterfaceExtensionChecks/StraightForwardTests.cs using FluentAssertions; using NUnit.Framework; namespace ArchValidation.ClassInterfaceExtensionChecks { [TestFixture] public class StraightForwardTests { [Test] public void Test01() { var hero = new Hero {Weapon = new CaptAmericasShield()}; hero.GetStats() .Should() .Be("Stats for hero: \n\tWeapon:5000\n\tShield:\n\tWear:"); } [Test] public void Test02() { var hero = new Hero {Shield = new CaptAmericasShield()}; hero.GetStats() .Should() .Be("Stats for hero: \n\tWeapon:\n\tShield:9000\n\tWear:"); } } }
138b464a4e6581ec445d1e002207b49d7d7d8f61
[ "Markdown", "C#", "Text" ]
25
C#
VioletTape/ArchValidation
7c44fa086cc988d4487dd36fe20493235ace6bca
492bd220c8efde5ce90de1c8c2e59500cbb148a4
refs/heads/master
<repo_name>guyzsarun/DataStructureLab<file_sep>/HW/src/Partition.java public class Partition extends CDLinkedList{ public static void main(String [] args)throws Exception{ CDLinkedList test=new CDLinkedList(); DListIterator dl=new DListIterator(test.header); test.insert(3,dl); while (true){ test.printList(); if (dl.currentNode.nextNode==HEADERVALUE) break; } } }<file_sep>/HW/src/TestStack.java public class TestStack { public static void main(String [] args)throws Exception { StackArray s=new StackArray(); s.push(1); s.push(1); s.push(1); s.push(1); s.push(1); StackArray temp= new StackArray(); int num=s.top(); s.pop(); temp.push(num); while (!s.isEmpty()){ if (temp.top()!=s.top()){ temp.push(s.top()); s.pop(); } else s.pop(); } while (!temp.isEmpty()){ System.out.println(temp.top()); temp.pop(); } } } <file_sep>/week7/src/Pairs.java import java.util.ArrayList; import java.util.HashSet; import java.util.Hashtable; import java.util.Set; import org.junit.internal.ExactComparisonCriteria; public class Pairs { public static ArrayList<Pair> allPairs(int[] a) { ArrayList<Pair> result = new ArrayList<Pair>(); for (int i=0;i<a.length-1;i++) { Pair x = new Pair(); x.first=a[i]; x.second=a[i+1]; result.add(x); } Pair x = new Pair(); x.first=a[a.length-1]; x.second=a[0]; result.add(x); return result; } public static Hashtable<Integer, Integer> allPairs02(int[] a) { Hashtable<Integer, Integer> h = new Hashtable<Integer, Integer>(); for (int i=0;i<a.length-1;i++) { h.put(a[i],a[i+1]); } h.put(a[a.length-1],a[0]); return h; } public static int find(ArrayList<Pair> a, int key) throws Exception { for (int i=0;i<a.size();i++) { if (a.get(i).first==key){ return a.get(i).second; } } throw new Exception(); } public static int find02(Hashtable<Integer, Integer> h, int key) { return h.get(key); } public static void printArrayListPairs(ArrayList<Pair> r) { for (Pair pair : r) { System.out.print("(" + pair.first + ", " + pair.second + "), "); } System.out.println(""); System.out.println(""); } } <file_sep>/HW/src/ListNode.java class ListNode { int data; ListNode nextNode; // Constructors ListNode(int theElement) { this(theElement, null); } ListNode(int theElement, ListNode n) { data = theElement; nextNode = n; } } <file_sep>/HW/src/TestQueue.java public class TestQueue{ public static void main(String [] args)throws Exception{ QueueArray q1=new QueueArray(); QueueArray q2=new QueueArray(); q1.insertLast(1); q1.insertLast(2); // this one q1.insertLast(3); q1.insertLast(4); //this one q1.insertLast(5); q1.insertLast(6); //crossOver(2,3,q1,q2); q1.swap(1, 6); System.out.println("Q1"); while (!q1.isEmpty()){ int x=q1.removeFirst(); System.out.println(x); } // System.out.println("\nQ2"); // while (!q2.isEmpty()){ // int x=q2.removeFirst(); // System.out.println(x); // } } public static void crossOver(int i,int p , QueueArray q1,QueueArray q2)throws Exception{ int size1 = q1.size()-i; int size2= q2.size()-p; for (int a=0;a<i;a++){ q1.insertLast(q1.removeFirst()); } for (int b=0;b<p;b++){ q2.insertLast(q2.removeFirst()); } for (int a=0;a<size1;a++){ q2.insertLast(q1.removeFirst()); } for (int b=0;b<size2;b++){ q1.insertLast(q2.removeFirst()); } } }<file_sep>/week1/src/Carrier.java public class Carrier { private Aircraft[] ac; public Carrier() { ac=new Aircraft[5]; } public Carrier(Aircraft a[]) { ac=new Aircraft[a.length]; for (int i=0;i<a.length;i++) { a[i].setCurrentSpeed(0); this.ac[i]=a[i]; } } public Aircraft[] getCrafts() { return this.ac; } public boolean planeLand(Aircraft p) { for (int i=0; i<this.ac.length; i++) { if (ac[i] == null) { ac[i]=p; p.setCurrentSpeed(0); return true; } } return false; } public boolean planeTakeoff(Aircraft p) { for (int i=0;i<this.ac.length;i++) { if (ac[i]==p) { ac[i]=null; p.setCurrentSpeed(10); return true; } } return false; } public String toString() { String s=""; for (int i=0;i<this.ac.length;i++){ if (ac[i] != null) s=s+"aircraft: speed= "+this.ac[i].getCurrentSpeed()+", maxspeed= "+this.ac[i].getMaxSpeed()+"\n"; } return s; } }
0dd69f694237059aec81555ce470e2bd34b1180b
[ "Java" ]
6
Java
guyzsarun/DataStructureLab
624d1239f50dcb4ebf5ed8f16373a6cd043fa379
abdb29ca1130e0007eb1d4d5bb64bd4cd9d0e41a
refs/heads/master
<file_sep><?php /* declare database connection variable */ define("HOST", "localhost"); define("USER", "root"); define("PASSWORD", ""); define("DATABASE", "angular_php_crud");<file_sep><?php require_once '../app.php'; /*********************************************************************************/ // delete record if (isset($_GET['delete'])) { $id = $_GET['delete']; $conn->query("DELETE FROM `students` WHERE sId = '$id'"); exit(); } /*********************************************************************************/ /*Fetch user update*/ if (isset($_GET['getStudentUpdate'])) { $id = $_GET['getStudentUpdate']; $sql = $conn->query("SELECT * FROM students WHERE sId = '$id' LIMIT 1"); $result = $sql->fetch_assoc(); echo json_encode($result); exit(); } /********************************************************************************/ //update if (isset($_GET['update'])) { $id = (int)$_GET['update']; $postdata = file_get_contents("php://input"); $request = json_decode($postdata); //sanitize $fName = ucwords(strtolower(trim($request->fName))); $lName = ucwords(strtolower(trim($request->lName))); $email = strtolower(trim($request->email)); $conn->query("UPDATE `students` SET `fName`='$fName',`lName`='$lName',`email`='$email' WHERE `sId`='$id'"); exit(); } /****************************************************/ <file_sep><?php require_once '../app.php'; $postdata = file_get_contents("php://input"); if (isset($postdata) && !empty($postdata)) { $request = json_decode($postdata); $token = null; //sanitize $username = $request->username; $password = $request->password; $response = $user->login($username, $password); echo json_encode($response); exit(); }<file_sep><?php require_once '../app.php'; $postdata = file_get_contents("php://input"); if (isset($postdata) && !empty($postdata)) { $request = json_decode($postdata); //sanitize $fName = ucwords(strtolower(trim($request->fName))); $lName = ucwords(strtolower(trim($request->lName))); $email = strtolower(trim($request->email)); $response = $user->newUser($email, $firstname, $surname); echo json_encode($response); } exit();<file_sep><?php echo "This is the Run page"; echo "This is the Run page again"; ?><file_sep><?php class Database{ public $conn; /********************************************************************** */ public function __construct(){ require_once "constant.php"; $this->conn = new mysqli(HOST, USER, PASSWORD, DATABASE); if($this->conn) return $this->conn; else return "DATABASE CONNECTION FAILED"; } /*********************************************************************** */ }//END CLASS // $db = new Database(); // if(!$db->conn->connect_error) // echo "connected"; // else die($db->conn->connect_error);<file_sep><?php require_once '../app.php'; // RETRIEVE ALL STUDENTS IN THE DATABASE $sql = "SELECT * FROM students"; $students = array(); if ($result = $conn->query($sql)) { while ($row = $result->fetch_assoc()) { $students[] = $row; } echo json_encode($students); }else{ http_response_code(404); } exit();<file_sep><?php require_once "db_connect.php"; class User extends Database { public function __construct(){ parent::__construct(); } public function login($email, $password) { $queryLog = $this->conn->query("SELECT * FROM students WHERE email = '$username' LIMIT 1"); $numRow = $queryLog->num_rows; if ($numRow > 0 ) { $row = $queryLog->fetch_assoc(); if ($row['password'] == $password) { return ( array( 'status' => 'OK', 'message' => 'successful login', 'token' => md5($username . time()), 'email' => $username )); } else{ // http_response_code(401); echo json_encode( array( 'status' => 'ERROR', 'message' => 'Login failed' )); } } else{ echo json_encode( array( 'status' => 'ERRORUSER', 'message' => 'User does not exist' )); } } /*----------------------------------------------------------------------*/ public function newUser($email, $firstname, $surname){ //store if (!empty($email, $firstname, $surname)) { $conn->query("INSERT INTO `students`(`fName`, `lName`, `email`) VALUES ('$firstname', '$surname','$email')"); return array( 'status' => 'OK', 'code' => 200, 'message' => 'User succefully created', 'userEmail' => $email ); }else{ return array( 'status' => 'ERROR', 'code' => 401, 'message' => 'User creation failed' ); } } /******************************************************************************************************** */ }//end User class <file_sep><?php require_once 'cores/config.php'; require_once 'cores/user.php' $user = new User();
20968d23dc932fa155de525d8e0efccc01b11530
[ "PHP" ]
9
PHP
ndundecode/mhdmiddleone
2bbcaed9c0fa810a7a6cf99d4cafe1a297db860b
8db87d6a8893cdc5f1b677cb0510218f2c9dfe8c
refs/heads/master
<repo_name>Kapranov/dice-roller<file_sep>/app/components/roll-dice.js /* global Materialize */ import Component from '@ember/component'; import { get } from '@ember/object'; export default Component.extend({ rollName: '', numberOfDice: 1, numberOfSides: 6, didRender() { Materialize.updateTextFields(); }, actions: { triggerRoll() { // alert(`Rolling ${this.numberOfDice}D${this.numberOfSides} as "${this.rollName}"`); get(this, 'roll')(this.rollName, this.numberOfDice, this.numberOfSides); // return true; } } }); <file_sep>/run.sh #!/usr/bin/env bash # install npm # npm cache clear # npm cache verify # npm i -g npm@latest # To turn off npm audit when installing a single package, use the --no-audit flag: # npm install example-package-name --no-audit npm set audit false # npm set audit true clear npm cache verify npm cache clean --force sleep 10s # rm -f -r ~/.npm # rm -f -r node_modules package-lock.json # 5 actual logging methods, ordered and available as: npm install --loglevel=error # npm install --loglevel=warn # npm install --loglevel=info # npm install --loglevel=debug # npm install --loglevel=trace sleep 10s # bower install # disable Chrome or Firefox for npm test # edit file testem.js <file_sep>/README.md # DiceRoller ### Testing ![testing](/ember_test.png "ember test") ## Install PhantomJS ```sh npm cache clean --force PHANTOM_JS="phantomjs-2.1.1-linux-x86_64" cd /tmp wget https://bitbucket.org/ariya/phantomjs/downloads/$PHANTOM_JS.tar.bz2 tar -xvjf $PHANTOM_JS.tar.bz2 mv $PHANTOM_JS /usr/local/share ln -s /usr/local/share/$PHANTOM_JS/bin/phantomjs /usr/local/bin phantomjs --version ``` ### May 2018 by <NAME> [1]: https://github.com/sazzer/dice-roller [2]: https://github.com/YanaNeronskaya/dice-roller [3]: https://www.sitepoint.com/ember-js-perfect-framework-web-applications/ [4]: https://habr.com/company/ruvds/blog/341076/ [5]: https://github.com/broerse/ember-cli-blog [6]: https://bloggr.exmer.com/posts [7]: https://medium.com/peep-stack/building-a-performant-real-time-web-app-with-ember-fastboot-and-phoenix-part-4-93118e278c68 [8]: https://www.emberscreencasts.com/ [9]: https://www.emberscreencasts.com/posts/175-shopping-cart-part-2-persistence-with-localstorage [10]: http://ideabuster.jayantbhawal.in/getting-started-with-ember-js-2-firebase-materialize-css/ [11]: https://emberigniter.com/send-closure-actions-up-data-owner/ [12]: https://github.com/emberjs/rfcs/blob/master/text/0050-improved-actions.md [13]: https://github.com/DockYard/ember-route-action-helper
a866458967f7c0a3168dd020ca367febfc864447
[ "JavaScript", "Markdown", "Shell" ]
3
JavaScript
Kapranov/dice-roller
19895f69e0f706b772daec69c88d433aa675c98d
72d7132a1bffb8bfe2d328a637efb6c8d6841d43
refs/heads/master
<file_sep># Generated by Django 2.1.2 on 2018-10-24 19:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('card', '0006_auto_20181025_0107'), ] operations = [ migrations.AlterField( model_name='category', name='name', field=models.CharField(max_length=100, verbose_name='Название'), ), ] <file_sep>from django.contrib import admin from .models import * class BranchInline(admin.StackedInline): model = Branch extra = 1 class ContactInline(admin.StackedInline): model = Contact extra = 1 class CourseAdmin(admin.ModelAdmin): inlines = [BranchInline, ContactInline, ] admin.site.register(Course, CourseAdmin) admin.site.register(Category) <file_sep>from rest_framework import generics from .serializers import * from .models import * class CourseViewSet(generics.ListCreateAPIView): queryset = Course.objects.all() serializer_class = CourseSerializer def perform_create(self, serializer): serializer.save() class CourseDetailViewSet(generics.RetrieveUpdateDestroyAPIView): queryset = Course.objects.all() serializer_class = CourseSerializer class CategoryViewSet(generics.ListCreateAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer <file_sep>Django==2.1.2 django-extensions==2.1.3 djangorestframework==3.8.2 gunicorn==19.9.0 pkg-resources==0.0.0 psycopg2==2.7.5 python-decouple==3.1 pytz==2018.5 six==1.11.0 <file_sep># Generated by Django 2.1.2 on 2018-10-24 09:32 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('card', '0003_auto_20181024_1514'), ] operations = [ migrations.AlterModelOptions( name='branch', options={'verbose_name': 'Географические данные', 'verbose_name_plural': 'Географические данные'}, ), migrations.AlterModelOptions( name='category', options={'verbose_name': 'Категория', 'verbose_name_plural': 'Категории'}, ), migrations.AlterModelOptions( name='contact', options={'verbose_name': 'Контактные данные', 'verbose_name_plural': 'Контактные данные'}, ), migrations.AlterModelOptions( name='course', options={'verbose_name': 'Курс', 'verbose_name_plural': 'Курсы'}, ), ] <file_sep># Courses In order for the project to function, you must install the programs installed in the file requirements.txt. To install them, enter the following command in the terminal: pip install -r requirements.txt To understand how requests work, documentation is needed. Documentation for the project is located by reference: https://api684.docs.apiary.io/# <file_sep># Generated by Django 2.1.2 on 2018-10-24 19:07 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('card', '0005_auto_20181024_1604'), ] operations = [ migrations.RemoveField( model_name='category', name='course', ), migrations.AddField( model_name='course', name='category', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='courses', to='card.Category', verbose_name='Категория'), preserve_default=False, ), migrations.AlterField( model_name='category', name='name', field=models.IntegerField(choices=[(1, 'Языковые курсы'), (2, 'Танцевальные курсы'), (3, 'Вокальные курсы'), (4, 'Курсы ораторского искусства')], default=1, verbose_name='Название'), ), migrations.AlterField( model_name='contact', name='type', field=models.IntegerField(choices=[(1, 'Телефон'), (2, 'Facebook'), (3, 'e-mail')], default=1, verbose_name='Варианты'), ), ] <file_sep># Generated by Django 2.1.2 on 2018-10-24 10:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('card', '0004_auto_20181024_1532'), ] operations = [ migrations.AlterField( model_name='branch', name='address', field=models.CharField(max_length=100, verbose_name='Адрес'), ), migrations.AlterField( model_name='branch', name='latitude', field=models.CharField(max_length=100, verbose_name='Ширина'), ), migrations.AlterField( model_name='branch', name='longitude', field=models.CharField(max_length=100, verbose_name='Долгота'), ), migrations.AlterField( model_name='category', name='course', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='categories', to='card.Course'), ), migrations.AlterField( model_name='category', name='name', field=models.CharField(max_length=100, verbose_name='Название'), ), migrations.AlterField( model_name='contact', name='type', field=models.IntegerField(choices=[(1, 'PHONE'), (2, 'FACEBOOK'), (3, 'EMAIL')], default=1, verbose_name='Варианты'), ), migrations.AlterField( model_name='contact', name='value', field=models.CharField(max_length=100, verbose_name='Значение'), ), migrations.AlterField( model_name='course', name='description', field=models.CharField(max_length=100, verbose_name='Описание'), ), migrations.AlterField( model_name='course', name='logo', field=models.CharField(max_length=100, verbose_name='Логотип'), ), migrations.AlterField( model_name='course', name='name', field=models.CharField(max_length=100, verbose_name='Название'), ), ] <file_sep># Generated by Django 2.1.2 on 2018-10-12 17:43 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('card', '0001_initial'), ] operations = [ migrations.RenameField( model_name='branch', old_name='branch', new_name='course', ), migrations.RenameField( model_name='contact', old_name='contact', new_name='course', ), ] <file_sep>from django.test import TestCase from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status from .models import * # tests for all of project # write comments for reviewer # write : python manage.py test class ModelsTestCase(TestCase): def setUp(self): self.course_name = 'english courses' self.course = Course(name=self.course_name,) self.category_name = 'language courses' self.category = Category(name=self.category_name) def test_model_create_category(self): old_count = Category.objects.count() self.category.save() new_count = Category.objects.count() self.assertNotEqual(old_count, new_count) def test_model_create_course(self): old_count = Course.objects.count() self.course.save() new_count = Course.objects.count() self.assertNotEqual(old_count, new_count) def test_model_readable_representation(self): self.assertEqual(str(self.course), self.course_name) self.assertEqual(str(self.category), self.category_name) class ViewsTestCase(TestCase): def setUp(self): self.client = APIClient() self.courses_data = { "name": "Мелодия", "description": "Курсы по изучению такта и музыки", "category":'', "logo": "Music", "contacts": [ { "type": 1, "value": "0702584685" } ], "branches": [ { "latitude": "741258963", "longitude": "987456321", "address": "г.Бишкек пр.Чуй 34" } ] } self.category_data = { "name": "Курсы рисования", "imgpath": "/pictures/2.jpg" } self.response_course = self.client.post( reverse('create'), self.courses_data, ) self.response_category = self.client.post( reverse('category'), self.category_data, ) def test_api_create_course(self): self.assertEqual(self.response_course.status_code, status.HTTP_201_CREATED) def test_api_create_category(self): self.assertEqual(self.response_category.status_code, status.HTTP_201_CREATED) def test_api_get_course(self): try: course = Course.objects.get(id=1) response = self.client.get( '/courses/', kwargs={'pk': course.id} ) except Course.DoesNotExist: return 'Course does not exist' self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertContains(response, course) def test_api_get_category(self): try: category = Category.objects.get(id=1) response = self.client.get( '/category/', kwargs={'pk': category.id} ) except Category.DoesNotExist: return 'Category does not exist' self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertContains(response, category)
80d29790a48a1b299dc1840924e97bb42a359cbb
[ "Markdown", "Python", "Text" ]
10
Python
Mendybaeva/Courses
5085ea9295f26b43ce82987428dd46a592f15c81
15005c500a6681d1d7a35a22592be1814d533dbb
refs/heads/master
<file_sep>#!/bin/bash RES=$1 function gdrive_download () { CONFIRM=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate "https://docs.google.com/uc?export=download&id=$1" -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p') wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$CONFIRM&id=$1" -O $2 rm -rf /tmp/cookies.txt } case ${RES} in '64') GDRIVE_ID=1UVY767XNw9tO5fBzbYwo2wuQxDmk4JRo TAR_FILE=./datasets/64x64.tar ;; '32') GDRIVE_ID=1ERud8ZBBRItTAh8co7GVZKRPCcoFxoHI TAR_FILE=./datasets/32x32.tar ;; esac mkdir -p ./datasets gdrive_download $GDRIVE_ID $TAR_FILE tar -xvf $TAR_FILE -C ./datasets/ rm $TAR_FILE <file_sep>import torch import numpy as np import skimage device = torch.device("cuda" if torch.cuda.is_available() else "cpu") c1 = np.array([1,1,0]) c2 = np.array([0,0,1]) def plot_input(data, filename): skimage.io.imsave(filename, data,check_contrastbool=False) def plot_img(data, filename): data = (data - data.min()) / (data.max() - data.min()) x = data.shape[0] y = data.shape[1] img = np.zeros([x,y,3]) for i in range(x): for j in range(y): img[i,j] = (1-data[i,j])*c1+data[i,j]*c2 skimage.io.imsave(filename, img,check_contrastbool=False) def show_hist(axis): print ('real data:') print (np.histogram(output[:,axis].contiguous().view(-1).cpu().numpy()) ) print ('predict data:') print (np.histogram(output_bak[:,axis].contiguous().view(-1).cpu().detach().numpy()) ) u_max = np.zeros(5) u_min = np.zeros(5) u_min[0] = -400 u_max[0] = 500 u_min[1] = -50 u_max[1] = 50 u_min[2] = -1 u_max[2] = 5 u_min[3] = -0.5 u_max[3] = 1 u_min[4] = -0.5 u_max[4] = 0.5 def plot_img_notnorm(data, filename, axis): # data = (data - data.min()) / (data.max() - data.min()) data = (data - u_min[axis]) / (u_max[axis]- u_min[axis]) data[data>1] = 1 data[data<0] = 0 x = data.shape[0] y = data.shape[1] img = np.zeros([x,y,3]) for i in range(x): for j in range(y): # img[i,j] = (1-data[i,j])*c1+data[i,j]*c2 img[i,j] = data[i,j]*255 skimage.io.imsave(filename, img,check_contrastbool=False) # input[sample] def get_testsample(model ,dirr, data, ref): sample_num = 15 num_label = np.arange(0, data.shape[0]) np.random.shuffle(num_label) sample = num_label[:sample_num] input = torch.from_numpy(data[sample]).to(device) output = model(input) for num, i in enumerate(sample): plot_input(1-input[num,0].cpu().detach().numpy(),f'{dirr}/{i}-input.jpg') plot_img_notnorm(output[num,0].cpu().detach().numpy(),f'{dirr}/{i}-ux-pre.jpg',0) plot_img_notnorm(output[num,1].cpu().detach().numpy(),f'{dirr}/{i}-uy-pre.jpg',1) plot_img_notnorm(ref[i,0].cpu().detach().numpy(),f'{dirr}/{i}-ux-ref.jpg',0) plot_img_notnorm(ref[i,1].cpu().detach().numpy(),f'{dirr}/{i}-uy-ref.jpg',1) def testsample(modelname, dirr): model = torch.load(modelname) data = np.loadtxt("data/rho20x40_SIMP_Edge.txt", dtype=np.float32) # [bs, 1, 20, 40] data = data.reshape(-1,1,40,20).transpose([0,1,3,2]) data_u = np.loadtxt("data/dis20x40_SIMP_Edge.txt", dtype=np.float32) data_s = np.loadtxt("data/stress20x40_SIMP_Edge.txt", dtype=np.float32) ref_u0 = torch.from_numpy(data_u).unsqueeze(1).to(device) ref_uy = ref_u0[:,:,range(1,1722,2)] ref_ux = ref_u0[:,:,range(0,1722,2)] ref_s0 = torch.from_numpy(data_s).unsqueeze(1).to(device) ref_sx = ref_s0[:,:,range(0,2583,3)] ref_sy = ref_s0[:,:,range(1,2583,3)] ref_sxy = ref_s0[:,:,range(2,2583,3)] # [bs, 5, 21, 41] ref = torch.cat([ref_ux, ref_uy, ref_sx, ref_sy, ref_sxy],1).view(-1,5,41,21).permute(0,1,3,2) sample_num = 15 num_label = np.arange(0, data.shape[0]) np.random.shuffle(num_label) sample = num_label[:sample_num] input = torch.from_numpy(data[sample]).to(device) # input = torch.from_numpy(data).to(device) output = model(input) for num, i in enumerate(sample): plot_input(1-input[num,0].cpu().detach().numpy(),f'{dirr}/{i}-input.jpg') plot_img_notnorm(output[num,0].cpu().detach().numpy(),f'{dirr}/{i}-ux-pre.jpg',0) plot_img_notnorm(output[num,1].cpu().detach().numpy(),f'{dirr}/{i}-uy-pre.jpg',1) plot_img_notnorm(ref[i,0].cpu().detach().numpy(),f'{dirr}/{i}-ux-ref.jpg',0) plot_img_notnorm(ref[i,1].cpu().detach().numpy(),f'{dirr}/{i}-uy-ref.jpg',1) # # dirr = "result_img_new" # for i in sample: # plot_input(1-input[i,0].cpu().detach().numpy(),f'{dirr}/{i}-input.jpg') # plot_img_notnorm(output[i,0].cpu().detach().numpy(),f'{dirr}/{i}-ux-pre.jpg',0) # plot_img_notnorm(output[i,1].cpu().detach().numpy(),f'{dirr}/{i}-uy-pre.jpg',1) # # plot_img(output[i,1].cpu().detach().numpy(),f'{dirr}/{i}-uy-pre.jpg') # # plot_img_notnorm(output[i,2].cpu().detach().numpy(),f'{dirr}/{i}-sx-pre.jpg',2) # # plot_img_notnorm(output[i,3].cpu().detach().numpy(),f'{dirr}/{i}-sy-pre.jpg',3) # # plot_img_notnorm(output[i,4].cpu().detach().numpy(),f'{dirr}/{i}-sxy-pre.jpg',4) # plot_img_notnorm(ref[i,0].cpu().detach().numpy(),f'{dirr}/{i}-ux-ref.jpg',0) # plot_img_notnorm(ref[i,1].cpu().detach().numpy(),f'{dirr}/{i}-uy-ref.jpg',1) # # plot_img(ref[i,1].cpu().detach().numpy(),f'{dirr}/{i}-uy-ref.jpg') # # plot_img_notnorm(ref[i,2].cpu().detach().numpy(),f'{dirr}/{i}-sx-ref.jpg',2) # # plot_img_notnorm(ref[i,3].cpu().detach().numpy(),f'{dirr}/{i}-sy-ref.jpg',3) # # plot_img_notnorm(ref[i,4].cpu().detach().numpy(),f'{dirr}/{i}-sxy-ref.jpg',4) if __name__ == '__main__': modelname = 'experiments/codec/mixed_residual/debug/grf_kle512_ntrain6007_run1_bs64_lr0.001_epochs30000/checkpoints/model_epoch30000.pth' dirr = "result_img_new" testsample(modelname, dirr)<file_sep>""" Darcy flow problem 8 cases... primal/mixed + fc/conv + variational/residual """ import torch import torch.autograd as ag import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt import numpy as np plt.switch_backend('agg') def grad(outputs, inputs): return ag.grad(outputs, inputs, grad_outputs=torch.ones_like(outputs), create_graph=True) def bilinear_interpolate_torch(im, x, y): # https://gist.github.com/peteflorence/a1da2c759ca1ac2b74af9a83f69ce20e if torch.cuda.is_available(): dtype = torch.cuda.FloatTensor dtype_long = torch.cuda.LongTensor else: dtype = torch.FloatTensor dtype_long = torch.LongTensor x0 = torch.floor(x).type(dtype_long) x1 = x0 + 1 y0 = torch.floor(y).type(dtype_long) y1 = y0 + 1 x0 = torch.clamp(x0, 0, im.shape[1]-1) x1 = torch.clamp(x1, 0, im.shape[1]-1) y0 = torch.clamp(y0, 0, im.shape[0]-1) y1 = torch.clamp(y1, 0, im.shape[0]-1) Ia = im[ y0, x0 ][0] Ib = im[ y1, x0 ][0] Ic = im[ y0, x1 ][0] Id = im[ y1, x1 ][0] wa = (x1.type(dtype)-x) * (y1.type(dtype)-y) wb = (x1.type(dtype)-x) * (y-y0.type(dtype)) wc = (x-x0.type(dtype)) * (y1.type(dtype)-y) wd = (x-x0.type(dtype)) * (y-y0.type(dtype)) return torch.t((torch.t(Ia)*wa)) + torch.t(torch.t(Ib)*wb) \ + torch.t(torch.t(Ic)*wc) + torch.t(torch.t(Id)*wd) def primal_residual_fc(model, x, K_grad_ver, K_grad_hor, K, verbose=False): """Computes the residules of satisifying PDE at x Permeability is also provided: K First assume x is on grid Args: model (Module): u = f(x) pressure network, input is spatial coordinate x (Tensor): (N, 2) spatial input x. could be off-grid, vary very pass grad_K (Tensor): estimated gradient field verbose (bool): If True, print info Returns: residual: (N, 1) """ assert len(K_grad_ver) == len(x) x.requires_grad = True u = model(x) # grad outputs a tuple: (N, 2) u_x = grad(u, x)[0] div1 = K_grad_ver * u_x[:, 0] + K * grad(u_x[:, 0], x)[0][:, 0] div2 = K_grad_hor * u_x[:, 1] + K * grad(u_x[:, 1], x)[0][:, 1] div = div1 + div2 if verbose: print(div.detach().mean(), div.detach().max(), div.detach().min()) return (div ** 2).mean() def neumann_boundary(model, x): # bug: u_y! NOT u_x x.requires_grad = True u = model(x) u_ver = grad(u, x)[0][:, 0] return (u_ver ** 2).mean() def neumann_boundary_mixed(model, x): # x.requires_grad = True y = model(x) tau_ver = y[:, 1] return (tau_ver ** 2).mean() def primal_variational_fc(model, x, K, verbose=False): """Evaulate energy functional. Simple MC. Evaluate on [1:-1, 1:-1] of grid Args: x (Tensor): colloc points on interior of grid (63 ** 2, 2) """ x.requires_grad = True u = model(x) u_x = grad(u, x)[0] u_x_squared = (u_x ** 2).sum(1) energy = (0.5 * K * u_x_squared).mean() if verbose: print(f'energy: {energy:.6f}') return energy def mixed_residual_fc(model, x, K, verbose=False, rand_colloc=False, fig_dir=None): """ Args: x: (N, 2) K: (N, 1) """ x.requires_grad = True # (N, 3) y = model(x) u = y[:, 0] # (N, 2) tau = y[:, [1, 2]] # (N, 2) u_x = grad(u, x)[0] grad_tau_ver = grad(y[:, 1], x)[0][:, 0] grad_tau_hor = grad(y[:, 2], x)[0][:, 1] if rand_colloc: K = bilinear_interpolate_torch(K.unsqueeze(-1), x[:, [1]], x[:, [0]]) K = K.t() # print(f'K interp: {K.shape}') # plt.imshow(K[0].detach().cpu().numpy().reshape(65, 65)) # plt.savefig(fig_dir+'/Kinterp.png') # plt.close() loss_constitutive = ((K * u_x + tau) ** 2).mean() loss_continuity = ((grad_tau_ver + grad_tau_hor) ** 2).mean() return loss_constitutive + loss_continuity """ ConvNet ============================================ """ def energy_functional_exp(input, output, sobel_filter): r""" sigma = -exp(K * u) * grad(u) V(u, K) = \int 0.5 * exp(K*u) * |grad(u)|^2 dx """ grad_h = sobel_filter.grad_h(output) grad_v = sobel_filter.grad_v(output) return (0.5 * torch.exp(input * output) * (grad_h ** 2 + grad_v ** 2)).mean() def cc2_fe(input, output,device): E = 1.0 nu = 0.3 # C0np = np.array() C0 = E/(1-nu**2)*torch.Tensor([[1,nu,0],[nu,1,0],[0,0,(1-nu)/2]]).to(device) pp = input.contiguous().view(input.shape[0], -1, 1, 1).to(device) # pp = input.permute(0,1,3,2).contiguous().view(input.shape[0], -1, 1, 1).to(device) C = pp**3*C0 ux = output[:,[0]] uy = output[:,[1]] unfold = nn.Unfold(kernel_size=(2, 2)) # [bs, 4, w*h] uex = unfold(ux) uey = unfold(uy) ue_not = torch.cat([uex, uey], 1).permute([0,2,1]) ue = ue_not[:,:,[0,4,1,5,3,7,2,6]].unsqueeze(3) Bxy=np.zeros([2,3,8],dtype=np.float32) Bxy[0,:,:]=np.array([ [0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, -1, 0, 1, 0, -1], [1, 0, -1, 0, 1, 0, -1, 0] ]) Bxy[1,:,:]=np.array([ [1, 0, -1, 0, 1, 0, -1, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, -1, 0, 1, 0, -1] ]) Bxy = torch.from_numpy(Bxy).to(device) S_x = torch.matmul(C, torch.matmul(Bxy[0,:,:],ue)) S_y = torch.matmul(C, torch.matmul(Bxy[1,:,:],ue)) return S_x.shape def cc1_new(input, output, device): E=1 nu=0.3 k=np.array([1/2-nu/6,1/8+nu/8,-1/4-nu/12,-1/8+3*nu/8,-1/4+nu/12,-1/8-nu/8,nu/6,1/8-3*nu/8]) KE = E/(1-nu**2)*np.array([ [k[0], k[1], k[2], k[3], k[4], k[5], k[6], k[7]], [k[1], k[0], k[7], k[6], k[5], k[4], k[3], k[2]], [k[2], k[7], k[0], k[5], k[6], k[3], k[4], k[1]], [k[3], k[6], k[5], k[0], k[7], k[2], k[1], k[4]], [k[4], k[5], k[6], k[7], k[0], k[1], k[2], k[3]], [k[5], k[4], k[3], k[2], k[1], k[0], k[7], k[6]], [k[6], k[3], k[4], k[1], k[2], k[7], k[0], k[5]], [k[7], k[2], k[1], k[4], k[3], k[6], k[5], k[0]] ]) # KE 8x8 KE = np.array(KE, dtype=np.float32) Ke = torch.from_numpy(KE).to(device) pp = input.contiguous().view(input.shape[0], -1, 1, 1).to(device) # K [bs, 800, 8, 8] K = pp**3*Ke # ??? # output[:,:,:,0] = 0 ux = output[:,[0]] uy = output[:,[1]] unfold = nn.Unfold(kernel_size=(2, 2)) # [bs, 4, w*h] uex = unfold(ux) uey = unfold(uy) ue_not = torch.cat([uex, uey], 1).permute([0,2,1]) ue = ue_not[:,:,[0,4,1,5,3,7,2,6]].unsqueeze(3) # KU KU = torch.matmul(K, ue) tku = KU.permute([0,2,1,3]).contiguous().view(-1,8,20,40) result = torch.zeros([ue.shape[0],2,21,41]).to(device) result[:,:,:20,:40] = tku[:,[0,1],:,:] result[:,:,:20,1:] += tku[:,[2,3],:,:] result[:,:,1:,:40] += tku[:,[6,7],:,:] result[:,:,1:,1:] += tku[:,[4,5],:,:] F = torch.zeros([ue.shape[0],2,21,41]).to(device) F[:,0,:,-1] = 1 F[:,0,0,-1] = 0.5 F[:,0,-1,-1] = 0.5 return ((result[:,:,:,1:]-F[:,:,:,1:])**2).sum([1,2,3]).mean() def bc_new(output): ux = output[:, [0]] uy = output[:, [1]] lu = ux[:,:,:,0]**2 + uy[:,:,:,0]**2 return lu.sum([-1]).mean() def cc1(input, output, output_post, sobel_filter, device): E = 1.0 nu = 0.3 # C0np = np.array() C0 = E/(1-nu**2)*torch.Tensor([[1,nu,0],[nu,1,0],[0,0,(1-nu)/2]]).to(device) pp = input.contiguous().view(input.shape[0], -1, 1, 1).to(device) # pp = input.permute(0,1,3,2).contiguous().view(input.shape[0], -1, 1, 1).to(device) C = pp**3*C0 # duxdx = sobel_filter.grad_h(output[:, [0]]) # duxdy = sobel_filter.grad_v(output[:, [0]]) # duydx = sobel_filter.grad_h(output[:, [1]]) # duydy = sobel_filter.grad_v(output[:, [1]]) # d1 = duxdx # d2 = duydy # d3 = duxdy+duydx # du = torch.cat([d1,d2,d3],1) # du_post = du.view(du.shape[0],3,-1,1).permute(0,2,1,3) B=np.zeros([4,3,8],dtype=np.float32) B[0,:,:]=np.array([ [-1, 0, 1, 0, 0, 0, 0, 0], [0, -1, 0, 0, 0, 0, 0, 1], [-1, -1, 0, 1, 0, 0, 1, 0] ]) B[1,:,:]=np.array([ [-1, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, -1, 0, 1, 0, 0], [0, -1, -1, 1, 1, 0, 0, 0] ]) B[2,:,:]=np.array([ [0, 0, 0, 0, 1, 0, -1, 0], [0, 0, 0, -1, 0, 1, 0, 0], [0, 0, -1, 0, 1, 1, 0, -1] ]) B[3,:,:]=np.array([ [0, 0, 0, 0, 1, 0, -1, 0], [0, -1, 0, 0, 0, 0, 0, 1], [-1, 0, 0, 0, 0, 1, 1, -1] ]) B = torch.from_numpy(B).to(device) B0 = torch.Tensor([[-0.5,0,-0.5],[0,-0.5,-0.5],[0.5,0,-0.5],\ [0,-0.5,0.5],[0.5,0,0.5] ,[0,0.5,0.5],[-0.5,0,0.5],[0,-0.5,-0.5]]).to(device) B0T = B0.transpose(0,1) ux = output[:,[0]] uy = output[:,[1]] k1 = torch.FloatTensor( np.array([[[[-0.5,0.5],[-0.5,0.5]]]]) ).to(device) k2 = torch.FloatTensor( np.array([[[[-0.5,-0.5],[-0.5,0.5]]]]) ).to(device) k31 = torch.FloatTensor( np.array([[[[-0.5,-0.5],[0.5,0.5]]]]) ).to(device) k32 = torch.FloatTensor( np.array([[[[-0.5,0.5],[-0.5,0.5]]]]) ).to(device) ux1 = F.conv2d(ux, k1, stride=1, padding=0, bias=None) uy1 = F.conv2d(uy, k2, stride=1, padding=0, bias=None) ux2 = F.conv2d(ux, k31, stride=1, padding=0, bias=None) uy2 = F.conv2d(uy, k32, stride=1, padding=0, bias=None) utest = torch.cat([ux1, uy1, ux2+uy2], 1) unfold = nn.Unfold(kernel_size=(2, 2)) # [bs, 4, w*h] uex = unfold(ux) uey = unfold(uy) ue_not = torch.cat([uex, uey], 1).permute([0,2,1]) ue = ue_not[:,:,[0,4,1,5,3,7,2,6]].unsqueeze(3) # sig = output_post[:, [2,3,4]] # sig_post = sig.view(sig.shape[0],3,-1,1).permute(0,2,1,3) du0 = torch.matmul(C, torch.matmul(B[0,:,:],ue)) du1 = torch.matmul(C, torch.matmul(B[1,:,:],ue)) du2 = torch.matmul(C, torch.matmul(B[2,:,:],ue)) du3 = torch.matmul(C, torch.matmul(B[3,:,:],ue)) du0t = du0.permute([0,2,1,3]).contiguous().view(-1,3,20,40) du1t = du1.permute([0,2,1,3]).contiguous().view(-1,3,20,40) du2t = du2.permute([0,2,1,3]).contiguous().view(-1,3,20,40) du3t = du3.permute([0,2,1,3]).contiguous().view(-1,3,20,40) ones = torch.ones_like(du0t) masks =torch.zeros([du0.shape[0],3,21,41]).to(device) result =torch.zeros([du0.shape[0],3,21,41]).to(device) result[:,:,:20,:40] = du0t result[:,:,:20,1:] += du1t result[:,:,1:,:40] += du3t result[:,:,1:,1:] += du2t masks[:,:,:20,:40] += ones masks[:,:,:20,1:] += ones masks[:,:,1:,:40] += ones masks[:,:,1:,1:] += ones lp1 = (result / masks) - output[:, [2,3,4]] # lp1 = torch.matmul(C,du_post) - sig_post # lp1 = torch.matmul(C, torch.matmul(B0T,ue)) - sig_post # ??? # return (lp1**2).sum([1,2,3]) return (lp1**2).sum([1,2,3]).mean() # !!!!!!!!!!!! def conv_constitutive_constraint(input, output, sobel_filter): """sigma = - K * grad(u) Args: input (Tensor): (1, 1, 65, 65) output (Tensor): (1, 3, 65, 65), three channels from 0-2: u, sigma_1, sigma_2 """ grad_h = sobel_filter.grad_h(output[:, [0]]) grad_v = sobel_filter.grad_v(output[:, [0]]) est_sigma1 = - input * grad_h est_sigma2 = - input * grad_v return ((output[:, [1]] - est_sigma1) ** 2 + (output[:, [2]] - est_sigma2) ** 2).mean() def conv_constitutive_constraint_nonlinear(input, output, sobel_filter, beta1, beta2): """Nonlinear extension of Darcy's law - K * grad_u = sigma + beta1 * sqrt(K) * sigma ** 2 + beta2 * K * sigma ** 3 Args: input: K output: u, sigma1, sigma2 """ K_u_h = - input * sobel_filter.grad_h(output[:, [0]]) K_u_v = - input * sobel_filter.grad_v(output[:, [0]]) sigma = output[:, [1, 2]] rhs = sigma + beta1 * torch.sqrt(input) * sigma ** 2 + beta2 * input * sigma ** 3 return ((K_u_h - rhs[:, [0]])** 2 + (K_u_v - rhs[:, [1]]) ** 2).mean() def conv_constitutive_constraint_nonlinear_exp(input, output, sobel_filter): """Nonlinear extension of Darcy's law sigma = - exp(K * u) grad(u) Args: input: K output: u, sigma1, sigma2 """ grad_h = sobel_filter.grad_h(output[:, [0]]) grad_v = sobel_filter.grad_v(output[:, [0]]) sigma_h = - torch.exp(input * output[:, [0]]) * grad_h sigma_v = - torch.exp(input * output[:, [0]]) * grad_v return ((output[:, [1]] - sigma_h) ** 2 + (output[:, [2]] - sigma_v) ** 2).mean() def cc2new(output, sobel_filter): sx = output[:, [2]] sy = output[:, [3]] sxy = output[:, [4]] dsxdx = sx[:,:,:20,1:]-sx[:,:,:20,:40] # dsxdy = sx[:,:,1:,:40]-sx[:,:,:20,:40] dsydy = sy[:,:,1:,:40]-sy[:,:,:20,:40] dsxydx = sxy[:,:,:20,1:]-sxy[:,:,:20,:40] dsxydy = sxy[:,:,1:,:40]-sxy[:,:,:20,:40] ds = torch.cat([dsxdx+dsxydy, dsydy+dsxydx],1) return (ds ** 2).sum([1,2,3]).mean() # !!!!!!!!!!!! def cc2(output, sobel_filter): dsxdx = sobel_filter.grad_h(output[:, [2]]) dsydy = sobel_filter.grad_v(output[:, [3]]) dsxydx = sobel_filter.grad_h(output[:, [4]]) dsxydy = sobel_filter.grad_v(output[:, [4]]) ds = torch.cat([dsxdx+dsxydy, dsydy+dsxydx],1) # return (ds ** 2).mean() #return (ds ** 2).sum([1,2,3]).mean() return (ds ** 2).sum([2,3]).mean() # !!!!!!!!!!!! def conv_continuity_constraint(output, sobel_filter, use_tb=True): """ div(sigma) = -f Args: """ sigma1_x1 = sobel_filter.grad_h(output[:, [1]]) sigma2_x2 = sobel_filter.grad_v(output[:, [2]]) # leave the top and bottom row free, since sigma2_x2 is almost 0, # don't want to enforce sigma1_x1 to be also zero. if use_tb: return ((sigma1_x1 + sigma2_x2) ** 2).mean() else: return ((sigma1_x1 + sigma2_x2) ** 2)[:, :, 1:-1, :].mean() def bc(output, output_post): ux = output[:, [0]] uy = output[:, [1]] lu = ux[:,:,:,0]**2 + uy[:,:,:,0]**2 sx = output[:, [2]] sy = output[:, [3]] sxy = output[:, [4]] lbr = (sx[:,:,:,40]-1)**2 + (sxy[:,:,:,40])**2 lbt = (sy[:,:,0,2:-2])**2 + (sxy[:,:,0,2:-2])**2 lbb = (sy[:,:,20,2:-2])**2 + (sxy[:,:,20,2:-2])**2 return torch.cat([lu,lbb,lbt,lbr],2).sum([-1]).mean() # !!!!!!!!!!!! def conv_boundary_condition(output): left_bound, right_bound = output[:, 0, :, 0], output[:, 0, :, -1] top_down_flux = output[:, 2, [0, -1], :] loss_dirichlet = F.mse_loss(left_bound, torch.ones_like(left_bound)) \ + F.mse_loss(right_bound, torch.zeros_like(right_bound)) loss_neumann = F.mse_loss(top_down_flux, torch.zeros_like(top_down_flux)) return loss_dirichlet, loss_neumann <file_sep>import numpy as np from scipy.sparse import coo_matrix from scipy.sparse.linalg import spsolve def FEA(nelx, nely, x, penal): # dofs: ndof = 2*(nelx+1)*(nely+1) xPhys = x.copy() KE = lk() edofMat = np.zeros((nelx*nely, 8), dtype=int) for elx in range(nelx): for ely in range(nely): el = ely+elx*nely n1 = (nely+1)*elx+ely n2 = (nely+1)*(elx+1)+ely edofMat[el, :] = np.array( #[2*n1+2, 2*n1+3, 2*n2+2, 2*n2+3, 2*n2, 2*n2+1, 2*n1, 2*n1+1]) [2*n1, 2*n1+1, 2*n2, 2*n2+1, 2*n2+2, 2*n2+3, 2*n1+2, 2*n1+3 ]) # Construct the index pointers for the coo format iK = np.kron(edofMat, np.ones((8, 1))).flatten() jK = np.kron(edofMat, np.ones((1, 8))).flatten() # BC's and support dofs = np.arange(2*(nelx+1)*(nely+1)) #fixed = np.union1d(dofs[0:2*(nely+1):2], np.array([2*(nelx+1)*(nely+1)-1])) fixed = dofs[0:2*(nely+1)] free = np.setdiff1d(dofs, fixed) # Solution and RHS vectors f = np.zeros((ndof, 1)) u = np.zeros((ndof, 1)) # Set load #f[1, 0] = -1 #f[ndof-1,0] = -1 # CASE 1 #loaddof=np.array(range(2*(nely+1)*nelx,2*(nely+1)*(nelx+1),2)) #f[loaddof,0]=1 # CASE 2 loaddof=np.array(range(2*(nely+1)*nelx+2,2*(nely+1)*(nelx+1)-2,2)) f[loaddof,0]=1 f[2*(nely+1)*nelx,0]=0.5 f[2*(nely+1)*(nelx+1)-2,0]=0.5 #sK = ((KE.flatten()[np.newaxis]).T*(Emin+(xPhys) # ** penal*(Emax-Emin))).flatten(order='F') sK = ((KE.flatten()[np.newaxis]).T*((xPhys)** penal)).flatten(order='F') K = coo_matrix((sK, (iK, jK)), shape=(ndof, ndof)).tocsc() # Remove constrained dofs from matrix K = K[free, :][:, free] # Solve system u[free, 0] = spsolve(K, f[free, 0]) return u def CompuStress(nelx, nely, x, penal, u): D=ElasticTensor() B=StrainDispMat() SMat = np.zeros([(nelx+1)*(nely+1),3]) NumCount = np.zeros([(nelx+1)*(nely+1),1]) strs = np.zeros([(nelx+1)*(nely+1)*3,1]) for elx in range(nelx): for ely in range(nely): el = ely+elx*nely n1 = (nely+1)*elx+ely n2 = (nely+1)*(elx+1)+ely edof = np.array( [2*n1, 2*n1+1, 2*n2, 2*n2+1, 2*n2+2, 2*n2+3, 2*n1+2, 2*n1+3 ]) ue=u[edof,0] n3 = n2 + 1 n4 = n1 + 1 SMat[n1,:]=SMat[n1,:]+x[el]**penal*D@B[0,:,:]@ue SMat[n2,:]=SMat[n2,:]+x[el]**penal*D@B[1,:,:]@ue SMat[n3,:]=SMat[n3,:]+x[el]**penal*D@B[2,:,:]@ue SMat[n4,:]=SMat[n4,:]+x[el]**penal*D@B[3,:,:]@ue NumCount[[n1,n2,n3,n4],0]=NumCount[[n1,n2,n3,n4],0]+[1,1,1,1] for i in range((nelx+1)*(nely+1)): strs[[i*3,i*3+1,i*3+2],0]=SMat[i,:]/NumCount[i] return strs #element stiffness matrix def lk(): E=1 nu=0.3 k=np.array([1/2-nu/6,1/8+nu/8,-1/4-nu/12,-1/8+3*nu/8,-1/4+nu/12,-1/8-nu/8,nu/6,1/8-3*nu/8]) KE = E/(1-nu**2)*np.array([ [k[0], k[1], k[2], k[3], k[4], k[5], k[6], k[7]], [k[1], k[0], k[7], k[6], k[5], k[4], k[3], k[2]], [k[2], k[7], k[0], k[5], k[6], k[3], k[4], k[1]], [k[3], k[6], k[5], k[0], k[7], k[2], k[1], k[4]], [k[4], k[5], k[6], k[7], k[0], k[1], k[2], k[3]], [k[5], k[4], k[3], k[2], k[1], k[0], k[7], k[6]], [k[6], k[3], k[4], k[1], k[2], k[7], k[0], k[5]], [k[7], k[2], k[1], k[4], k[3], k[6], k[5], k[0]] ]) return (KE) def ElasticTensor(): E=1 nu=0.3 D = E/(1-nu**2)*np.array([[1,nu,0], [nu,1,0], [0,0,(1-nu)/2] ]) return D def StrainDispMat(): B=np.zeros([4,3,8],dtype=float) B[0,:,:]=np.array([ [-1, 0, 1, 0, 0, 0, 0, 0], [0, -1, 0, 0, 0, 0, 0, 1], [-1, -1, 0, 1, 0, 0, 1, 0] ]) B[1,:,:]=np.array([ [-1, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, -1, 0, 1, 0, 0], [0, -1, -1, 1, 1, 0, 0, 0] ]) B[2,:,:]=np.array([ [0, 0, 0, 0, 1, 0, -1, 0], [0, 0, 0, -1, 0, 1, 0, 0], [0, 0, -1, 0, 1, 1, 0, -1] ]) B[3,:,:]=np.array([ [0, 0, 0, 0, 1, 0, -1, 0], [0, -1, 0, 0, 0, 0, 0, 1], [-1, 0, 0, 0, 0, 1, 1, -1] ]) return B def ComputeTarget(input): # x np.array [bs, 1, 20, 40] nelx = 40 nely = 20 penal = 3.0 bs = input.shape[0] result = np.zeros([bs, 5, 21, 41], dtype=float) data = input.transpose([0,1,3,2]).reshape(-1,800) # data = input.permute([0,1,3,2]).contiguous().view(-1,800) for i in range(bs): xx = data[i] u = FEA(nelx, nely, xx, penal) strs=CompuStress(nelx, nely, xx, penal, u) ux = u[range(0,1722,2)] uy = u[range(1,1722,2)] sx = strs[range(0,2583,3)] sy = strs[range(1,2583,3)] sxy = strs[range(2,2583,3)] result[i] = np.concatenate([ux,uy,sx,sy,sxy],1).T.reshape(5,41,21).transpose([0,2,1]) return result if __name__ == "__main__": # Default input parameters nelx = 40 nely = 20 penal = 3.0 volfrac = 0.4 x = volfrac * np.ones(nely*nelx, dtype=float) # 0.001 <= x <= 1 u = FEA(nelx, nely, x, penal) print(u[42:84:1]) #print(u[43:84:2]) strs=CompuStress(nelx, nely, x, penal, u) print(strs[0:14:1])<file_sep>import torch import torch.nn.functional as F from models.darcy import cc1 from models.darcy import cc2 from models.darcy import bc import numpy as np from utils.image_gradient import SobelFilter from FEA_simp import ComputeTarget device = torch.device("cuda" if torch.cuda.is_available() else "cpu") data = np.loadtxt("data/rho20x40_SIMP_Edge.txt", dtype=np.float32) # [bs, 1, 20, 40] data = data.reshape(-1,1,40,20).transpose([0,1,3,2]) data_u = np.loadtxt("data/dis20x40_SIMP_Edge.txt", dtype=np.float32) data_s = np.loadtxt("data/stress20x40_SIMP_Edge.txt", dtype=np.float32) ref_u0 = torch.from_numpy(data_u).unsqueeze(1).to(device) ref_uy = ref_u0[:,:,range(1,1722,2)] ref_ux = ref_u0[:,:,range(0,1722,2)] ref_s0 = torch.from_numpy(data_s).unsqueeze(1).to(device) ref_sx = ref_s0[:,:,range(0,2583,3)] ref_sy = ref_s0[:,:,range(1,2583,3)] ref_sxy = ref_s0[:,:,range(2,2583,3)] # [bs, 5, 21, 41] ref = torch.cat([ref_ux, ref_uy, ref_sx, ref_sy, ref_sxy],1).view(-1,5,41,21).permute(0,1,3,2) # input = np.array(np.random.random([1,1,20,40]), dtype=np.float32) # output = torch.from_numpy(np.array(ComputeTarget(input), dtype=np.float32)).to(device) # input = torch.from_numpy(input).to(device) input = torch.from_numpy(data[:1024]) output = ref[:1024] # post output WEIGHTS_2x2 = torch.FloatTensor( np.ones([1,1,2,2])/4 ).to(device) o0 = F.conv2d(output[:,[0]], WEIGHTS_2x2, stride=1, padding=0, bias=None) o1 = F.conv2d(output[:,[1]], WEIGHTS_2x2, stride=1, padding=0, bias=None) o2 = F.conv2d(output[:,[2]], WEIGHTS_2x2, stride=1, padding=0, bias=None) o3 = F.conv2d(output[:,[3]], WEIGHTS_2x2, stride=1, padding=0, bias=None) o4 = F.conv2d(output[:,[4]], WEIGHTS_2x2, stride=1, padding=0, bias=None) output_post = torch.cat([o0,o1,o2,o3,o4],1) sobel_filter = SobelFilter(64, correct=False, device=device) print (cc1(input, output, output_post, sobel_filter, device)) print(cc2(output_post, sobel_filter)) loss_boundary = bc(output, output_post) print(loss_boundary)<file_sep>#!/bin/bash KLE=$1 NUM_TRAIN=$2 function gdrive_download () { CONFIRM=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate "https://docs.google.com/uc?export=download&id=$1" -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p') wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$CONFIRM&id=$1" -O $2 rm -rf /tmp/cookies.txt } # kle100ng32n4096beta150.tar GDRIVE_ID=1--1F6AvzyEKyta3yfdtdpfGR9sPebbd6 TARGET_DIR=./experiments/cglow/reverse_kld mkdir -p $TARGET_DIR TAR_FILE=./experiments/cglow/reverse_kld/kle100ng32n4096beta150.tar gdrive_download $GDRIVE_ID $TAR_FILE tar -xvf $TAR_FILE -C $TARGET_DIR rm $TAR_FILE <file_sep>"""Solving Darcy Flow using ConvNet with mixed residual loss Flow through Porous Media, 2D div (K(s) grad u(s)) = 0, s = (s1, s2) in (0, 1) x (0, 1) Boundary: u = 1, s1 = 0; u = 0, s1 = 1 u_s2 = 0, s2 in {0, 1} Optimizer: L-BFGS Considered nonlinear PDE. (nonlinear corrections to Darcy) """ import torch import torch.nn as nn import torch.autograd as ag import torch.nn.functional as F import torch.optim as optim from models.codec import Decoder from utils.image_gradient import SobelFilter from models.darcy import conv_continuity_constraint as continuity_constraint from models.darcy import conv_boundary_condition as boundary_condition from utils.plot import save_stats, plot_prediction_det, plot_prediction_det_animate2 from utils.misc import mkdirs, to_numpy import numpy as np import argparse import h5py import sys import time import os from pprint import pprint import matplotlib.pyplot as plt plt.switch_backend('agg') def main(): parser = argparse.ArgumentParser(description='CNN to solve PDE') parser.add_argument('--exp-dir', type=str, default='./experiments/solver', help='color map') parser.add_argument('--nonlinear', action='store_true', default=False, help='set True for nonlinear PDE') # data parser.add_argument('--data-dir', type=str, default="./datasets", help='directory to dataset') parser.add_argument('--data', type=str, default='grf', choices=['grf', 'channelized', 'warped_grf'], help='data type') parser.add_argument('--kle', type=int, default=512, help='# kle terms') parser.add_argument('--imsize', type=int, default=64, help='image size') parser.add_argument('--idx', type=int, default=8, help='idx of input, please use 0 ~ 999') parser.add_argument('--alpha1', type=float, default=1.0, help='coefficient for the squared term') parser.add_argument('--alpha2', type=float, default=1.0, help='coefficient for the cubic term') # latent size: (nz, sz, sz) parser.add_argument('--nz', type=int, default=1, help='# feature maps of latent z') # parser.add_argument('--sz', type=int, default=16, help='feature map size of latent z') parser.add_argument('--blocks', type=list, default=[8, 6], help='# layers in each dense block of the decoder') parser.add_argument('--weight-bound', type=float, default=10, help='weight for boundary condition loss') parser.add_argument('--lr', type=float, default=0.5, help='learning rate') parser.add_argument('--epochs', type=int, default=500, help='# epochs to train') parser.add_argument('--test-freq', type=int, default=50, help='every # epoch to test') parser.add_argument('--ckpt-freq', type=int, default=250, help='every # epoch to save model') parser.add_argument('--cmap', type=str, default='jet', help='color map') parser.add_argument('--same-scale', action='store_true', help='true for setting noise to be same scale as output') parser.add_argument('--animate', action='store_true', help='true to plot animate figures') parser.add_argument('--cuda', type=int, default=1, help='cuda number') parser.add_argument('-v', '--verbose', action='store_true', help='True for versbose output') args = parser.parse_args() pprint(vars(args)) device = torch.device(f"cuda:{args.cuda}" if torch.cuda.is_available() else "cpu") dataset = f'{args.data}_kle{args.kle}' if args.data == 'grf' else args.data hyparams = f'{dataset}_idx{args.idx}_dz{args.nz}_blocks{args.blocks}_'\ f'lr{args.lr}_wb{args.weight_bound}_epochs{args.epochs}' if args.nonlinear: from utils.fenics import solve_nonlinear_poisson exp_name = 'conv_mixed_residual_nonlinear' from models.darcy import conv_constitutive_constraint_nonlinear as constitutive_constraint hyparams = hyparams + f'_alpha1_{args.alpha1}_alpha2_{args.alpha2}' else: exp_name = 'conv_mixed_residual' from models.darcy import conv_constitutive_constraint as constitutive_constraint run_dir = args.exp_dir + '/' + exp_name + '/' + hyparams mkdirs(run_dir) # load data assert args.idx < 1000 if args.data == 'grf': assert args.kle in [512, 128, 1024, 2048] ntest = 1000 if args.kle == 512 else 1024 hdf5_file = args.data_dir + f'/{args.imsize}x{args.imsize}/kle{args.kle}_lhs{ntest}_test.hdf5' elif args.data == 'warped_grf': hdf5_file = args.data_dir + f'/{args.imsize}x{args.imsize}/warped_gp_ng64_n1000.hdf5' elif args.data == 'channelized': hdf5_file = args.data_dir + f'/{args.imsize}x{args.imsize}/channel_ng64_n512_test.hdf5' else: raise ValueError('No dataset are found for the speficied parameters') print(f'dataset: {hdf5_file}') with h5py.File(hdf5_file, 'r') as f: input_data = f['input'][()] output_data = f['output'][()] print(f'input: {input_data.shape}') print(f'output: {output_data.shape}') # permeability, (1, 1, 64, 64) perm_arr = input_data[[args.idx]] # pressure, flux_hor, flux_ver, (3, 64, 64) if args.nonlinear: # solve nonlinear Darcy for perm_arr with FEniCS output_file = run_dir + '/output_fenics.npy' if os.path.isfile(output_file): output_arr = np.load(output_file) print('Loaded solved output field') else: print('Solve nonlinear poisson with FEniCS...') output_arr = solve_nonlinear_poisson(perm_arr[0, 0], args.alpha1, args.alpha2, run_dir) np.save(output_file, output_arr) else: output_arr = output_data[args.idx] print('output shape: ', output_arr.shape) # model model = Decoder(args.nz, out_channels=3, blocks=args.blocks).to(device) print(f'model size: {model.model_size}') fixed_latent = torch.randn(1, args.nz, 16, 16).to(device) * 0.5 perm_tensor = torch.FloatTensor(perm_arr).to(device) sobel_filter = SobelFilter(args.imsize, correct=True, device=device) optimizer = optim.LBFGS(model.parameters(), lr=args.lr, max_iter=20, history_size=50) logger = {} logger['loss'] = [] def train(epoch): model.train() def closure(): optimizer.zero_grad() output = model(fixed_latent) if args.nonlinear: energy = constitutive_constraint(perm_tensor, output, sobel_filter, args.alpha1, args.alpha2) \ + continuity_constraint(output, sobel_filter) else: energy = constitutive_constraint(perm_tensor, output, sobel_filter) + continuity_constraint(output, sobel_filter) loss_dirichlet, loss_neumann = boundary_condition(output) loss_boundary = loss_dirichlet + loss_neumann loss = energy + loss_boundary * args.weight_bound loss.backward() if args.verbose: print(f'epoch {epoch}: loss {loss.item():6f}, '\ f'energy {energy.item():.6f}, diri {loss_dirichlet.item():.6f}, '\ f'neum {loss_neumann.item():.6f}') return loss loss = optimizer.step(closure) loss_value = loss.item() if not isinstance(loss, float) else loss logger['loss'].append(loss_value) print(f'epoch {epoch}: loss {loss_value:.6f}') if epoch % args.ckpt_freq == 0: torch.save(model.state_dict(), run_dir + "/model_epoch{}.pth".format(epoch)) def test(epoch): if epoch % args.epochs == 0 or epoch % args.test_freq == 0: output = model(fixed_latent) output = to_numpy(output) if args.animate: i_plot = epoch // args.test_freq plot_prediction_det_animate2(run_dir, output_arr, output[0], epoch, args.idx, i_plot, plot_fn='imshow', cmap=args.cmap, same_scale=args.same_scale) else: plot_prediction_det(run_dir, output_arr, output[0], epoch, args.idx, plot_fn='imshow', cmap=args.cmap, same_scale=args.same_scale) np.save(run_dir + f'/epoch{epoch}.npy', output[0]) print('start training...') dryrun = False tic = time.time() for epoch in range(1, args.epochs + 1): if not dryrun: train(epoch) test(epoch) print(f'Finished optimization for {args.epochs} epochs using {(time.time()-tic)/60:.3f} minutes') save_stats(run_dir, logger, 'loss') # save input plt.imshow(perm_arr[0, 0]) plt.colorbar() plt.savefig(run_dir + '/input.png') plt.close() if __name__ == '__main__': main() <file_sep>""" Compositional pattern-producing network (CPPN) (x, y) --> p """ import torch import torch.nn as nn import numpy as np import torch.nn.functional as F class CPPN(nn.Sequential): """size 1024 x 1024 is okay to generate at one pass """ def __init__(self, dim_in, dim_out, dim_hidden, layers_hidden, act='tanh', xavier_init=True): super(CPPN, self).__init__() self.add_module('fc0', nn.Linear(dim_in, dim_hidden, bias=None)) self.add_module('act0', nn.Tanh()) for i in range(1, layers_hidden): self.add_module('fc{}'.format(i), nn.Linear(dim_hidden, dim_hidden, bias=True)) if act == 'tanh': self.add_module('act{}'.format(i), nn.Tanh()) elif act == 'relu': self.add_module('act{}'.format(i), nn.ReLU()) else: raise ValueError(f'unknown activation function: {act}') self.add_module('fc{}'.format(layers_hidden), nn.Linear(dim_hidden, dim_out)) if xavier_init: self.init_xavier() def forward_test(self, x): print('{:<15}{:>30}'.format('input', str(x.size()))) for name, module in self._modules.items(): x = module(x) print('{:<15}{:>30}'.format(name, str(x.size()))) return x def init_xavier(self): for param in self.parameters(): if len(param.shape) > 1: nn.init.xavier_normal_(param) def _model_size(self): n_params, n_fc_layers = 0, 0 for name, param in self.named_parameters(): if 'fc' in name: n_fc_layers += 1 n_params += param.numel() return n_params, n_fc_layers def activation(name): if name in ['tanh', 'Tanh']: return nn.Tanh() elif name in ['relu', 'ReLU']: return nn.ReLU(inplace=True) elif name in ['lrelu', 'LReLU']: return nn.LeakyReLU(inplace=True) elif name in ['sigmoid', 'Sigmoid']: return nn.Sigmoid() elif name in ['softplus', 'Softplus']: return nn.Softplus(beta=4) else: raise ValueError('Unknown activation function') # densely fully connected NN class _ResLayer(nn.Module): def __init__(self, dim_in, dim_out, dim_hidden, act='tanh'): super().__init__() self.fc1 = nn.Linear(dim_in, dim_hidden, bias=True) self.fc2 = nn.Linear(dim_hidden, dim_out, bias=True) if act == 'tanh': self.act = F.tanh elif act == 'relu': self.act = F.relu def forward(self, x): # pre-activation res = x out = self.fc1(self.act(x)) out = self.fc2(self.act(out)) return res + out class ResCPPN(nn.Sequential): def __init__(self, dim_in, dim_out, dim_hidden, res_layers, act='tanh'): super().__init__() self.add_module('fc0', nn.Linear(dim_in, dim_hidden, bias=None)) for i in range(res_layers): reslayer = _ResLayer(dim_hidden, dim_hidden, dim_hidden, act=act) self.add_module(f'reslayer{i+1}', reslayer) self.add_module('act_last', activation(act)) self.add_module('fc_last', nn.Linear(dim_hidden, dim_out, bias=True)) def _model_size(self): n_params, n_fc_layers = 0, 0 for name, param in self.named_parameters(): if 'fc' in name: n_fc_layers += 1 n_params += param.numel() return n_params, n_fc_layers if __name__ == '__main__': cppn = ResCPPN(dim_in=2, dim_out=1, dim_hidden=64, res_layers=3, act='tanh') print(cppn) print(cppn._model_size()) x = torch.randn(16, 2) y = cppn(x) print(y.shape) <file_sep>""" Sampling in spatial domain collocation points boundary points For sure, lots of people will work on how to use different sampling grid to train fully-connected networks. """ import numpy as np import torch from .lhs import lhs class SampleSpatial2d(object): """Uniform grid (y, x) h - height, or y axis w - width, x axis default output [0, 1] from [0, ngrid_h - 1], [0, ngrid_w - 1] """ def __init__(self, ngrid_h, ngrid_w): self.ngrid_h = int(ngrid_h) self.ngrid_w = int(ngrid_w) self.n_grids = self.ngrid_h * self.ngrid_w self.refactor = torch.FloatTensor(np.array([[ngrid_h-1, ngrid_w-1]])) self.coordinates = self._coordinates() self.coordinates_no_boundary = self._coordinates_no_boundary() def _coordinates(self): # super wired torch.meshgrid grid_x, grid_y = np.meshgrid(np.arange(self.ngrid_w), np.arange(self.ngrid_h)) points = np.stack((grid_y.flatten(), grid_x.flatten()), 1) return torch.FloatTensor(points) def _coordinates_no_boundary(self): grid_x, grid_y = np.meshgrid(np.arange(self.ngrid_w), np.arange(self.ngrid_h)) points = np.stack((grid_y[1:-1, 1:-1].flatten(), grid_x[1:-1, 1:-1].flatten()), 1) return torch.FloatTensor(points) def _sample2d(self, on_grid, n_samples=None, no_boundary=False): if n_samples is None: n_samples = self.n_grids if on_grid: if no_boundary: points = self.coordinates_no_boundary.to(torch.float32) / self.refactor else: points = self.coordinates.to(torch.float32) / self.refactor if n_samples < len(points): points = points[torch.randperm(self.n_grids)[:n_samples]] else: print('n_samples is greater than grid size, set n_samples '\ 'equals to grid size') else: points = torch.FloatTensor(lhs(2, n_samples)) return points def _sample1d(self, horizontal, on_grid, n_samples=None): """ if on_grid is on, n_sampels is ignored if it is larger than ngrid. """ ngrid = self.ngrid_h if horizontal else self.ngrid_w if n_samples is None: n_samples = ngrid if on_grid: points = (torch.arange(float(ngrid)) / (ngrid-1)) if n_samples <= len(points): points = points[torch.randperm(ngrid)[:n_samples]] else: print('n_samples is greater than grid size, set n_samples '\ 'equals to grid size') else: points = torch.rand(n_samples) return points def left(self, on_grid=True, n_samples=None): points = self._sample1d(horizontal=True, on_grid=on_grid, n_samples=n_samples) return torch.stack((points, torch.zeros_like(points)), 1) def right(self, on_grid=True, n_samples=None): points = self._sample1d(horizontal=True, on_grid=on_grid, n_samples=n_samples) return torch.stack((points, torch.ones_like(points)), 1) def top(self, on_grid=True, n_samples=None): points = self._sample1d(horizontal=False, on_grid=on_grid, n_samples=n_samples) return torch.stack((torch.zeros_like(points), points), 1) def bottom(self, on_grid=True, n_samples=None): points = self._sample1d(horizontal=False, on_grid=on_grid, n_samples=n_samples) return torch.stack((torch.ones_like(points), points), 1) def colloc(self, on_grid=True, n_samples=None, no_boundary=False): return self._sample2d(on_grid, n_samples, no_boundary) if __name__ == '__main__': ngrid_h = 10 ngrid_w = 10 sampler = SampleSpatial2d(ngrid_h, ngrid_w) # print(sampler.refactor) # print(sampler.refactor.shape) # points = sampler.lhs(n_samples=1000, on_grid=True) # print(points) points = sampler.right(on_grid=True, n_samples=12) # points = sampler.colloc(on_grid=False, n_samples=99, no_boundary=False) print(points * sampler.refactor) print(points.shape) <file_sep>""" Post processing, mainly for uncertainty quantification tasks using pre-trained conditional Glow. """ import torch from models.glow_msc import MultiScaleCondGlow from utils.uq import UQ_CondGlow from utils.load import load_args from utils.misc import mkdirs from torch.utils.data import DataLoader, TensorDataset from time import time import h5py import argparse parser = argparse.ArgumentParser() parser.add_argument('--run-dir', type=str, default=None, help='directory to an experiment run') parser.add_argument('--n-pred', type=int, default=32, help='# prediction at x') parser.add_argument('--n-samples', type=int, default=20, help='# predictive output samples per input') parser.add_argument('--plot-samples', action='store_true', default=False, help='plot predictive output samples per input') parser.add_argument('--var-samples', type=int, default=10, help='# exprs to evaluate the mean and var of the statistics in uncertainty propagation') parser.add_argument('--temperature', type=float, default=1.0, help='sampling temperature for Gaussian noise') parser.add_argument('--n-loc', type=int, default=40, help='# locations on which to evalute the PDF') parser.add_argument('--n-mc', type=int, default=10000, help='# data for Monte Carlo') parser.add_argument('--mc-bs', type=int, default=1000, help='batch size for Monte Carlo') parser.add_argument('--cuda', type=int, default=0, help='gpu #') args_post = parser.parse_args() run_dir = './experiments/cglow/reverse_kld/kle100_ntrain4096_ENC_blocks[3, 4, 4]_'\ 'FLOW_blocks[6, 6, 6]_wb50_beta150.0_batch32_lr0.0015_epochs400' if args_post.run_dir is not None: run_dir = args_post.run_dir device = torch.device(f'cuda:{args_post.cuda}' if torch.cuda.is_available() else 'cpu') # load the args for pre-trained run args = load_args(run_dir) args.device = device args.post_dir = args.run_dir + f'/post_proc_mc{args_post.n_mc}_nsamples{args_post.n_samples}_'\ f'varsamples{args_post.var_samples}_temp{args_post.temperature}' mkdirs(args.post_dir) # load the pre-trained model cglow = MultiScaleCondGlow(img_size=args.imsize, x_channels=args.x_channels, y_channels=args.y_channels, enc_blocks=args.enc_blocks, flow_blocks=args.flow_blocks, LUdecompose=args.LU_decompose, squeeze_factor=2, data_init=args.data_init) print(cglow.model_size) ckpt_file = args.ckpt_dir + f"/model_epoch{args.epochs}.pth" checkpoint = torch.load(ckpt_file, map_location='cpu') cglow.load_state_dict(checkpoint['model_state_dict']) cglow = cglow.to(device) if args.data_init: cglow.init_actnorm() cglow.eval() print(f'Loaded checkpoint: {ckpt_file}') # load Monte Carlo data: 10,000 hdf5_file = args.data_dir + f'/{args.imsize}x{args.imsize}/kle{args.kle}_lhs10000_monte_carlo.hdf5' tic = time() with h5py.File(hdf5_file, 'r') as f: x_data = f['input'][-args_post.n_mc:] y_data = f['output'][-args_post.n_mc:] print(f'y: {y_data.shape}') mc_loader = DataLoader(TensorDataset(torch.FloatTensor(x_data), torch.FloatTensor(y_data)), batch_size=args_post.mc_bs, shuffle=False, drop_last=True) print(f'Loaded Monte Carlo data in {hdf5_file} in {time()-tic} seconds') # load test data if args.kle == 100: test_hdf5_file = args.data_dir + f'/{args.imsize}x{args.imsize}/kle{args.kle}_lhs1000_test.hdf5' with h5py.File(test_hdf5_file, 'r') as f: x_test = f['input'][:args.ntest] # no sim data yet y_test = f['output'][:args.ntest] print(f'y_test: {y_test.shape}') y_test_variation = ((y_test - y_test.mean(0, keepdims=True)) ** 2).sum(axis=(0, 2, 3)) test_loader = DataLoader(TensorDataset(torch.FloatTensor(x_test), torch.FloatTensor(y_test)), batch_size=512, shuffle=True, drop_last=True) print(f'Loaded test data in: {test_hdf5_file}') # Now performs UQ tasks uq = UQ_CondGlow(cglow, args, mc_loader, test_loader, y_test_variation, n_samples=args_post.n_samples, temperature=args_post.temperature) with torch.no_grad(): uq.plot_prediction_at_x(n_pred=args_post.n_pred, plot_samples=args_post.plot_samples) uq.plot_dist(num_loc=args_post.n_loc) uq.test_metric(handle_nan=True) uq.plot_reliability_diagram(save_time=True) uq.propagate_uncertainty(manual_scale=False, var_samples=args_post.var_samples) <file_sep>r"""Solving Darcy Flow using fully-connected neural nets with mixed residual loss Flow through Porous Media, 2D div (K(x) grad u(x)) = 0, x = (x1, x2) \in (0, 1) x (0, 1) Boundary: u = 1, s1 = 0; u = 0, s1 = 1 u_s2 = 0, s2 in {0, 1} K -- permeability u -- pressure Optimizer: L-BFGS Only considered the linear PDE case. """ import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from models.cppn import CPPN from utils.sampling import SampleSpatial2d from utils.image_gradient import SobelFilter from models.darcy import mixed_residual_fc, neumann_boundary_mixed, grad from utils.plot import plot_row, save_stats, plot_prediction_det_animate2, plot_prediction_det from utils.misc import mkdirs import numpy as np import argparse import h5py import sys import time from pprint import pprint import matplotlib.pyplot as plt import matplotlib plt.switch_backend('agg') print('ok') def main(): parser = argparse.ArgumentParser(description='CNN to solve PDE') parser.add_argument('--exp-dir', type=str, default='./experiments/solver', help='color map') # data parser.add_argument('--data-dir', type=str, default="./datasets", help='directory to dataset') parser.add_argument('--data', type=str, default='grf', choices=['grf', 'channelized', 'warped_grf'], help='data type') parser.add_argument('--kle', type=int, default=512, help='# kle terms') parser.add_argument('--imsize', type=int, default=64, help='image size') parser.add_argument('--idx', type=int, default=8, help='idx of input, please use 0 ~ 999') parser.add_argument('--alpha1', type=float, default=1.0, help='coefficient for the squared term') parser.add_argument('--alpha2', type=float, default=1.0, help='coefficient for the cubic term') parser.add_argument('--dim-hidden', type=int, default=512, help='# nodes in each hidden layer') parser.add_argument('--layers-hidden', type=int, default=8, help='# hidden layers') parser.add_argument('--off-grid', action='store_true', help='set True to use colloc ') parser.add_argument('--n-colloc', type=int, default=4096, help='# collocation points') parser.add_argument('--weight-bound', type=float, default=10, help='weight for boundary condition loss') parser.add_argument('--lr', type=float, default=0.5, help='learning rate') parser.add_argument('--epochs', type=int, default=2000, help='# epochs to train') parser.add_argument('--test-freq', type=int, default=50, help='every # epoch to test') parser.add_argument('--ckpt-freq', type=int, default=250, help='every # epoch to save model') parser.add_argument('--cmap', type=str, default='jet', help='color map') parser.add_argument('--same-scale', action='store_true', help='true for setting noise to be same scale as output') parser.add_argument('--animate', action='store_true', help='true to plot animate figures') parser.add_argument('--cuda', type=int, default=2, help='cuda number') parser.add_argument('-v', '--verbose', action='store_true', help='True for versbose output') args = parser.parse_args() pprint(vars(args)) device = torch.device(f"cuda:{args.cuda}" if torch.cuda.is_available() else "cpu") exp_name = 'fc_mixed_residual' dataset = f'{args.data}_kle{args.kle}' if args.data == 'grf' else args.data hyparams = f'{dataset}_idx{args.idx}_dhid{args.dim_hidden}_lhid{args.layers_hidden}_alpha1_{args.alpha1}_alpha2_{args.alpha2}_'\ f'lr{args.lr}_wb{args.weight_bound}_epochs{args.epochs}_ongrid_{not args.off_grid}_ncolloc{args.n_colloc}' run_dir = args.exp_dir + '/' + exp_name + '/' + hyparams mkdirs(run_dir) # load data assert args.idx < 1000 if args.data == 'grf': assert args.kle in [512, 128, 1024, 2048] ntest = 1000 if args.kle == 512 else 1024 hdf5_file = args.data_dir + f'/{args.imsize}x{args.imsize}/kle{args.kle}_lhs{ntest}_test.hdf5' elif args.data == 'warped_grf': hdf5_file = args.data_dir + f'/{args.imsize}x{args.imsize}/warped_gp_ng64_n1000.hdf5' elif args.data == 'channelized': assert args.idx < 512 hdf5_file = args.data_dir + f'/{args.imsize}x{args.imsize}/channel_ng64_n512_test.hdf5' else: raise ValueError('No dataset are found for the speficied parameters') print(f'dataset: {hdf5_file}') with h5py.File(hdf5_file, 'r') as f: input_data = f['input'][()] output_data = f['output'][()] print(f'input: {input_data.shape}') print(f'output: {output_data.shape}') # permeability, (1, 1, 64, 64) perm_arr = input_data[[args.idx]] # pressure, flux_hor, flux_ver, (3, 64, 64) output_arr = output_data[args.idx] def to_tensor_gpu(*numpy_seq): # x: numpy array --> tensor on GPU return (torch.FloatTensor(x).to(device) for x in numpy_seq) # define networks net_u = CPPN(dim_in=2, dim_out=3, dim_hidden=args.dim_hidden, layers_hidden=args.layers_hidden).to(device) print(net_u) print(net_u._model_size()) optimizer = optim.LBFGS(net_u.parameters(), lr=args.lr, max_iter=20, history_size=50) logger = {} logger['loss'] = [] ngrids = [args.imsize, args.imsize] sampler = SampleSpatial2d(int(ngrids[0]), int(ngrids[1])) colloc_on_grid = not args.off_grid # for batch optimization x_colloc = sampler.colloc(colloc_on_grid, n_samples=args.n_colloc).to(device) x_dirichlet = torch.cat((sampler.left(on_grid=False, n_samples=256), sampler.right(on_grid=False, n_samples=256)), 0).to(device) y_dirichlet = torch.cat((torch.ones(256, 1), torch.zeros(256, 1)), 0).to(device) x_neumann = torch.cat((sampler.top(colloc_on_grid), sampler.bottom(colloc_on_grid)), 0).to(device) print(sampler.coordinates_no_boundary.shape) K_true_tensor, = to_tensor_gpu(perm_arr.reshape(-1, 1)) if args.verbose: print('x_colloc: {}'.format(x_colloc.shape)) print('x_dirc: {}'.format(x_dirichlet.shape)) print('y_dirc: {}'.format(y_dirichlet.shape)) print('x_neumann: {}'.format(x_neumann.shape)) def train(epoch): net_u.train() def closure(): optimizer.zero_grad() loss_colloc = mixed_residual_fc(net_u, x_colloc, K_true_tensor, args.verbose, rand_colloc=args.off_grid) # loss_colloc = 0 loss_dirichlet = F.mse_loss(net_u(x_dirichlet)[:, [0]], y_dirichlet) loss_neumann = neumann_boundary_mixed(net_u, x_neumann) loss = loss_colloc + args.weight_bound * (loss_dirichlet + loss_neumann) loss.backward() if args.verbose: print(f'epoch {epoch}: colloc {loss_colloc:.6f}, ' f'diri {loss_dirichlet:.6f}, neum {loss_neumann:.6f}') return loss loss = optimizer.step(closure) loss_value = loss.item() if not isinstance(loss, float) else loss logger['loss'].append(loss_value) print('epoch {}: loss {:.10f}'.format(epoch, loss_value)) if epoch % args.ckpt_freq == 0: torch.save(net_u.state_dict(), run_dir + "/model_epoch{}.pth".format(epoch)) def test(epoch): if epoch % args.epochs == 0 or epoch % args.test_freq == 0: # plot the solution xx, yy = np.meshgrid(np.arange(ngrids[0]), np.arange(ngrids[1])) x_test = xx.flatten()[:, None] / ngrids[1] y_test = yy.flatten()[:, None] / ngrids[0] x_test, y_test = to_tensor_gpu(x_test, y_test) net_u.eval() x_test.requires_grad = True y_test.requires_grad = True xy_test = torch.cat((y_test, x_test), 1) y_pred = net_u(xy_test) target = output_arr # three output of net_u from 0-3 channel: u, flux_y, flux_x u_pred = y_pred[:, 0].detach().cpu().numpy().reshape(*ngrids) u_y = y_pred[:, 1].detach().cpu().numpy().reshape(*ngrids) u_x = y_pred[:, 2].detach().cpu().numpy().reshape(*ngrids) prediction = np.stack((u_pred, u_x, u_y)) # prediction = y_pred.view(*ngrids, -1).transpose(0, 1).permute(2, 1, 0).detach().cpu().numpy() if args.animate: i_plot = epoch // args.test_freq plot_prediction_det_animate2(run_dir, target, prediction, epoch, args.idx, i_plot, plot_fn='imshow', cmap=args.cmap, same_scale=args.same_scale) else: plot_prediction_det(run_dir, target, prediction, epoch, args.idx, plot_fn='imshow', cmap=args.cmap, same_scale=args.same_scale) np.save(run_dir + f'/epoch{epoch}.npy', prediction) print('start training...') dryrun = False tic = time.time() for epoch in range(1, args.epochs + 1): if not dryrun: train(epoch) test(epoch) print(f'Finished training {args.epochs} epochs in {(time.time()-tic)/60:.3f} minutes') save_stats(run_dir, logger, 'loss') # save input plt.close() plt.imshow(np.log(perm_arr[0, 0])) plt.colorbar() plt.savefig(run_dir + '/input_logK.png') plt.close() # super-resultion one ngrids = (640, 640) xx, yy = np.meshgrid(np.arange(ngrids[0]), np.arange(ngrids[1])) x_test = torch.FloatTensor(np.stack((yy.flatten() / (ngrids[1]-1), xx.flatten() / (ngrids[0]-1)), 1)).to(device) net_u.eval() u_pred = net_u(x_test) u_pred = u_pred[:, 0].reshape(*ngrids).detach().cpu().numpy() plt.contourf(u_pred, 65) plt.colorbar() plt.savefig(run_dir + '/solution_HR.png') plt.close() if __name__ == '__main__': main()<file_sep>"""Solve nonlinear corrections to Darcy flow """ import dolfin as df import matplotlib.pyplot as plt import numpy as np import matplotlib.ticker as ticker import sys import os from time import time def solve_nonlinear_poisson(input, alpha1, alpha2, save_dir): if not os.path.exists(save_dir): os.makedirs(save_dir) perm = input flux_order = 3 ngy, ngx = perm.shape[0], perm.shape[1] # Create mesh and define function space mesh = df.UnitSquareMesh(ngy-1, ngx-1) K_CG = df.FunctionSpace(mesh, "Lagrange", 1) K = df.Function(K_CG) ordering = df.dof_to_vertex_map(K_CG) K.vector()[:] = perm.flatten(order='C')[ordering] def boundary(x, on_boundary): return x[0] < df.DOLFIN_EPS or x[0] > 1.0 - df.DOLFIN_EPS left = df.CompiledSubDomain("near(x[0], 0.0) && on_boundary") right = df.CompiledSubDomain("near(x[0], 1.0) && on_boundary") top = df.CompiledSubDomain("near(x[1], 1.0) && on_boundary") bottom = df.CompiledSubDomain("near(x[1], 0.0) && on_boundary") boundaries = df.MeshFunction("size_t", mesh, mesh.topology().dim() - 1, 0) # boundaries.set_all(0) left.mark(boundaries, 1) top.mark(boundaries, 2) right.mark(boundaries, 3) bottom.mark(boundaries, 4) ds = df.Measure("ds", domain=mesh, subdomain_data=boundaries) # Discontinuous Raviart-Thomas DRT = df.FiniteElement("DRT", mesh.ufl_cell(), flux_order) # Lagrange CG = df.FiniteElement("CG", mesh.ufl_cell(), flux_order + 1) W = df.FunctionSpace(mesh, DRT * CG) ww = df.Function(W) sigma, u = df.split(ww) tau, v = df.TestFunctions(W) dw = df.TrialFunction(W) # Define boundary condition gamma = df.Expression("1.0 - x[0]", degree=1) bc = df.DirichletBC(W.sub(1), gamma, boundary) g = df.Constant(0.0) f = df.Constant(0.0) def flux(sigma): s1 = sigma[0] s2 = sigma[1] nonlinear1 = alpha1 * df.sqrt(K) * df.as_vector([s1 ** 2, s2 ** 2]) nonlinear2 = alpha2 * K * df.as_vector([s1 ** 3, s2 ** 3]) nonlinear = nonlinear1 + nonlinear2 return nonlinear F = (df.dot(sigma, tau) + df.dot(K * df.grad(u), tau) + df.dot(flux(sigma), tau)\ + df.dot(sigma, df.grad(v)) + f * v) * df.dx + g * v * ds(2) + g * v * ds(4) J = df.derivative(F, ww, dw) # Compute solution problem = df.NonlinearVariationalProblem(F, ww, bc, J) solver = df.NonlinearVariationalSolver(problem) prm = solver.parameters prm['newton_solver']['absolute_tolerance'] = 1E-8 prm['newton_solver']['relative_tolerance'] = 1E-6 prm['newton_solver']['maximum_iterations'] = 10 prm['newton_solver']['relaxation_parameter'] = 1.0 tic = time() solver.solve() print(f'time taken {time()-tic} seconds') (sigma_, u_) = ww.split() u_mat = u_.compute_vertex_values(mesh).reshape(64, 64) grad_u = sigma_.compute_vertex_values(mesh) sigma1 = grad_u[:4096].reshape(64, 64) sigma2 = grad_u[4096:].reshape(64, 64) output = np.stack((u_mat, sigma1, sigma2)) print('output shape: {output.shape}') return output <file_sep>import torch import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker import scipy.io from scipy.stats import norm as scipy_norm import seaborn as sns from utils.misc import mkdir, to_numpy from utils.plot import plot_prediction_bayes2, plot_MC2, save_samples from utils.lhs import lhs plt.switch_backend('agg') class UQ_CondGlow(object): """Class for uncertainty quantification tasks, include: - prediction at one input realization - uncertainty propagation - distribution estimate at certain location - reliability diagram (assess uncertainty quality) Args: model: Pre-trained probabilistic surrogate args: training arguments mc_loader (utils.data.DataLoader): Dataloader for Monte Carlo data """ def __init__(self, model, args, mc_loader, test_loader, y_test_variation, n_samples=20, temperature=1.0): self.model = model self.mc_loader = mc_loader self.test_loader = test_loader self.y_test_variation = y_test_variation self.ntrain = args.ntrain self.plot_fn = args.plot_fn self.epochs = args.epochs self.device = args.device self.post_dir = args.post_dir self.imsize = args.imsize self.n_samples = n_samples self.temperature = temperature print(f'mc loader size: {len(self.mc_loader.dataset)}') print(f'test loader size: {len(self.test_loader.dataset)}') def plot_prediction_at_x(self, n_pred, plot_samples=False): r"""Plot `n_pred` predictions for randomly selected input from test dataset. - target - predictive mean - standard deviation of predictive output distribution - error of the above two Args: n_pred: number of candidate predictions plot_samples (bool): plot 15 output samples from p(y|x) for given x """ save_dir = self.post_dir + '/predict_at_x' mkdir(save_dir) print('Plotting predictions at x from test dataset..................') np.random.seed(1) idx = np.random.permutation(len(self.test_loader.dataset))[:n_pred] for i in idx: print('input index: {}'.format(i)) input, target = self.test_loader.dataset[i] pred_mean, pred_var = self.model.predict(input.unsqueeze(0).to(self.device), n_samples=self.n_samples, temperature=self.temperature) plot_prediction_bayes2(save_dir, target, pred_mean.squeeze(0), pred_var.squeeze(0), self.epochs, i, plot_fn=self.plot_fn) if plot_samples: samples_pred = self.model.sample(input.unsqueeze(0).to(self.device), n_samples=15)[:, 0] samples = torch.cat((target.unsqueeze(0), samples_pred.detach().cpu()), 0) save_samples(save_dir, samples, self.epochs, i, 'samples', nrow=4, heatmap=True, cmap='jet') def propagate_uncertainty(self, manual_scale=False, var_samples=10): print("Propagate Uncertainty using pre-trained surrogate ...........") # compute MC sample mean and variance in mini-batch sample_mean_x = torch.zeros_like(self.mc_loader.dataset[0][0]) sample_var_x = torch.zeros_like(sample_mean_x) sample_mean_y = torch.zeros_like(self.mc_loader.dataset[0][1]) sample_var_y = torch.zeros_like(sample_mean_y) for _, (x_test_mc, y_test_mc) in enumerate(self.mc_loader): x_test_mc, y_test_mc = x_test_mc, y_test_mc sample_mean_x += x_test_mc.mean(0) sample_mean_y += y_test_mc.mean(0) sample_mean_x /= len(self.mc_loader) sample_mean_y /= len(self.mc_loader) for _, (x_test_mc, y_test_mc) in enumerate(self.mc_loader): x_test_mc, y_test_mc = x_test_mc, y_test_mc sample_var_x += ((x_test_mc - sample_mean_x) ** 2).mean(0) sample_var_y += ((y_test_mc - sample_mean_y) ** 2).mean(0) sample_var_x /= len(self.mc_loader) sample_var_y /= len(self.mc_loader) # plot input MC stats_x = torch.stack((sample_mean_x, sample_var_x)).cpu().numpy() fig, _ = plt.subplots(1, 2) for i, ax in enumerate(fig.axes): # ax.set_title(titles[i]) ax.set_aspect('equal') ax.set_axis_off() # im = ax.imshow(stats_x[i].squeeze(0), # interpolation='bilinear', cmap=self.args.cmap) im = ax.contourf(stats_x[i].squeeze(0), 50, cmap='jet') for c in im.collections: c.set_edgecolor("face") c.set_linewidth(0.000000000001) cbar = plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04, format=ticker.ScalarFormatter(useMathText=True)) cbar.formatter.set_powerlimits((0, 0)) cbar.ax.yaxis.set_offset_position('left') cbar.update_ticks() plt.tight_layout(pad=0.5, w_pad=0.5, h_pad=0.5) out_stats_dir = self.post_dir + '/out_stats' mkdir(out_stats_dir) plt.savefig(out_stats_dir + '/input_MC.pdf', di=300, bbox_inches='tight') plt.close(fig) print("Done plotting input MC, num of training: {}".format(self.ntrain)) # MC surrogate predictions y_pred_EE, y_pred_VE, y_pred_EV, y_pred_VV = self.model.propagate( self.mc_loader, n_samples=self.n_samples, temperature=self.temperature, var_samples=var_samples) print('Done MC predictions') # plot the 4 output stats # plot the predictive mean plot_MC2(out_stats_dir, sample_mean_y, y_pred_EE, y_pred_VE, True, self.ntrain, manual_scale=manual_scale) # plot the predictive var plot_MC2(out_stats_dir, sample_var_y, y_pred_EV, y_pred_VV, False, self.ntrain) # save for MATLAB plotting scipy.io.savemat(out_stats_dir + '/out_stats.mat', {'sample_mean': sample_mean_y.cpu().numpy(), 'sample_var': sample_var_y.cpu().numpy(), 'y_pred_EE': y_pred_EE.cpu().numpy(), 'y_pred_VE': y_pred_VE.cpu().numpy(), 'y_pred_EV': y_pred_EV.cpu().numpy(), 'y_pred_VV': y_pred_VV.cpu().numpy()}) print('saved output stats to .mat file') def plot_dist(self, num_loc): """Plot distribution estimate in `num_loc` locations in the domain, which are chosen by Latin Hypercube Sampling. Args: num_loc (int): number of locations where distribution is estimated """ print('Plotting distribution estimate.................................') assert num_loc > 0, 'num_loc must be greater than zero' locations = lhs(2, num_loc, criterion='c') print('Locations selected by LHS: \n{}'.format(locations)) # location (ndarray): [0, 1] x [0, 1]: N x 2 idx = (locations * self.imsize).astype(int) print('Propagating...') pred, target = [], [] for _, (x_mc, t_mc) in enumerate(self.mc_loader): x_mc = x_mc.to(self.device) # S x B x C x H x W y_mc = self.model.sample(x_mc, n_samples=self.n_samples, temperature=self.temperature) # S x B x C x n_points pred.append(y_mc[:, :, :, idx[:, 0], idx[:, 1]]) # B x C x n_points target.append(t_mc[:, :, idx[:, 0], idx[:, 1]]) # S x M x C x n_points --> M x C x n_points pred = torch.cat(pred, dim=1).mean(0).cpu().numpy() print('pred size: {}'.format(pred.shape)) # M x C x n_points target = torch.cat(target, dim=0).cpu().numpy() print('target shape: {}'.format(target.shape)) dist_dir = self.post_dir + '/dist_estimate' mkdir(dist_dir) for loc in range(locations.shape[0]): print(loc) fig, _ = plt.subplots(1, 3, figsize=(12, 4)) for c, ax in enumerate(fig.axes): sns.kdeplot(target[:, c, loc], color='b', ls='--', label='Monte Carlo', ax=ax) sns.kdeplot(pred[:, c, loc], color='r', label='Surrogate', ax=ax) ax.legend() plt.savefig(dist_dir + '/loc_({:.5f}, {:.5f}).pdf' .format(locations[loc][0], locations[loc][1]), dpi=300) plt.close(fig) def plot_reliability_diagram(self, label='Conditional Glow', save_time=True): print("Plotting reliability diagram..................................") # percentage: p # p_list = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95] p_list = np.linspace(0.01, 0.99, 10) freq = [] n_channels = self.mc_loader.dataset[0][1].shape[0] for p in p_list: count = 0 numels = 0 for batch_idx, (input, target) in enumerate(self.mc_loader): # only evaluate 2000 of the MC data to save time if save_time and batch_idx > 4: continue pred_mean, pred_var = self.model.predict(input.to(self.device), n_samples=self.n_samples, temperature=self.temperature) interval = scipy_norm.interval(p, loc=pred_mean.cpu().numpy(), scale=pred_var.sqrt().cpu().numpy()) count += ((target.numpy() >= interval[0]) & (target.numpy() <= interval[1])).sum(axis=(0, 2, 3)) numels += target.numel() / n_channels print('p: {}, {} / {} = {}'.format(p, count, numels, np.true_divide(count, numels))) freq.append(np.true_divide(count, numels)) reliability_dir = self.post_dir + '/uncertainty_quality' mkdir(reliability_dir) freq = np.stack(freq, 0) for i in range(freq.shape[-1]): plt.figure() plt.plot(p_list, freq[:, i], 'r', label=label) plt.xlabel('Probability') plt.ylabel('Frequency') x = np.linspace(0, 1, 100) plt.plot(x, x, 'k--', label='Ideal') plt.legend(loc='upper left') plt.savefig(reliability_dir + f"/reliability_diagram_{i}.pdf", dpi=300) plt.close() reliability = np.zeros((p_list.shape[0], 1+n_channels)) reliability[:, 0] = p_list reliability[:, 1:] = freq np.savetxt(reliability_dir + "/reliability_diagram.txt", reliability) plt.close() def test_metric(self, handle_nan=True): relative_l2, err2 = [], [] num_nan_inf = 0 for batch_idx, (input, target) in enumerate(self.test_loader): input, target = input.to(self.device), target.to(self.device) pred_mean, pred_var = self.model.predict(input, n_samples=self.n_samples, temperature=self.temperature) # handling nan, inf if handle_nan: exception = torch.isnan(pred_mean) + torch.isinf(pred_mean) exception = exception.sum((1, 2, 3)).gt(0) normal = (1 - exception) # print(normal) normal_idx = torch.arange(len(normal)).to(self.device).masked_select(normal).to(torch.long) # print(normal_idx) pred_mean, target = pred_mean.index_select(0, normal_idx), target.index_select(0, normal_idx) num_nan_inf += exception.sum() # print(pred_mean.shape) err2_sum = torch.sum((pred_mean - target) ** 2, [-1, -2]) relative_l2.append(torch.sqrt(err2_sum / (target ** 2).sum([-1, -2]))) err2.append(err2_sum) relative_l2 = to_numpy(torch.cat(relative_l2, 0).mean(0)) r2_score = 1 - to_numpy(torch.cat(err2, 0).sum(0)) / self.y_test_variation print(relative_l2) print(r2_score) np.savetxt(self.post_dir + '/nrmse_test.txt', relative_l2) np.savetxt(self.post_dir + '/r2_test.txt', r2_score) if handle_nan: abnormal_rate = num_nan_inf / len(self.test_loader.dataset) print(f'num_nan_inf: {num_nan_inf}') print(f'abnormal rate: {abnormal_rate:.6f}') np.savetxt(self.post_dir + '/log_stats.txt', [num_nan_inf, len(self.test_loader.dataset), abnormal_rate]) <file_sep>"""Physics-constraint surrogates. Convolutional Encoder-decoder networks for surrogate modeling of darcy flow. Assume the PDEs and boundary conditions are known. Train the surrogate with mixed residual loss, instead of maximum likelihood. 5 runs per setup setup: - training with different number of input: 512, 1024, 2048, 4096, 8192 with mini-batch size 8, 8, 16, 32, 32, correpondingly. - metric: relative L2 error, i.e. NRMSE R^2 score - Other default hyperparameters in __init__ of Parser class """ import torch import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import numpy as np from models.codec import DenseED from models.darcy import conv_constitutive_constraint as constitutive_constraint from models.darcy import conv_continuity_constraint as continuity_constraint from models.darcy import conv_boundary_condition as boundary_condition # my loss from models.darcy import cc1 from models.darcy import cc2 from models.darcy import cc2new from models.darcy import bc from models.darcy import cc1_new, bc_new from torch.utils.data import DataLoader, TensorDataset from utils.image_gradient import SobelFilter from utils.load import load_data from utils.misc import mkdirs, to_numpy from utils.plot import plot_prediction_det, save_stats from utils.practices import OneCycleScheduler, adjust_learning_rate, find_lr import time import argparse import random from pprint import pprint import json import sys import matplotlib.pyplot as plt import h5py from FEA_simp import ComputeTarget from mytest import testsample, get_testsample plt.switch_backend('agg') class Parser(argparse.ArgumentParser): def __init__(self): super(Parser, self).__init__(description='Learning surrogate with mixed residual norm loss') self.add_argument('--exp-name', type=str, default='codec/mixed_residual', help='experiment name') self.add_argument('--exp-dir', type=str, default="./experiments", help='directory to save experiments') # codec self.add_argument('--blocks', type=list, default=[8, 12, 8], help='list of number of layers in each dense block') self.add_argument('--growth-rate', type=int, default=16, help='number of output feature maps of each conv layer within each dense block') self.add_argument('--init-features', type=int, default=48, help='number of initial features after the first conv layer') self.add_argument('--drop-rate', type=float, default=0., help='dropout rate') self.add_argument('--upsample', type=str, default='nearest', choices=['nearest', 'bilinear']) # data self.add_argument('--data-dir', type=str, default="./datasets", help='directory to dataset') self.add_argument('--data', type=str, default='grf_kle512', choices=['grf_kle512', 'channelized']) self.add_argument('--ntrain', type=int, default=7003, help="number of training data") self.add_argument('--ntest', type=int, default=512, help="number of validation data") self.add_argument('--imsize', type=int, default=64) # training self.add_argument('--run', type=int, default=1, help='run instance') self.add_argument('--epochs', type=int, default=50000, help='number of epochs to train') self.add_argument('--lr', type=float, default=1e-3, help='learnign rate') self.add_argument('--lr-div', type=float, default=2., help='lr div factor to get the initial lr') self.add_argument('--lr-pct', type=float, default=0.3, help='percentage to reach the maximun lr, which is args.lr') self.add_argument('--weight-decay', type=float, default=0., help="weight decay") self.add_argument('--weight-bound', type=float, default=10, help="weight for boundary loss") self.add_argument('--batch-size', type=int, default=64, help='input batch size for training') self.add_argument('--test-batch-size', type=int, default=64, help='input batch size for testing') self.add_argument('--seed', type=int, default=1, help='manual seed used in Tensor') self.add_argument('--cuda', type=int, default=0, choices=[0, 1, 2, 3], help='cuda index') # logging self.add_argument('--debug', action='store_true', default=True, help='debug or verbose') self.add_argument('--ckpt-epoch', type=int, default=None, help='which epoch of checkpoints to be loaded') self.add_argument('--ckpt-freq', type=int, default=2000, help='how many epochs to wait before saving model') self.add_argument('--log-freq', type=int, default=1, help='how many epochs to wait before logging training status') self.add_argument('--plot-freq', type=int, default=50, help='how many epochs to wait before plotting test output') self.add_argument('--plot-fn', type=str, default='imshow', choices=['contourf', 'imshow'], help='plotting method') def parse(self): args = self.parse_args() hparams = f'{args.data}_ntrain{args.ntrain}_run{args.run}_bs{args.batch_size}_lr{args.lr}_epochs{args.epochs}' if args.debug: hparams = 'debug/' + hparams args.run_dir = args.exp_dir + '/' + args.exp_name + '/' + hparams args.ckpt_dir = args.run_dir + '/checkpoints' # print(args.run_dir) # print(args.ckpt_dir) mkdirs(args.run_dir, args.ckpt_dir) # assert args.ntrain % args.batch_size == 0 and \ # args.ntest % args.test_batch_size == 0 if args.seed is None: args.seed = random.randint(1, 10000) print("Random Seed: ", args.seed) random.seed(args.seed) torch.manual_seed(args.seed) print('Arguments:') pprint(vars(args)) with open(args.run_dir + "/args.txt", 'w') as args_file: json.dump(vars(args), args_file, indent=4) return args if __name__ == '__main__': args = Parser().parse() device = torch.device(f"cuda:{args.cuda}" if torch.cuda.is_available() else "cpu") args.train_dir = args.run_dir + '/training' args.pred_dir = args.train_dir + '/predictions' mkdirs(args.train_dir, args.pred_dir) model = DenseED(in_channels=1, out_channels=2, imsize=args.imsize, blocks=args.blocks, growth_rate=args.growth_rate, init_features=args.init_features, drop_rate=args.drop_rate, out_activation=None, upsample=args.upsample).to(device) if args.debug: # print(model) pass # if start from ckpt if args.ckpt_epoch is not None: ckpt_file = args.run_dir + f'/checkpoints/model_epoch{args.ckpt_epoch}.pth' model.load_state_dict(torch.load(ckpt_file, map_location='cpu')) print(f'Loaded ckpt: {ckpt_file}') print(f'Resume training from epoch {args.ckpt_epoch + 1} to {args.epochs}') # load data if args.data == 'grf_kle512': train_hdf5_file = args.data_dir + \ f'/{args.imsize}x{args.imsize}/kle512_lhs10000_train.hdf5' test_hdf5_file = args.data_dir + \ f'/{args.imsize}x{args.imsize}/kle512_lhs1000_val.hdf5' ntrain_total, ntest_total = 10000, 1000 elif args.data == 'channelized': train_hdf5_file = args.data_dir + \ f'/{args.imsize}x{args.imsize}/channel_ng64_n4096_train.hdf5' test_hdf5_file = args.data_dir + \ f'/{args.imsize}x{args.imsize}/channel_ng64_n512_test.hdf5' ntrain_total, ntest_total = 4096, 512 assert args.ntrain <= ntrain_total, f"Only {args.ntrain_total} data "\ f"available in {args.data} dataset, but needs {args.ntrain} training data." assert args.ntest <= ntest_total, f"Only {args.ntest_total} data "\ f"available in {args.data} dataset, but needs {args.ntest} test data." # modif its data with h5py.File(train_hdf5_file, 'r') as f: # x_data = f['input'][:ndata] x_data = f['input'][:args.ntrain,:,:20,:40] x_data = (x_data - x_data.min()) /( x_data.max() - x_data.min()) print("ComputeTarget....") # label_data = ComputeTarget(x_data) # print("ComputeTarget finish") # data_tuple = (torch.FloatTensor(x_data), torch.FloatTensor(label_data).to(device)) # train_loader = DataLoader(TensorDataset(*data_tuple), # batch_size=args.batch_size, shuffle=True, drop_last=True) # train_loader, _ = load_data(train_hdf5_file, args.ntrain, args.batch_size, # only_input=True, return_stats=False) test_loader, test_stats = load_data(test_hdf5_file, args.ntest, args.test_batch_size, only_input=False, return_stats=True) y_test_variation = test_stats['y_variation'] print(f'Test output variation per channel: {y_test_variation}') data = np.loadtxt("data/rho20x40_SIMP_Edge.txt", dtype=np.float32) # [bs, 1, 20, 40] data = data.reshape(-1,1,40,20).transpose([0,1,3,2]) data_u = np.loadtxt("data/dis20x40_SIMP_Edge.txt", dtype=np.float32) data_s = np.loadtxt("data/stress20x40_SIMP_Edge.txt", dtype=np.float32) # filter data result_label = [] for ind,i in enumerate(data_u): if i.max()>5000 or i.min()<-1000: pass else: result_label.append(ind) data = data[result_label] data_u = data_u[result_label] data_s = data_s[result_label] ref_u0 = torch.from_numpy(data_u).unsqueeze(1).to(device) ref_uy = ref_u0[:,:,range(1,1722,2)] ref_ux = ref_u0[:,:,range(0,1722,2)] ref_s0 = torch.from_numpy(data_s).unsqueeze(1).to(device) ref_sx = ref_s0[:,:,range(0,2583,3)] ref_sy = ref_s0[:,:,range(1,2583,3)] ref_sxy = ref_s0[:,:,range(2,2583,3)] # [bs, 5, 21, 41] ref = torch.cat([ref_ux, ref_uy, ref_sx, ref_sy, ref_sxy],1).view(-1,5,41,21).permute(0,1,3,2) # data_tuple = (torch.FloatTensor(data),) data_tuple = (torch.FloatTensor(data), ref) # torch.FloatTensor(data_dis)) train_loader = DataLoader(TensorDataset(*data_tuple), batch_size=args.batch_size, shuffle=True, drop_last=True) optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay) scheduler = OneCycleScheduler(lr_max=args.lr, div_factor=args.lr_div, pct_start=args.lr_pct) sobel_filter = SobelFilter(args.imsize, correct=False, device=device) # 1/4 conv to make output (21x41) => (20x40) WEIGHTS_2x2 = torch.FloatTensor( np.ones([1,1,2,2])/4 ).to(device) # post_y = F.conv2d(y_test, WEIGHTS_2x2, stride=1, padding=0, bias=None) n_out_pixels = test_loader.dataset[0][1].numel() print(f'Number of out pixels per image: {n_out_pixels}') logger = {} logger['loss_train'] = [] logger['loss_pde1'] = [] logger['loss_pde2'] = [] logger['loss_b'] = [] logger['u_l2loss'] = [] logger['s_l2loss'] = [] print('Start training...................................................') start_epoch = 1 if args.ckpt_epoch is None else args.ckpt_epoch + 1 tic = time.time() # step = 0 total_steps = args.epochs * len(train_loader) print(f'total steps: {total_steps}') for epoch in range(start_epoch, args.epochs + 1): model.train() # if epoch == 30: # print('begin finding lr') # logs,losses = find_lr(model, train_loader, optimizer, loss_fn, # args.weight_bound, init_value=1e-8, final_value=10., beta=0.98) # plt.plot(logs[10:-5], losses[10:-5]) # plt.savefig(args.train_dir + '/find_lr.png') # sys.exit(0) relative_l2 = [] loss_train, mse = 0., 0. for batch_idx, (input, target) in enumerate(train_loader, start=1): input = input.to(device) model.zero_grad() output = model(input) # post output # o0 = F.conv2d(output[:,[0]], WEIGHTS_2x2, stride=1, padding=0, bias=None) # o1 = F.conv2d(output[:,[1]], WEIGHTS_2x2, stride=1, padding=0, bias=None) # o2 = F.conv2d(output[:,[2]], WEIGHTS_2x2, stride=1, padding=0, bias=None) # o3 = F.conv2d(output[:,[3]], WEIGHTS_2x2, stride=1, padding=0, bias=None) # o4 = F.conv2d(output[:,[4]], WEIGHTS_2x2, stride=1, padding=0, bias=None) # output_post = torch.cat([o0,o1,o2,o3,o4],1) # new target = target[:,:2,:,:] loss_pde = cc1_new(input, output, device) loss_pde1 = loss_pde # loss_boundary = 0 loss_boundary = bc_new(output) # old # loss_pde1 = cc1(input, output, output_post, sobel_filter, device) # # loss_pde2 = cc2(output_post, sobel_filter) # loss_pde2 = cc2new(output, sobel_filter) # loss_pde = 2*loss_pde1 + 3*loss_pde2 # loss_boundary = bc(output, output_post) loss = 200*loss_pde + loss_boundary # * args.weight_bound loss.backward() # uapr = output.view(input.shape[0],5,-1) # e2 = torch.sum((output[:,:2] - target[:,:2]) ** 2 , [-1, -2]) # torch.sqrt(e2 / (target[:,:2] ** 2).sum([-1, -2])) err2_sum = torch.sum((output - target) ** 2, [-1, -2]) # relative_l2.append(err2_sum) relative_l2.append(torch.sqrt(err2_sum / (target ** 2).sum([-1, -2]) ) ) # lr scheduling step = (epoch - 1) * len(train_loader) + batch_idx pct = step / total_steps lr = scheduler.step(pct) adjust_learning_rate(optimizer, lr) optimizer.step() loss_train += loss.item() loss_train /= batch_idx relative_l2 = to_numpy(torch.cat(relative_l2, 0).mean(0)) relative_u = np.mean(relative_l2[:2]) relative_s = np.mean(relative_l2[2:]) print(f'Epoch {epoch}, lr {lr:.6f}') # print(f'Epoch {epoch}: training loss: {loss_train:.6f}, pde1: {loss_pde1:.6f}, pde2: {loss_pde2:.6f}, '\ # # f'dirichlet {loss_dirichlet:.6f}, nuemann {loss_neumann:.6f}') # f'boundary: {loss_boundary:.6f}, relative-u: {relative_u: .5f}, relative_s: {relative_s: .5f}') print(f'Epoch {epoch}: training loss: {loss_train:.6f}, pde1: {loss_pde1:.6f} '\ f'boundary: {loss_boundary:.6f}, relative-u: {relative_u: .5f}') if epoch % args.log_freq == 0: logger['loss_train'].append(loss_train) logger['loss_pde1'].append(loss_pde1) # logger['loss_pde2'].append(loss_pde2) logger['loss_b'].append(loss_boundary) logger['u_l2loss'].append(relative_u) logger['s_l2loss'].append(relative_s) if epoch % args.ckpt_freq == 0: torch.save(model, args.ckpt_dir + "/model_epoch{}.pth".format(epoch)) sampledir = args.ckpt_dir + "/model{}".format(epoch) mkdirs((sampledir)) get_testsample(model, sampledir, data, ref) # testsample(args.ckpt_dir + "/model_epoch{}.pth".format(epoch), sampledir) # with torch.no_grad(): # test(epoch) tic2 = time.time() print(f'Finished training {args.epochs} epochs with {args.ntrain} data ' \ f'using {(tic2 - tic) / 60:.2f} mins') metrics = ['loss_train','loss_pde1', 'loss_b', 'u_l2loss', 's_l2loss'] # metrics = ['loss_train','loss_pde1', 'loss_pde2', 'loss_b', 'u_l2loss', 's_l2loss'] save_stats(args.train_dir, logger, *metrics) args.training_time = tic2 - tic args.n_params, args.n_layers = model.model_size with open(args.run_dir + "/args.txt", 'w') as args_file: json.dump(vars(args), args_file, indent=4)
ed6d19fdfff3fe8ca7faa38ffa0032ce94a838f6
[ "Python", "Shell" ]
14
Shell
qq519043202/pde-surrogate
d59ca48a2bd7e1bcb375e11b56def36e163db948
d0282c8eb7bee130dd268beb44b0de56aa3e19dd
refs/heads/master
<file_sep>import scrabble # Print the longest word where every character is unique. I used a # Set for this which we'll talk about today. # Don't worry: you didn't miss anything if you don't know what a set # is. We didn't teach it, but if you are reading this, you get a # bonus! # A set is a container like a list or a dict, except that *each # element can be stored only once*. Think of it like the keys of a # dict, except there isn't any value associated with each key. I use # Sets to count digits below. Feel free to look up the Set online and # try it in the interpreter. new_words = [] for word in scrabble.wordlist: local_chars = {} if len(word) == len(set(word)): # Wait what!? See if you can figure out why this works. new_words.append(word) # Reuse my code for longest word, (in this case, the code to track all occurences) from the # advanced solution. longest_so_far = [] length_of_longest_word = 0 for word in new_words: if len(word) > length_of_longest_word: length_of_longest_word = len(word) longest_so_far = [word] elif len(word) == length_of_longest_word: longest_so_far.append(word) print(longest_so_far)
a9afc78836264ab604655f4bcbabf5bec4e04990
[ "Python" ]
1
Python
yaping8512/wordplay-cdsw-solutions
7b538ea99568eb4511b2b92e3f55193796017866
60f801352072e8a6eb889517444f107876ccf65a
refs/heads/master
<file_sep>'use strict'; /** * @ngdoc function * @name angularjsApp.controller:MainCtrl * @description * # MainCtrl * Controller of the angularjsApp */ angular.module('angularjsApp') .controller('MainCtrl', function () { this.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; }) .controller('movieController', function () { var ctrl = this; ctrl.movies = []; ctrl.addMovie = function (movie) { ctrl.movies.push({ name: movie }); }; })
8890aca7dee954adec57a327a3f78b12f4c2fad0
[ "JavaScript" ]
1
JavaScript
sdegroot/angularjs-demo
5413d6d9b71dfe624da0a39e1f9093109d560acb
0d1994706155690f1e18a55cc630231958f34e7a
refs/heads/master
<file_sep>module Forem class View < ActiveRecord::Base belongs_to :topic belongs_to :user, :class_name => Forem.user_class.to_s validates :topic_id, :presence => true end end <file_sep>FactoryGirl.define do factory :topic, :class => Forem::Topic do |t| t.subject "FIRST TOPIC" t.forum {|f| f.association(:forum) } t.user {|u| u.association(:user) } t.posts_attributes { [Factory.attributes_for(:post)] } trait :approved do state 'approved' end factory :approved_topic, :traits => [:approved] end end <file_sep>require 'refinery/generators' module Refinery class ForemGenerator < ::Refinery::Generators::EngineInstaller source_root File.expand_path('../../../../', __FILE__) engine_name "refinerycms-forem" end end<file_sep>user = Forem.user_class.first unless user.nil? forum = Forem::Forum.find_or_create_by_title( :category_id => Forem::Category.first.id, :title => "Default", :description => "Default forem created by install") topic = Forem::Topic.find_or_initialize_by_subject("Welcome to Forem") topic.forum = forum topic.user = user topic.posts_attributes = [{:text => "Hello World", :user_id => user.id}] topic.save! end <file_sep>require 'spec_helper' describe Forem do describe ".default_gravatar" do it "can be set and retrieved" do Forem.default_gravatar = "foo" Forem.default_gravatar.should eq("foo") Forem.default_gravatar = nil Forem.default_gravatar.should be_nil end end describe ".default_gravatar_image" do it "can be set and retrieved" do Forem.default_gravatar_image = "foo" Forem.default_gravatar_image.should eq("foo") Forem.default_gravatar_image = nil Forem.default_gravatar_image.should be_nil end end describe ".email_from_address" do it "can be set and retrieved" do Forem.email_from_address = "foo" Forem.email_from_address.should eq("foo") Forem.email_from_address = nil Forem.email_from_address.should be_nil end end end <file_sep>class CreateUsers < ActiveRecord::Migration create_table :users, :force => true do |t| t.string :email, :default => "", :null => false t.string :encrypted_password, :limit => 128, :default => "", :null => false t.string :login t.boolean :forem_admin, :default => false t.string :forem_state, :default => "pending_review" end add_index :users, :email, :unique => true end <file_sep>module Forem module TopicsHelper def link_to_latest_post(post) text = "#{time_ago_in_words(post.created_at)} #{t("ago_by")} #{post.user}" link_to text, forum_topic_path(post.topic.forum, post.topic, :anchor => "post-#{post.id}") end end end <file_sep>require 'spec_helper' describe "forum moderators" do before do sign_in(Factory(:admin)) user = Factory(:user, :login => "bob") group = Factory(:group, :name => "The Mods") group.members << user forum = Factory(:forum) visit edit_admin_forum_path(forum) end it "can assign a group as a moderators" do check "The Mods" click_button "Update Forum" within(".forum .moderators") do page.should have_content("The Mods") end end end <file_sep>require 'spec_helper' describe "category permissions" do let!(:category) { Factory(:category) } let!(:forum) { Factory(:forum, :category => category) } context "without ability to read a category" do before do User.any_instance.stub(:can_read_forem_category?).and_return(false) end it "can't see the categories it can't access" do visit forums_path page.should_not have_content("Welcome to Forem!") end it "can't visit a particular category" do visit category_path(category) access_denied! end end context "with default permissions" do it "can see the category" do visit root_path within(".category h2") do page.should have_content("Test Category") end end end end <file_sep>require 'spec_helper' describe "moderation" do context" of topics" do let!(:moderator) { Factory(:user, :login => "moderator") } let!(:group) do group = Factory(:group) group.members << moderator group.save! group end let!(:forum) { Factory(:forum) } let!(:topic) { Factory(:topic, :forum => forum) } before do forum.moderators << group sign_in(moderator) end context "singular moderation" do it "can approve a topic by a new user" do visit forum_topic_path(forum, topic) within("#topic_moderation") do choose "Approve" click_button "Moderate" end flash_notice!("The selected topic has been moderated.") page.should_not have_content("This topic is currently pending review.") end end end end <file_sep>require 'spec_helper' describe 'topic permissions' do let!(:forum) { Factory(:forum) } let!(:topic) { Factory(:approved_topic, :forum => forum) } let!(:user) { Factory(:user) } context "without permission to create a new topic" do before do sign_in(user) User.any_instance.stub(:can_create_forem_topics?).and_return(false) end it "users can't see the link to create a topic" do visit forum_path(forum) assert_no_link_for!("New topic") end it "cannot visit the new action to create a new topic" do visit new_forum_topic_path(forum) access_denied! end end context "with, but then without permission to create a new topic" do before do sign_in(user) end it "cannot create a new topic" do # User has permission to do so when they navigate to the new page visit new_forum_topic_path(forum) fill_in "Subject", :with => "This is a subject" fill_in "Text", :with => "And this is some text" # And then doesn't User.any_instance.stub(:can_create_forem_topics?).and_return(false) click_button "Create Topic" access_denied! end end context "without permission to read a topic" do before do sign_in(user) User.any_instance.stub(:can_read_forem_topic?).and_return(false) end it "cannot subscribe to a topic" do visit subscribe_forum_topic_path(topic.forum, topic) access_denied! end end end
4ff416e9d10b934eb8de691c9ecf0e85f341b099
[ "Ruby" ]
11
Ruby
regedarek/forem
5ec19afa2e5be598365c8f5f4b16166acc328cd5
9c2515d21cc25111a9277f6f641bedaa05efa7ff
refs/heads/master
<repo_name>codacy-acme/ruby-test<file_sep>/Gemfile source 'https://rubygems.org' gem 'minitest' gem 'rake' gem 'rubocop' gem 'rubocop-performance' gem 'rubocop-rspec' gem 'rubocop-shopify'<file_sep>/lib/cool_program.rb # frozen_string_literal: true # The coolest program class CoolProgram attr_reader :coolness def initialize @coolness = 11 end end REGISTRATION_CHECKBOX = '[data-testid=page_registration]' puts "Coolness: #{CoolProgram.new.coolness}/10"
a4bcdb2a063269fa92635dc820af9db7861c915a
[ "Ruby" ]
2
Ruby
codacy-acme/ruby-test
3523e367d8ac213f35bcfa64119d4e02708bc542
55872c1e18482a8fdb0eecd52120d5cee3522713
refs/heads/master
<repo_name>matkoson/FCC-markdown-previewer<file_sep>/src/CodeInput.js import React, { Component } from "react"; class CodeInput extends Component { render(props) { let fullScreen = this.props.fullScreen ? this.props.fullScreen : null; return ( <div className={`code-input border-shadow-black ${fullScreen}`}> <div className="window-title "> <div className="window-title-logo"> <i className="fa fa-fire" /> <h2>Editor</h2> </div> <div className="window-title-arrows"> <i id="arrow-input" className="fa fa-arrows-alt" onClick={e => this.props.arrowHandler(e)} /> </div> </div> <textarea id="editor" className="code-input__input" defaultValue={this.props.defaultValue} onChange={event => this.props.inputHandler(event.target.value)} /> </div> ); } } export default CodeInput; <file_sep>/src/PreviewWindow.js import React, { Component } from "react"; class PreviewWindow extends Component { state = {}; render() { let fullScreen = this.props.fullScreen ? this.props.fullScreen : null; return ( <div className={`preview-window border-shadow-black ${fullScreen}`}> <div className="window-title"> <div className="window-title-logo"> <i className="fa fa-fire" /> <h1>Previewer</h1> </div> <div className="window-title-arrows"> <i id="arrow-preview" className="fa fa-arrows-alt" onClick={e => this.props.arrowHandler(e)} /> </div> </div> <div id="preview" className="parsed-input" dangerouslySetInnerHTML={{ __html: this.props.parsedInput && this.props.parsedInput }} /> </div> ); } } export default PreviewWindow; <file_sep>/src/App.js import React, { Component } from "react"; import "./App.sass"; import CodeInput from "./CodeInput"; import PreviewWindow from "./PreviewWindow"; import marked from "marked"; class App extends Component { constructor(props) { super(props); this.state = { // inputValue: // '<h1>Header</h1>\n <h2>Sub-header</h2>\n <a href="www.realmadryt.pl">Anchor</a>\n <code>Inline Code</code>\n <code>``multicode``</code>\n <li>List item</li>\n <blockquote>blockquote</blockquote>\n <img href ="../public/favicon.ico" />\n <strong>bolded</strong> ', inputValue: "# Heading\n## Sub-heading\n\n[This is a link.](https://www.freecodecamp.org)\n\n`This is inline code.`\n\n```\nThis is a code block.\n```\n\nThis is a list:\n* item 1\n* item 2\n* item 3\n\n> This is a blockquote.\n\n![Free Code Camp logo](https://dl.dropbox.com/s/lei6k4qqrvo23qb/freeCodeCamp-alternative.png)\n\n**This is bolded text.** aaa ", parsedInput: "", fullScreen: "" }; this.handleTextareaInput = this.handleTextareaInput.bind(this); this.handleArrowClick = this.handleArrowClick.bind(this); } componentDidMount() { this.setState({ parsedInput: marked(this.state.inputValue) }); } handleTextareaInput(input) { const parsed = marked(String(input)); this.setState({ parsedInput: parsed }); } handleArrowClick(input) { if (!this.state.fullScreen) { this.setState({ fullScreen: input.target.id }); } else { this.setState({ fullScreen: "" }); } } render() { if (!this.state.fullScreen) { return ( <main className="app"> <CodeInput arrowHandler={this.handleArrowClick} defaultValue={this.state.inputValue} inputHandler={this.handleTextareaInput} /> <PreviewWindow arrowHandler={this.handleArrowClick} parsedInput={this.state.parsedInput} /> </main> ); } else if (this.state.fullScreen === "arrow-input") { return ( <main className="app"> <CodeInput fullScreen="full-screen" arrowHandler={this.handleArrowClick} defaultValue={this.state.inputValue} inputHandler={this.handleTextareaInput} /> </main> ); } else if (this.state.fullScreen === "arrow-preview") { return ( <main className="app"> <PreviewWindow fullScreen="full-screen" arrowHandler={this.handleArrowClick} parsedInput={this.state.parsedInput} /> </main> ); } } } export default App;
92c378fff39b3e07ac5703cb2fad6048db153f5e
[ "JavaScript" ]
3
JavaScript
matkoson/FCC-markdown-previewer
bd0ab8f892c5d0ab3a47ca8e621688de7c9a74b4
65d0a7e3272cd6ff8b3528473fd5bad7b38ade46
refs/heads/master
<file_sep>from flask import Flask, render_template,request,redirect,url_for,session from app2 import get_all, insert_data_book,delete_data_book,update_book_by_id,get_book_by_id from app3 import get_all2,insert_data_user app = Flask(__name__) app.secret_key = '<KEY>' @app.route('/DN', methods = ['POST']) def post_login(): tk = request.form.get('namedn') mk = request.form.get('mkdn') if tk == "admin" or "ntduc" and mk == "admin" or "12051998": session['namedn'] = request.form.get('namedn') return redirect(url_for("indexTC")) else: return "Login false" @app.route('/AddBook', methods = ['POST']) def post(): book_name = request.form.get('names') book_link = request.form.get('link') book_sl = request.form.get('sl') book_nxb = request.form.get('nxb') book_price = int(request.form.get('price')) if 'namedn' in session: insert_data_book(book_name,book_link,book_sl,book_nxb,book_price) return redirect(url_for("indexAB")) else: return "Yêu cầu đăng nhập để thực hiện chức năng này" @app.route('/AddCardUser', methods = ['POST']) def posrUser(): user_name = request.form.get('namek') user_sex = request.form.get('sex') user_bi = request.form.get('birth') user_cmt = request.form.get('cmt') user_job = request.form.get('job') user_le = request.form.get('level') user_wp = request.form.get('wp') user_phone = request.form.get('phone') user_ct = request.form.get('ct') user_ci = request.form.get('city') user_add = request.form.get('add') user_ti = request.form.get('time') if 'namedn' in session: insert_data_user(user_name,user_sex,user_bi,user_cmt,user_job,user_le,user_wp,user_phone,user_ct,user_ci,user_add,user_ti) return redirect(url_for('indexKH')) else: return "Yêu cầu đăng nhập để thực hiện chức năng này" @app.route('/edit_book/<book_id>',methods = ['POST']) def put_book(book_id): bo_names = request.form.get('names') bo_li = request.form.get('link') bo_nxb = request.form.get('nxb') bo_sl = int(request.form.get('sl')) bo_price = int(request.form.get('price')) update_book_by_id(book_id,bo_names, bo_li, bo_nxb, bo_sl, bo_price) return redirect(url_for('indexAB')) @app.route('/edit_book/<book_id>') def func_name(book_id): if 'namedn' in session: bo = get_book_by_id(book_id) return render_template('edit_book.html',book = bo) else: return "Yêu cầu đăng nhập để thực hiện chức năng này" @app.route('/AddCardUser') def indexKH(): return render_template("cate_list2.html") @app.route('/TrangChu') def indexTC(): return render_template("cate_list3.html") @app.route('/AddBook') def indexAB(): return render_template("cate_list.html",dulieu = get_all()) @app.route('/delete_book/<book_id>') def delete(book_id): if 'namedn' in session: delete_data_book(book_id) return redirect(url_for("indexAB")) else: return "Yêu cầu đăng nhập để thực hiện chức năng này" @app.route('/NQ') def indexNQ(): return render_template("cate_list4.html") @app.route('/QD') def indexQD(): return render_template("cate_list5.html") @app.route('/IFU') def indexIFU(): return render_template("cate_list6.html",dulieu2 = get_all2()) @app.route('/DN') def index(): return render_template("index.html") @app.route('/out') def method_name(): del session ['namedn'] return redirect(url_for("indexTC")) if __name__ == '__main__': app.run(host='127.0.0.1', port=8000, debug=True) <file_sep>import pymongo from bson.objectid import ObjectId uri = "mongodb://mrd198:<EMAIL>:35957/c4e32thuvien" client = pymongo.MongoClient(uri) db = client.c4e32thuvien collection = db.sach def get_all(): return list(collection.find()) def insert_data_book(names,link,sl,nxb,price): collection.insert_one({"names":names,"link":link,"sl":sl,"nxb":nxb,"price":price}) def update_book_by_id(book_id,names,link,nxb,sl,price): collection.update_one({"_id":ObjectId(book_id)}, {"$set":{"names":names,"link":link,"nxb":nxb,"sl":sl,"price":price}}) def get_book_by_id(book_id): return collection.find_one({"_id": ObjectId(book_id)}) def delete_data_book(book_id): collection.delete_one({"_id": ObjectId(book_id)}) <file_sep>(function(n) { n.extend(n.ui.tabs.prototype, { rotation: null, rotationDelay: null, continuing: null, rotate: function(n, i) { var r = this, f = this.options, u, e; return (n > 1 || r.rotationDelay === null) && n !== undefined && (r.rotationDelay = n), i !== undefined && (r.continuing = i), u = r._rotate || (r._rotate = function(t) { clearTimeout(r.rotation); r.rotation = setTimeout(function() { var n = f.selected; r.select(++n < r.anchors.length ? n : 0) }, n); t && t.stopPropagation() }), e = r._unrotate || (r._unrotate = i ? function() { t = f.selected; u() } : function(n) { n.clientX && r.rotate(null) }), n ? (this.element.bind("tabsshow", u), this.anchors.bind(f.event + ".tabs", e), u()) : (clearTimeout(r.rotation), this.element.unbind("tabsshow", u), this.anchors.unbind(f.event + ".tabs", e), delete this._rotate, delete this._unrotate), n === 1 && (n = r.rotationDelay), this }, pause: function() { var n = this, t = this.options; n.rotate(0) }, unpause: function() { var n = this, t = this.options; n.rotate(1, n.continuing) } }) })(jQuery);<file_sep>import pymongo uri = "mongodb://mrd198:1<EMAIL>998d@ds<EMAIL>:35957/c4e32thuvien" client = pymongo.MongoClient(uri) db = client.c4e32thuvien collection = db.user def get_all2(): return list(collection.find()) def insert_data_user(namek,sex,birth,cmt,job,level,wp,phone,ct,city,add,time): collection.insert_one({'namek':namek,'sex':sex,'birth': birth,'cmt':cmt,'job':job,'level':level,'wp':wp,'phone':phone, 'ct':ct,'city':city,'add':add,'time':time})
85f73d1b65fd2ecd8dacfbf1ddc0fef539538853
[ "JavaScript", "Python" ]
4
Python
qltv123/QLTV
0ad16da19ff77bd5e50511424f9d7034b6a16914
bc6268870900c405e786c8a6beae8a1d981cf23f
refs/heads/master
<file_sep># TYPES class Number < Struct.new(:value) def to_s value.to_s end def evaluate(environment) self end def inspect "<<#{self}>>" end end class Boolean < Struct.new(:value) def to_s value.to_s end def evaluate(environment) self end def inspect "<<#{self}>>" end end class Variable < Struct.new(:name) def to_s name.to_s end def evaluate(environment) environment[name] end def inspect "<<#{self}>>" end end # OPERATIONS class Add < Struct.new(:left, :right) def to_s "#{left} + #{right}" end def inspect "<<#{self}>>" end def evaluate(environment) Number.new(left.evaluate(environment).value + right.evaluate(environment).value) end end class Multiply < Struct.new(:left, :right) def to_s "#{left} * #{right}" end def inspect "<<#{self}>>" end def evaluate(environment) Number.new(left.evaluate(environment).value * right.evaluate(environment).value) end end class LessThan < Struct.new(:left, :right) def to_s "#{left} < #{right}" end def inspect "<<#{self}>>" end def evaluate(environment) Boolean.new(left.evaluate(environment).value < right.evaluate(environment).value) end end # STATEMENTS class DoNothing def to_s "literally_doing_nothing" end def inspect "<<#{self}>>" end def ==(other_statement) other_statement.instance_of?(DoNothing) end def evaluate(environment) environment end end class Assign < Struct.new(:name, :expression) def to_s "#{name} = #{expression}" end def inspect "<<#{self}>>" end def evaluate(environment) environment.merge({ name => expression.evaluate(environment)}) end end class If < Struct.new(:condition, :consequence, :alternative) def to_s "if (#{condition}) { #{consequence} } else { #{alternative} }" end def inspect "<<#{self}>>" end def evaluate(environment) case condition.evaluate(environment) when Boolean.new(true) consequence.evaluate(environment) when Boolean.new(false) alternative.evaluate(environment) end end end class Sequence < Struct.new(:first, :second) def to_s "#{first}; #{second}" end def inspect "<<#{self}>>" end def evaluate(environment) second.evaluate(first.evaluate(environment)) end end class While < Struct.new(:condition, :body) def to_s "while (#{condition}) { #{body} }" end def inspect "<<#{self}>>" end def evaluate(environment) case condition.evaluate(environment) when Boolean.new(true) evaluate(body.evaluate(environment)) when Boolean.new(false) environment end end end Number.new(23).evaluate({}) Variable.new(:x).evaluate({ x: Number.new(42)}) LessThan.new( Add.new(Variable.new(:x), Number.new(2)), Variable.new(:y) ).evaluate({ x: Number.new(2), y: Number.new(7) }) statement = While.new( LessThan.new(Variable.new(:x), Variable.new(:y)), Assign.new(:x, Multiply.new(Variable.new(:x), Number.new(2))) ) statement.evaluate({ x: Number.new(1), y: Number.new(5) }) statement.evaluate({ x: Number.new(1), y: Number.new(64) }) statement.evaluate({ x: Number.new(-1), y: Number.new(64) }) <file_sep># UComp Code re-implementations for the book [Understanding Computation: From Simple Machines to Impossible Programs](http://computationbook.com/) with Ruby.
7c23070bb0de772b3c2d14f482d93fac677a5cea
[ "Markdown", "Ruby" ]
2
Ruby
Otomadmt/UComp
2e6ab11904b772166a3f7f77aa341c8fa8d3c3a8
e76968b49edb327fcf2b05b4f1022e7f44d3b848
refs/heads/main
<repo_name>iamrhm/react-vis-demo<file_sep>/src/components/playground/validation.js import chroma from "chroma-js"; export function validate(data) { const obj = { minNegativeColor: data.minNegativeColor, maxNegativeColor: data.maxNegativeColor, minPositiveColor: data.minPositiveColor, maxPositiveColor: data.maxPositiveColor }; const inValidInputs = []; Object.keys(obj).forEach(key => { if(!chroma.valid(obj[key])) { inValidInputs.push(obj[key]); } }); if(inValidInputs.length) { return { isValid: false, messages: `${inValidInputs.join(', ')}, are/is not valid color input(s)` } } return { isValid: true, messages: null } }<file_sep>/src/components/json-editor/index.jsx import React from 'react'; import './style.css'; const objSchema = { "Sector": "", "Return Attribution": "", "Free Float": "" } const JSONEditor = ({ inputJSON, updateJSON = () => {} }) => { const [state, updateState] = React.useState(inputJSON || []); const [isUpdated, toggleUpdate] = React.useState(false); const updateJsonValue = (e, key, valuePointer) => { const newState = [...state]; newState[valuePointer] = {...newState[valuePointer], [key]: e.target.value } updateState(newState); toggleUpdate(true); } const addValue = (e) => { e.stopPropagation(); updateState([...state, objSchema]); toggleUpdate(true); } const deleteJsonValue = (index) => { const newState = [...state].filter((data,idx) => idx !== index); updateState(newState); toggleUpdate(true); } const getJSONHolder = ( obj = { ...objSchema }, valuePointer = 0 ) => { return ( <div className="json-blocks"> <span className="display-key-value braces">&#123;</span> <br/> <div className="json-values-display"> { Object.keys(obj).map((key, index) => ( <div className="row" key={index}> <span className="display-key-value">{key}:</span> <span> <input type="text" className="json-input-box" value={obj[key]} onChange={(e) => updateJsonValue(e, key, valuePointer)} /> </span> </div> )) } </div> <span className="display-key-value braces">&#125;</span> <div className="json-delete" onClick={() => deleteJsonValue(valuePointer)}> <span className="material-icons icon-styles"> delete </span> </div> </div> ) } return ( <div className='json-editor-container'> { state.map((obj, index)=> ( <React.Fragment key={index} > {getJSONHolder(obj, index)} </React.Fragment> ) ) } <div className="add-button-container"> <div className="add-button" onClick={(e) => addValue(e)}> <span className="material-icons add-style"> add </span> </div> { isUpdated && <div className='json-editor-message' onClick={() => { updateJSON(state) toggleUpdate(false) }} > validate </div> } </div> </div> ) } export default JSONEditor;<file_sep>/src/components/playground/index.jsx import React from 'react'; import { validate } from './validation'; import JSONEditor from '../json-editor'; import './style.css' function reducer(state, action){ console.log(action.playground) switch(action.type){ case 'update-min-negative-color': return {...state, minNegativeColor: action.payload} case 'update-max-negative-color': return {...state, maxNegativeColor: action.payload} case 'update-min-positive-color': return {...state, minPositiveColor: action.payload} case 'update-max-positive-color': return {...state, maxPositiveColor: action.payload} case 'update-width': return {...state, width: action.payload} case 'update-height': return {...state, height: action.payload} case 'update-is-single-color': return {...state, isSingleColor: action.payload} case 'update-state': return {...state, ...action.payload} case 'update-json-data': return {...state, jsonData : action.payload} default: return state; } } const Playground = ({ playgroundData, updateData = () => {} }) => { const [state, dispatch] = React.useReducer(reducer, playgroundData); const [errorMessage, updateErrorMessage] = React.useState(); const handleInputChange = (e) => { const name = e.target.name; let value = e.target.type === 'checkbox' ? e.target.checked : e.target.value; if(name === 'update-width' || name === 'update-height') { value = Number(value); } dispatch({ type: name, payload: value }) } const handleUpdate = () => { debugger const validationOp = validate(state); if(validationOp.isValid) { updateData({...state}); } updateErrorMessage(validationOp.messages); } const updateInputJSON = (data) => { dispatch({ type: 'update-json-data', payload: data }); } React.useEffect(()=> { dispatch({ type: 'update-state', payload: playgroundData }) },[playgroundData]); return( <div className="user-playground-container"> <div className="user-input-container"> <div className="input-label"> Enter treemap dimensions (width x height) <br /> <div className="input-label-hints"> Also responsive </div> </div> <div className="input-panels"> <input type="number" value={state.width} name="update-width" onChange={handleInputChange} className="input-box" /> <input type="number" value={state.height} name="update-height" onChange={handleInputChange} className="input-box" /> </div> </div> <div className="user-input-container"> <div className="input-label"> Enter negative color{state.isSingleColor ? '' : 's min - max'} </div> <div className="input-label-hints"> Enter hex, name color or rgb value, <br/> Yes we are enough smart to understand what you want 😎 </div> <div className="input-panels"> <input type="text" value={state.minNegativeColor} name="update-min-negative-color" onChange={handleInputChange} className="input-box" /> { !state.isSingleColor && ( <input type="text" value={state.maxNegativeColor} name="update-max-negative-color" onChange={handleInputChange} className="input-box" /> ) } </div> </div> <div className="user-input-container"> <div className="input-label"> Enter positive color{state.isSingleColor ? '' : 's min - max'} </div> <div className="input-label-hints"> Enter hex, name color or rgb value, <br/> Yes we are enough smart to understand what you want 😎 </div> <div className="input-panels"> <input type="text" value={state.minPositiveColor} name="update-min-positive-color" onChange={handleInputChange} className="input-box" /> { !state.isSingleColor && ( <input type="text" value={state.maxPositiveColor} name="update-max-positive-color" onChange={handleInputChange} className="input-box" /> ) } </div> </div> <div className="user-input-container check-box-container"> <input type="checkbox" name="update-is-single-color" className="input-checkbox" defaultChecked={state.isSingleColor} onChange={handleInputChange} /> <div className="checkbox-label"> I would like to try out with one color each, <br /> because I am boring 😐 </div> </div> <div className="user-input-container"> <div className="input-label"> Edit the below JSON </div> <JSONEditor inputJSON={state.jsonData} updateJSON={updateInputJSON} /> </div> <div className="user-input-container align-center"> <button className="update-button" onClick={handleUpdate} > Leviosa 💫 </button> </div> { errorMessage && ( <div className="user-input-container align-center danger"> {errorMessage} </div> ) } </div> ) } export default Playground;<file_sep>/src/App.js import React from 'react'; import './App.css'; import Graph from './components/graph' import Playground from './components/playground'; import mockData from './__mocks__/data.json'; const initialState = { width: 600, height: 400, minNegativeColor: 'red', maxNegativeColor: 'darkred', minPositiveColor: 'green', maxPositiveColor: 'darkgreen', isSingleColor: false, jsonData: mockData, } const App = () => { const [state, updateState] = React.useState(initialState); return ( <div className="container"> <div className="graph-container"> <Graph graphData={state} /> </div> <div className="playground-container"> <Playground playgroundData={state} updateData={updateState} /> </div> </div> ) } export default App; <file_sep>/src/components/graph/index.jsx import React from 'react'; import { Treemap } from 'react-vis'; import chroma from 'chroma-js'; import '../../../node_modules/react-vis/dist/style.css'; import './style.css'; const Graph = ({ graphData }) => { const [dimensions, updateDimensions] = React.useState({ width: graphData.width, height: graphData.height, }) const treemapRef = React.useRef(null); const negativeColorPallet = React.useRef(); const positiveColorPallet = React.useRef(); const negativeColorRange = React.useRef(); const positiveColorRange = React.useRef(); const populateColorValues = (data) => { if(data < 0) { negativeColorPallet.current.data.add(data); } else { positiveColorPallet.current.data.add(data); } } const getTitleComponent = (title, displayValue, size) => { const returnAttribute = (Number(displayValue.split('%')[0])); const getSign = () => { if(Math.sign(returnAttribute) < 0 ) { return ( <span className="material-icons "> arrow_drop_down </span> ) } else if (Math.sign(returnAttribute > 0)) { return ( <span className="material-icons "> arrow_drop_up </span> ) } else { return null; } } return ( <div className="title-holder"> <div className="title">{title}</div> <div className="display-value"> {getSign()} &nbsp; {Math.abs(returnAttribute)} </div> <div className="display-size"> <span className="material-icons box-icon-style"> crop_5_4 </span> &nbsp; {Number(size).toFixed(2)} </div> </div> ) } const getLeafData = () => { negativeColorPallet.current = { data: new Set(), colors: () => {} }; positiveColorPallet.current = { data: new Set(), colors: () => {} }; let leafData = (graphData.jsonData || []).map((data) => { const freeFloat = !isNaN(Number(data['Free Float'])) ? Number(data['Free Float']) : Number(`${data['Free Float']}`.split(',').join('')); const returnAttribute = (Number(data['Return Attribution'].split('%')[0])); populateColorValues(returnAttribute); return { title: getTitleComponent( data['Sector'], data['Return Attribution'], Math.abs(freeFloat * (returnAttribute+1)) ), size: Math.abs(freeFloat * (returnAttribute+1)), label: data['Sector'], returnAttribute: returnAttribute } }); negativeColorPallet.current.data = [...negativeColorPallet.current.data].sort(); positiveColorPallet.current.data = [...positiveColorPallet.current.data].sort(); leafData.sort((a, b) => (a.returnAttribute > b.returnAttribute ? -1 : 1)) negativeColorPallet.current.colors = chroma.scale( [graphData.minNegativeColor, graphData.maxNegativeColor] ); positiveColorPallet.current.colors = chroma.scale( [graphData.minPositiveColor, graphData.maxPositiveColor] ); negativeColorRange.current = new Set(); positiveColorRange.current = new Set(); leafData = leafData.map((data) => { if(data.returnAttribute < 0) { if(graphData.isSingleColor) { data.color = chroma(graphData.minNegativeColor).hex(); } else { data.color = negativeColorPallet.current.colors( (negativeColorPallet.current.data .findIndex(el => el === data.returnAttribute) + 1) / negativeColorPallet.current.data.length ) } negativeColorRange.current.add(data.color); } else if(data.returnAttribute > 0) { if(graphData.isSingleColor) { data.color = chroma(graphData.minPositiveColor).hex(); } else { data.color = positiveColorPallet.current.colors( (positiveColorPallet.current.data .findIndex(el => el === data.returnAttribute) + 1) / positiveColorPallet.current.data.length ) } positiveColorRange.current.add(data.color); } else { data.color = '#e4e4e4' } return data; }); return leafData; } const myData = { title: "", colorType: 'literal', children: getLeafData(), } const getColorPalette = () => { return( <> <div className="color-details"> <div className="title-color-palette"> Negative Colors <br/> {!graphData.isSingleColor ? '(minInputVal → maxInputVal)' : ''} </div> <div className="negative-palette"> { [...negativeColorRange.current] .map((color, idx) => ( <div className="color-box" key={idx} style={{ backgroundColor: color }} /> )) } </div> </div> <div className="color-details"> <div className="title-color-palette"> Positive Colors <br/> {!graphData.isSingleColor ? '(minInputVal → maxInputVal)' : ''} &nbsp; </div> <div className="positive-palette"> { [...positiveColorRange.current] .map((color, idx) => ( <div className="color-box" key={idx} style={{ backgroundColor: color }} /> )) } </div> </div> </> ) } const handResize = () => { if(treemapRef.current) { const width = treemapRef.current.clientWidth; const height = treemapRef.current.clientHeight; updateDimensions({ width, height }) } } React.useEffect(()=>{ window.addEventListener("resize", handResize); window.addEventListener("orientationchange", handResize); return () => { window.removeEventListener("resize", handResize); window.removeEventListener("orientationchange", handResize); } },[]) React.useLayoutEffect(()=>{ if(treemapRef.current) { const width = treemapRef.current.clientWidth; const height = treemapRef.current.clientHeight; updateDimensions({ width, height }) } }, []); return ( <div className="graph-fold"> <div className="wrapper"> <div className="header"> Nifty 50 Sector Performance </div> <div className="treemap-container" ref={treemapRef}> <Treemap animation={true} className='treemap-demo-container' colorType='literal' width={dimensions.width} height={dimensions.height} data={myData} mode='squarify' style= {{ "border": '2px solid #ffffff', "display": "flex", "justifyContent": "center", "alignItems": "center", }} margin= {0} hideRootNode={true} /> </div> </div> <div className="color-pallet"> {getColorPalette()} </div> </div> ); } export default Graph;
08209864c66dff01c68016a5c3543948b73ca749
[ "JavaScript" ]
5
JavaScript
iamrhm/react-vis-demo
98cdf826b9ec67244d2cf74db3f0c9a1d7a417e7
ea5497dc2cbdf1a4a8db381da65cbc34733ce04a
refs/heads/master
<file_sep>import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Date; class Repository { private final String Db_url = "jdbc:mysql://localhost/inventory_management?useLegacyDatetimeCode=false&serverTimezone=Asia/Kathmandu"; // GET DATA FROM THE DATABASE //GET ITEM DATA FROM DATABASE // GET ALL THE INFORMATION OF A PARTICULAR ITEM FROM A PARTICULAR STORE ItemModel getParticularItemData(String storeName, String itemName){ try{ String sql = "SELECT * FROM " + changeNameToDBFormat(storeName); Connection con = DriverManager.getConnection(Db_url, "root", ""); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql); while(rs.next()){ if(reformItemName(rs.getString("Item")).equals(itemName)){ return new ItemModel( storeName, itemName, rs.getDouble("Quantity"), rs.getDouble("Price"), reformItemName(rs.getString("Type"))); } } }catch(Exception exception){ exception.printStackTrace(); } return new ItemModel( storeName, itemName, 0.0, 0.0, "" ); } // GET USER DATA FROM DATABASE // GET NAMES OF ALL EXISTING USERS ArrayList<String> getUserNames(){ ArrayList<String> users = new ArrayList<>(); try{ Connection con = DriverManager.getConnection(Db_url, "root", ""); String sql = "SELECT Username FROM user_info"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ users.add(rs.getString("Username")); } }catch(Exception exception){ exception.printStackTrace(); } return users; } // GET ALL THE INFORMATION OF A PARTICULAR USER UserModel getParticularUserData(String userName) { try { String sql = "SELECT * from user_info"; Connection con = DriverManager.getConnection(Db_url, "root", ""); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql); while (rs.next()) { if (rs.getString("Username").equals(userName)) { return new UserModel(userName, rs.getString("PhoneNumber"), rs.getString("Address"), rs.getString("Password")); } } } catch (Exception exception) { exception.printStackTrace(); } return null; } // GET LIST OF ALL WISH LIST ITEMS OF USER ArrayList<ItemModel> getUserWishListData(String userName){ try{ ArrayList<ItemModel> list = new ArrayList<>(); Connection con = DriverManager.getConnection(Db_url,"root", ""); String sql = "SELECT * from " + getWishListName(userName); PreparedStatement st = con.prepareStatement(sql); ResultSet rs = st.executeQuery(); while(rs.next()){ String sql2 = "SELECT * from " + changeNameToDBFormat(rs.getString("StoreName")); PreparedStatement st2 = con.prepareStatement(sql2); ResultSet rs2 = st2.executeQuery(); while (rs2.next()) { if(rs2.getString("Item").equals(rs.getString("Item"))){ list.add(new ItemModel(rs.getString("StoreName"),reformItemName(rs.getString("Item")),rs2.getDouble("Quantity"),rs2.getDouble("Price"),reformItemName(rs2.getString("Type")))); break; } } } return list; }catch(Exception exception){ exception.printStackTrace(); } return null; } // GET ALL THE DATA OF USER TRANSACTIONS // PASS getUserBuyListName() METHOD FOR NOT DELIVERED ITEMS LIST // PASS getUserDeliveredListName() DELIVERED ITEMS LIST ArrayList<UserReportModel> getUserBuyListData(String userName){ try{ ArrayList<UserReportModel> list = new ArrayList<>(); Connection con = DriverManager.getConnection(Db_url,"root", ""); String sql = "SELECT * from " + userName; PreparedStatement st = con.prepareStatement(sql); ResultSet rs = st.executeQuery(); while(rs.next()){ list.add(new UserReportModel( reformItemName(rs.getString("Item")), rs.getDouble("Quantity"), rs.getDouble("Price"), rs.getString("Type"), rs.getString("StoreName"), rs.getTimestamp("BuyDate")) ); } return list; }catch(Exception exception){ exception.printStackTrace(); } return null; } // GET STORE DATA FROM DATABASE // GET NAMES OF ALL EXISTING STORES ArrayList<String> getStoreNames(){ ArrayList<String> stores = new ArrayList<>(); try{ Connection con = DriverManager.getConnection(Db_url, "root", ""); String sql = "SELECT StoreName FROM stores_info"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ stores.add(rs.getString("StoreName")); } }catch(Exception exception){ exception.printStackTrace(); } return stores; } // GET ALL THE INFORMATION OF A PARTICULAR STORE List<ItemModel> getParticularStoreData(String storeName){ try{ List<ItemModel> list = new ArrayList<>(); String sql = "SELECT * from " + changeNameToDBFormat(storeName); Connection con = DriverManager.getConnection(Db_url, "root", ""); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql); ItemModel item; while(rs.next()){ item = new ItemModel( storeName, reformItemName(rs.getString("Item")), rs.getDouble("Quantity"), rs.getDouble("Price"), reformItemName(rs.getString("Type")) ); list.add(item); } return list; }catch(Exception exception){ exception.printStackTrace(); } return null; } // GET ALL THE INFORMATION OF ALL EXISTING STORES List<ItemModel> getAllStoreData(){ ArrayList<String> stores = getStoreNames(); List<ItemModel> items = new ArrayList<>(); ItemModel item; try{ Connection con = DriverManager.getConnection(Db_url, "root",""); for(String store: stores){ String sql = "SELECT * FROM " + changeNameToDBFormat(store); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql); while(rs.next()){ item = new ItemModel( store, reformItemName(rs.getString("Item")), rs.getDouble("Quantity"), rs.getDouble("Price"), reformItemName(rs.getString("Type")) ); items.add(item); } } }catch (Exception exception){ exception.printStackTrace(); } return items; } // GET SALES REPORT LIST OF A PARTICULAR STORE ArrayList<StoreReportModel> getStoreReportData(String storeName){ try{ ArrayList<StoreReportModel> list = new ArrayList<>(); Connection con = DriverManager.getConnection(Db_url,"root", ""); String sql = "SELECT * from " + getStoreReportListName(storeName); PreparedStatement st = con.prepareStatement(sql); ResultSet rs = st.executeQuery(); while(rs.next()){ list.add(new StoreReportModel( reformItemName(rs.getString("Item")), rs.getDouble("Quantity"), rs.getDouble("Price"), rs.getString("Type"), rs.getTimestamp("SalesDate"), rs.getString("BuyerName"), rs.getString("BuyerAddress"), rs.getString("BuyerPhoneNumber")) ); } return list; }catch(Exception exception){ exception.printStackTrace(); } return null; } // ADD DATA TO THE DATABASE // ADD DATA TO USER DATABASE // ADD INFORMATION OF NEW USER int addUserData(UserModel model){ try{ Connection con = DriverManager.getConnection(Db_url, "root", ""); String sql = "INSERT into user_info (UserName, PhoneNumber, Address, Password)" + "VALUES(?,?,?,?)"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setString(1,model.getUserName()); stmt.setString(2,model.getPhoneNumber()); stmt.setString(3,model.getAddress()); stmt.setString(4,model.getPassword()); return stmt.executeUpdate(); }catch(Exception exception){ exception.printStackTrace(); return 0; } } // ADD ITEM TO USER WISH LIST int addItemToWishList(ItemModel itemModel,String userName){ try{ Connection con = DriverManager.getConnection(Db_url, "root", ""); String sql = "INSERT into " + getWishListName(userName) + " (Item,StoreName)" + " VALUES(?,?)"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setString(1,itemModel.getItem().toLowerCase()); stmt.setString(2,itemModel.getStoreName()); return stmt.executeUpdate(); }catch(Exception exception){ exception.printStackTrace(); } return 0; } private final int DELIVERY_TIME = 10; // Delivery Time in Minutes // TO CHANGE DELIVERY TIME, CHANGE THE {DELIVERY_TIME} CONSTANT ABOVE // CHECK WHETHER THE ITEMS HAVE BEEN DELIVERED TO THE USER // AND CALL METHODS TO UPDATE THE TABLES RESPECTIVELY void deliverItemsToUser(String userName){ try{ Connection con = DriverManager.getConnection(Db_url,"root",""); String sql = "SELECT * from " + getUserBuyListName(userName); PreparedStatement st = con.prepareStatement(sql); ResultSet rs = st.executeQuery(); while(rs.next()){ if((DateStuff.getIntegerTime(rs.getTimestamp("BuyDate").toString()) + DELIVERY_TIME) < DateStuff.getIntegerTime((new Timestamp((new Date()).getTime())).toString().substring(0,19))){ addBoughtItemToUserDeliveredList(rs,userName,con); removeBoughtItemFromUserBuyList(rs.getInt("Id"),userName,con); } } }catch(Exception exception){ exception.printStackTrace(); } } // ADD ITEM TO userBuyList WHEN USER BUYS ITEMS void addBoughtItemToUserBuyList(double quantity,ItemModel itemModel, UserModel userModel){ try{ Connection con = DriverManager.getConnection(Db_url,"root",""); String sql = "INSERT into " + getUserBuyListName(userModel.getUserName()) + " (Item, Quantity, Price, `Type`, StoreName, BuyDate)" + "VALUES(?,?,?,?,?,?)"; PreparedStatement st = con.prepareStatement(sql); st.setString(1,itemModel.getItem()); st.setDouble(2,quantity); st.setDouble(3,itemModel.getPrice()); st.setString(4,itemModel.getType()); st.setString(5,itemModel.getStoreName()); st.setObject(6,new Timestamp((new Date()).getTime())); st.execute(); }catch (Exception exception){ exception.printStackTrace(); } } // ADD ITEM TO THE USER DELIVERED LIST FROM userBuyList AFTER DELIVERY TIME HAS PASSED void addBoughtItemToUserDeliveredList(ResultSet rs, String userName,Connection con){ try{ String sql = "INSERT into " + getUserDeliveredListName(userName) + " (Item, Quantity, Price, `Type`, StoreName, BuyDate)" + "VALUES(?,?,?,?,?,?)"; PreparedStatement st = con.prepareStatement(sql); st.setString(1,rs.getString("Item")); st.setDouble(2,rs.getDouble("Quantity")); st.setDouble(3,rs.getDouble("Price")); st.setString(4,rs.getString("Type")); st.setString(5,rs.getString("StoreName")); st.setObject(6,rs.getTimestamp("BuyDate")); st.execute(); }catch (Exception exception){ exception.printStackTrace(); } } // ADD DATA TO STORE DATABASE // ADD INFORMATION OF NEW STORE int addStoreData(StoreModel model){ try { Connection con = DriverManager.getConnection(Db_url, "root", ""); String sql = "INSERT into stores_info (StoreName, StoreOwnerName, PhoneNumber, Address, Password)" + "VALUES(?,?,?,?,?)"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setString(1,model.storeName); stmt.setString(2,model.storeOwnerName); stmt.setString(3,model.phoneNumber); stmt.setString(4,model.address); stmt.setString(5,model.password); return stmt.executeUpdate(); }catch(Exception exception){ exception.printStackTrace(); return 0; } } // ADD NEW STOCK ITEMS TO STORE DATABASE int addStoreItems(ItemModel model){ try{ String sqlExtract = "SELECT * FROM " + changeNameToDBFormat(model.getStoreName()); Connection con = DriverManager.getConnection(Db_url, "root", ""); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sqlExtract); while(rs.next()){ if(rs.getString("Item").toLowerCase().equals(model.getItem().toLowerCase())){ String sql = "UPDATE " + changeNameToDBFormat(model.getStoreName()) + " SET Quantity = ? , Price = ?"+ " WHERE Item = ?"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setDouble(1,rs.getDouble("Quantity")+model.getQuantity()); stmt.setDouble(2, model.getPrice()); stmt.setString(3, model.getItem().toLowerCase()); stmt.executeUpdate(); return 1; } } String sqlInsert = "INSERT INTO " + changeNameToDBFormat(model.getStoreName()) + "(Item, Quantity, Price, Type)" + "VALUES(?,?,?,?)"; PreparedStatement stmt = con.prepareStatement(sqlInsert); stmt.setString(1, model.getItem().toLowerCase()); stmt.setDouble(2,model.getQuantity()); stmt.setDouble(3,model.getPrice()); stmt.setString(4, model.getType().toLowerCase()); stmt.executeUpdate(); return 2; }catch (Exception exception){ exception.printStackTrace(); } return 0; } // ADD ITEM TO storeReportList WHEN A USER BUYS AN ITEM FROM THE STORE void addSoldItemToReportList(double quantity,ItemModel itemModel, UserModel userModel){ try{ Connection con = DriverManager.getConnection(Db_url,"root",""); String sql = "INSERT into " + getStoreReportListName(itemModel.getStoreName()) + " (Item, Quantity, Price, `Type`, SalesDate, BuyerName, BuyerAddress, BuyerPhoneNumber) " + "VALUES(?,?,?,?,?,?,?,?)"; PreparedStatement st = con.prepareStatement(sql); st.setString(1,itemModel.getItem()); st.setDouble(2,quantity); st.setDouble(3,itemModel.getPrice()); st.setString(4,itemModel.getType()); st.setObject(5,new Timestamp((new Date()).getTime())); st.setString(6,userModel.getUserName()); st.setString(7,userModel.getAddress()); st.setString(8,userModel.getPhoneNumber()); st.execute(); }catch(Exception exception){ exception.printStackTrace(); } } // REMOVE ITEMS FROM DATABASE // REMOVE ITEMS FROM USER BUY LIST AFTER DELIVERY TIME HAS PASSED void removeBoughtItemFromUserBuyList(int id, String userName,Connection con){ try{ String sql = "DELETE FROM " + getUserBuyListName(userName) + " WHERE id = " + id; PreparedStatement st = con.prepareStatement(sql); st.executeUpdate(); }catch(Exception exception){ exception.printStackTrace(); } } // REDUCE STOCK OF THE STORE FROM WHERE THE ITEMS ARE BOUGHT AND // CALL METHODS TO ADD THE BOUGHT ITEM TO USER AND STORE REPORT LIST int transact(String item, String storeName, Double quantity, Double totalQuantity){ try { Connection con = DriverManager.getConnection(Db_url, "root", ""); String sql = "UPDATE " + changeNameToDBFormat(storeName) + " SET Quantity = ? " + "WHERE Item = ?"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setDouble(1, totalQuantity - quantity); stmt.setString(2, item); stmt.executeUpdate(); String userName = Home.getLoggedInUser(); ItemModel itemModel = getParticularItemData(storeName,item); UserModel userModel = getParticularUserData(userName); addSoldItemToReportList(quantity,itemModel,userModel); addBoughtItemToUserBuyList(quantity,itemModel,userModel); return 1; }catch(Exception exception){ exception.printStackTrace(); } return 0; } // NEW ACCOUNT TABLE CREATIONS // CREATE ALL NECESSARY TABLES FOR USER ACCOUNT void createUserAccount(String userName){ try{ Connection con = DriverManager.getConnection(Db_url, "root", ""); String sql = "CREATE TABLE " + "user_"+ changeNameToDBFormat(userName) + "(Id INT PRIMARY KEY AUTO_INCREMENT," + " Item VARCHAR(100)," + " Quantity DOUBLE," + " Price DOUBLE," + " Type TEXT," + " Store VARCHAR(100)," + " PurchaseDate VARCHAR(100)," + " Delivered INT)"; PreparedStatement stmt = con.prepareStatement(sql); stmt.executeUpdate(); String sql2 = "CREATE TABLE " + getWishListName(userName) + "(Id INT PRIMARY KEY AUTO_INCREMENT," + " Item VARCHAR(100)," + " StoreName VARCHAR(100))"; PreparedStatement stmt2 = con.prepareStatement(sql2); stmt2.executeUpdate(); String sql3 = "CREATE TABLE " + getUserBuyListName(userName) + "(Id INT PRIMARY KEY AUTO_INCREMENT," + " Item VARCHAR(100)," + " Quantity DOUBLE," + " Price DOUBLE," + " Type TEXT," + " StoreName VARCHAR(100)," + " BuyDate DATETIME)"; PreparedStatement stmt3 = con.prepareStatement(sql3); stmt3.executeUpdate(); String sql4 = "CREATE TABLE " + getUserDeliveredListName(userName) + "(Id INT PRIMARY KEY AUTO_INCREMENT," + " Item VARCHAR(100)," + " Quantity DOUBLE," + " Price DOUBLE," + " Type TEXT," + " StoreName VARCHAR(100)," + " BuyDate DATETIME)"; PreparedStatement stmt4 = con.prepareStatement(sql4); stmt4.executeUpdate(); }catch(Exception exception){ exception.printStackTrace(); } } // CREATE ALL NECESSARY TABLES FOR STORE ACCOUNT void createStoreAccount(String storeName){ try{ Connection con = DriverManager.getConnection(Db_url, "root", ""); String sql = "CREATE TABLE " + changeNameToDBFormat(storeName) + "(Id INT PRIMARY KEY AUTO_INCREMENT," + " Item VARCHAR(100)," + " Quantity DOUBLE," + " Price DOUBLE," + " Type TEXT)"; PreparedStatement stmt = con.prepareStatement(sql); stmt.executeUpdate(); String sql2 = "CREATE TABLE " + getStoreReportListName(storeName) + "(Id INT PRIMARY KEY AUTO_INCREMENT," + " Item VARCHAR(100)," + " Quantity DOUBLE," + " Price DOUBLE," + " Type TEXT," + " SalesDate DATETIME," + " BuyerName VARCHAR(100)," + " BuyerAddress VARCHAR(100)," + " BuyerPhoneNumber TEXT)"; PreparedStatement stmt2 = con.prepareStatement(sql2); stmt2.executeUpdate(); }catch(Exception exception){ exception.printStackTrace(); } } // CHECK DUPLICATES // CHECK IF THE GIVEN ITEM ALREADY EXISTS IN THE USER WISH LIST boolean checkDuplicateItemInWishList(ItemModel itemModel,String userName){ try{ Connection con = DriverManager.getConnection(Db_url, "root", ""); String sql = "SELECT * from " + getWishListName(userName); PreparedStatement st = con.prepareStatement(sql); ResultSet rs = st.executeQuery(); while(rs.next()){ if(itemModel.getItem().toLowerCase().equals(rs.getString("Item").toLowerCase()) && itemModel.getStoreName().toLowerCase().equals(rs.getString("StoreName").toLowerCase())){ return true; } } }catch(Exception exception){ exception.printStackTrace(); } return false; } // CHECK IF THE GIVEN STORE NAME ALREADY EXISTS boolean checkDuplicateStoreName(String name){ String []stores = getStoreNames().toArray(new String[0]); for(String store: stores){ if(name.equals(store)){ return false; } } return true; } // CHECK IF THE GIVEN USER NAME ALREADY EXISTS boolean checkDuplicateUserName(String name){ String []users = getUserNames().toArray(new String[0]); for(String user: users){ if(name.equals(user)){ return false; } } return true; } // CHECK IF THE SAME ITEM IS PROVIDED WITH DIFFERENT TYPE boolean checkDuplicateItemWithDifferentType(String storeName, String item, String type){ try{ Connection con = DriverManager.getConnection(Db_url, "root", ""); String sql = "SELECT * from " + changeNameToDBFormat(storeName); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql); while(rs.next()){ if(rs.getString("Item").equals(item.toLowerCase()) && !rs.getString("Type").equals(type.toLowerCase())){ return true; } } return false; }catch(Exception exception){ exception.printStackTrace(); } return false; } // CHECK IF THE SAME ITEM IS PROVIDED WITH DIFFERENT PRICE boolean checkDuplicateItemWithDifferentPrice(String storeName, String item, String price){ try{ Connection con = DriverManager.getConnection(Db_url,"root",""); String sql = "SELECT * FROM " + changeNameToDBFormat(storeName); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql); while(rs.next()){ if(item.toLowerCase().equals(rs.getString(2).toLowerCase()) && !(Double.parseDouble(price) == (rs.getDouble(4)))){ return true; } } }catch(Exception exception){ exception.printStackTrace(); } return false; } // HELPER FUNCTIONS // RETURN DATABASE NAME FOR STORE REPORT LIST String getStoreReportListName(String storeName){ return changeNameToDBFormat(storeName)+"_report"; } // RETURN DATABASE NAME FOR USER DELIVERED LIST String getUserDeliveredListName(String userName){ return "user_" + changeNameToDBFormat(userName) + "_delivered_report"; } // RETURN DATABASE NAME FOR USER WISH LIST private String getWishListName(String userName) { return "user_" + changeNameToDBFormat(userName) + "_wishlist"; } // RETURN DATABASE NAME FOR USER BUY LIST REPORT String getUserBuyListName(String userName){ return "user_"+ changeNameToDBFormat(userName)+"_report"; } // CHANGE NAME TO DATABASE FORMAT private String changeNameToDBFormat(String storeName){ return storeName.toLowerCase().replaceAll(" ","_"); } // REFORM ITEM NAME TO DISPLAY FORMAT (FIRST LETTER OF EACH WORD CAPITAL) private String reformItemName(String item) { if(item.equals("")) return item; item = (item.substring(0,1).toUpperCase() + item.substring(1)).trim(); for(int i=0;i<item.length();i++){ if(item.substring(i,i+1).equals(" ")){ item = item.substring(0,i+1) + item.substring(i+1,i+2).toUpperCase() + item.substring(i+2); } } return item; } // VALIDATION // VALIDATE STORE LOGIN boolean checkStoreValidity(String storeName, String password){ try{ Connection con = DriverManager.getConnection(Db_url, "root", ""); String sql = "SELECT * FROM stores_info"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); while(rs.next()) { if (storeName.equals(rs.getString(2)) && password.equals(rs.getString(6))) { return true; } } }catch(Exception exception){ exception.printStackTrace(); } return false; } // VALIDATE USER LOGIN boolean checkUserValidity(String Username, String password){ try{ Connection con = DriverManager.getConnection(Db_url, "root", ""); String sql = "SELECT * FROM user_info"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); while(rs.next()) { if (Username.equals(rs.getString(2)) && password.equals(rs.getString(5))) { return true; } } }catch(Exception exception){ exception.printStackTrace(); } return false; } }<file_sep>-- phpMyAdmin SQL Dump -- version 5.0.1 -- https://www.phpmyadmin.net/ -- -- Host: 1172.16.17.32 -- Generation Time: Feb 20, 2021 at 07:37 AM -- Server version: 10.4.11-MariaDB -- PHP Version: 7.3.14 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `inventory_management` -- -- -------------------------------------------------------- -- -- Table structure for table `jaya_ram_store` -- CREATE TABLE `jaya_ram_store` ( `Id` int(11) NOT NULL, `Item` varchar(100) DEFAULT NULL, `Quantity` double DEFAULT NULL, `Price` double DEFAULT NULL, `Type` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `jaya_ram_store` -- INSERT INTO `jaya_ram_store` (`Id`, `Item`, `Quantity`, `Price`, `Type`) VALUES (1, 'pencil', 50, 30, 'stationary'), (3, 'pen', 40, 30, 'stationary'), (4, 'eraser', 30, 10, 'stationary'), (5, 'scale', 30, 20, 'stationary'), (6, 'stapler', 20, 20, 'stationary'), (7, 'glue', 15, 15, 'stationary'), (8, 'copy', 20, 30, 'stationary'), (9, 'cello tape', 20, 30, 'stationary'), (11, 'cookie', 35, 10, 'biscuit'), (12, 'marker', 15, 50, 'stationary'), (14, 'paper cutter', 35, 90, 'stationary'), (15, 'scissor', 5, 75, 'stationary'); -- -------------------------------------------------------- -- -- Table structure for table `parsuram_store` -- CREATE TABLE `parsuram_store` ( `Id` int(11) NOT NULL, `Item` varchar(100) DEFAULT NULL, `Quantity` double DEFAULT NULL, `Price` double DEFAULT NULL, `Type` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `parsuram_store` -- INSERT INTO `parsuram_store` (`Id`, `Item`, `Quantity`, `Price`, `Type`) VALUES (1, 'garlic', 30, 100, 'vegetable'), (2, 'ginger', 50, 85, 'vegetable'), (3, 'tomato', 60, 135, 'vegetable'), (4, 'oreo', 25, 75, 'biscuit'), (5, 'top', 20, 30, 'biscuit'); -- -------------------------------------------------------- -- -- Table structure for table `shreeya_store` -- CREATE TABLE `shreeya_store` ( `Id` int(11) NOT NULL, `Item` varchar(100) DEFAULT NULL, `Quantity` double DEFAULT NULL, `Price` double DEFAULT NULL, `Type` text DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `shreeya_store` -- INSERT INTO `shreeya_store` (`Id`, `Item`, `Quantity`, `Price`, `Type`) VALUES (1, 'shampoo', 5, 350, 'cosmetic'); -- -------------------------------------------------------- -- -- Table structure for table `stores_info` -- CREATE TABLE `stores_info` ( `Id` int(11) NOT NULL, `StoreName` varchar(100) NOT NULL, `StoreOwnerName` varchar(50) NOT NULL, `PhoneNumber` text NOT NULL, `Address` varchar(100) NOT NULL, `Password` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `stores_info` -- INSERT INTO `stores_info` (`Id`, `StoreName`, `StoreOwnerName`, `PhoneNumber`, `Address`, `Password`) VALUES (15, 'Jaya Ram Store', '<NAME>', '9867564534', '<PASSWORD>', '<PASSWORD>'), (16, 'Tatsam Raj Store', 'Tatsam Raj', '9856745634', 'Kalanki', 'TatsamRaj'), (17, 'Parsuram Store', 'Parsuram', '9856765456', 'Pokhara', 'Parsuram'), (20, 'Shreeya Store', '<NAME>ha', '9847384832', 'Lazimpat', 'ShreeyaShrestha'); -- -------------------------------------------------------- -- -- Table structure for table `tatsam_raj_store` -- CREATE TABLE `tatsam_raj_store` ( `Id` int(11) NOT NULL, `Item` varchar(100) DEFAULT NULL, `Quantity` double DEFAULT NULL, `Price` double DEFAULT NULL, `Type` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `tatsam_raj_store` -- INSERT INTO `tatsam_raj_store` (`Id`, `Item`, `Quantity`, `Price`, `Type`) VALUES (1, 'pencil', 10, 25, 'stationary'), (2, 'pen', 30, 20, 'stationary'), (3, 'eraser', 40, 15, 'stationary'), (4, 'scissor', 8, 50, 'stationary'), (5, 'stapler', 13, 60, 'stationary'), (6, 'stapler pins', 17, 15, 'stationary'), (7, 'potato', 15, 90, 'vegetable'); -- -- Indexes for dumped tables -- -- -- Indexes for table `jaya_ram_store` -- ALTER TABLE `jaya_ram_store` ADD PRIMARY KEY (`Id`); -- -- Indexes for table `parsuram_store` -- ALTER TABLE `parsuram_store` ADD PRIMARY KEY (`Id`); -- -- Indexes for table `shreeya_store` -- ALTER TABLE `shreeya_store` ADD PRIMARY KEY (`Id`); -- -- Indexes for table `stores_info` -- ALTER TABLE `stores_info` ADD PRIMARY KEY (`Id`); -- -- Indexes for table `tatsam_raj_store` -- ALTER TABLE `tatsam_raj_store` ADD PRIMARY KEY (`Id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `jaya_ram_store` -- ALTER TABLE `jaya_ram_store` MODIFY `Id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16; -- -- AUTO_INCREMENT for table `parsuram_store` -- ALTER TABLE `parsuram_store` MODIFY `Id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `shreeya_store` -- ALTER TABLE `shreeya_store` MODIFY `Id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `stores_info` -- ALTER TABLE `stores_info` MODIFY `Id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=26; -- -- AUTO_INCREMENT for table `tatsam_raj_store` -- ALTER TABLE `tatsam_raj_store` MODIFY `Id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>package project; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import javax.swing.*; import javax.swing.table.DefaultTableModel; public class SalesEntry { JFrame frame4=new JFrame(); double rate=93.79; void salesEntry(){ frame4.setTitle("Sales Entry Form"); JLabel l1=new JLabel("Sales Entry"); JLabel l2=new JLabel("Customer Information"); JLabel l3=new JLabel("Bill no:"); JLabel payment=new JLabel("Payment"); JLabel vatNo=new JLabel("Vat no."); JLabel phone=new JLabel("Phone:"); JTextField vatNoField=new JTextField(20); JTextField phoneField=new JTextField(20); Object []mat= {"Iron","Cement"}; Object []pay= {"Cash","Cheque"}; @SuppressWarnings("unchecked") JComboBox<String> box=new JComboBox(mat); JComboBox<String> boxPayment=new JComboBox(pay); JLabel category=new JLabel("Category"); JTextField t1=new JTextField(10); LocalDate date=LocalDate.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); JLabel l4=new JLabel("Date : "+date.format(formatter)); JLabel l5=new JLabel("Item Details:"); JLabel l6=new JLabel("Item"); JLabel l7=new JLabel("Bundle"); JLabel l8=new JLabel("Quantity"); JLabel total=new JLabel("Total"); JLabel discount=new JLabel("Discount | 0.59%"); JLabel subTotal=new JLabel("Sub Total"); JLabel exciseDuty=new JLabel("Excise Duty"); JLabel taxableAmt=new JLabel("Taxable Amount"); JLabel vat=new JLabel("VAT"); JLabel totalAmount=new JLabel("Total Amount"); JTextField totalField=new JTextField(20); JTextField discountField=new JTextField(20); JTextField subTotalField=new JTextField(20); JTextField exciseDutyField=new JTextField(20); JTextField taxableAmtField=new JTextField(20); JTextField vatField=new JTextField(20); JTextField totalAmountField=new JTextField(20); total.setBounds(360,380,100,50); totalField.setBounds(470,395,100,20); discount.setBounds(360,400,100,50); discountField.setBounds(470,415,100,20); subTotal.setBounds(360,420,100,50); subTotalField.setBounds(470,435,100,20); exciseDuty.setBounds(360,440,100,50); exciseDutyField.setBounds(470,455,100,20); taxableAmt.setBounds(360,460,100,50); taxableAmtField.setBounds(470,475,100,20); vat.setBounds(360,480,100,50); vatField.setBounds(470,495,100,20); totalAmount.setBounds(360,500,100,50); totalAmountField.setBounds(470,515,100,20); frame4.add(total); frame4.add(totalField); frame4.add(discount); frame4.add(subTotal); frame4.add(exciseDuty); frame4.add(taxableAmt); frame4.add(vat); frame4.add(totalAmount); frame4.add(discountField); frame4.add(subTotalField); frame4.add(exciseDutyField); frame4.add(taxableAmtField); frame4.add(vatField); frame4.add(totalAmountField); JTextField item=new JTextField(35); JTextField bundle=new JTextField(35); JTextField quantity=new JTextField(35); JButton add=new JButton("Add"); JButton delete=new JButton("Delete"); JButton next=new JButton("Next"); JButton clear=new JButton("Clear"); JButton close=new JButton("Close"); add.setBounds(30,600,100,20); delete.setBounds(130,600,100,20); clear.setBounds(280,600,100,20); next.setBounds(380,600,100,20); close.setBounds(520,600,100,20); category.setBounds(250,60,100,50); box.setBounds(310,75,100,20); payment.setBounds(250,80,200,50); boxPayment.setBounds(310,95,100,20); vatNo.setBounds(450,60,100,50); vatNoField.setBounds(500,80,100,20); phone.setBounds(450,80,100,50); phoneField.setBounds(500,100,100,20); l4.setBounds(80,80,200,50); l1.setBounds(50,20,100,50); l2.setBounds(70,40,200,50); l3.setBounds(80,60,100,50); l5.setBounds(50,180,100,50); l6.setBounds(120,120,150,50); item.setBounds(50,160,165,20); l7.setBounds(280,120,150,50); bundle.setBounds(215,160,170,20); l8.setBounds(450,120,150,50); quantity.setBounds(385,160,165,20); frame4.add(add); frame4.add(delete); frame4.add(clear); frame4.add(next); frame4.add(close); frame4.add(l1); frame4.add(l2); frame4.add(l3); frame4.add(t1); frame4.add(category); frame4.add(box); frame4.add(payment); frame4.add(boxPayment); frame4.add(vatNo); frame4.add(vatNoField); frame4.add(phone); frame4.add(phoneField); frame4.add(l4); frame4.add(l5); frame4.add(l6); frame4.add(l7); frame4.add(l8); frame4.add(item); frame4.add(bundle); frame4.add(quantity); JTable table=new JTable(); JScrollPane pane=new JScrollPane(); pane.setBounds(50,220,550,150); pane.getViewport().add(table); DefaultTableModel model=new DefaultTableModel(); Object columns[]= {"Item","Bundle","Quantity","Rate","Amount","Excise Amount"}; model.setColumnIdentifiers(columns); table.setModel(model); Object []row=new Object[6]; add.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(item.getText().equals("") || bundle.getText().equals("") || quantity.getText().equals("")) { }else { row[0]=item.getText(); row[1]=bundle.getText(); row[2]=quantity.getText(); row[3]=rate; row[4]=Float.parseFloat(quantity.getText())*rate; row[5]=Float.parseFloat(quantity.getText())*1.5; model.addRow(row); item.setText(""); bundle.setText(""); quantity.setText(""); item.requestFocus(); String total2=Double.toString(Float.parseFloat(quantity.getText())*rate); totalField.setText(total2); } } }); clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { model.setRowCount(0); } }); close.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub frame4.dispose(); } }); frame4.getRootPane().setDefaultButton(add); frame4.add(pane); frame4.setSize(650, 700); frame4.setLocationRelativeTo(null); frame4.setLayout(null); frame4.setVisible(true); } } <file_sep>import java.sql.Timestamp; // Created on: 3/28/2021 public class StoreReportModel { private String item; private Double quantity; private Double price; private String type; private Timestamp timestamp; private String buyerName; private String buyerAddress; private String buyerPhoneNumber; StoreReportModel(String item, Double quantity, Double price, String type, Timestamp timestamp, String buyerName, String buyerAddress, String buyerPhoneNumber){ this.item = item; this.quantity = quantity; this.price = price; this.type = type; this.timestamp = timestamp; this.buyerName = buyerName; this.buyerAddress = buyerAddress; this.buyerPhoneNumber = buyerPhoneNumber; } public String getItem() { return item; } public Double getQuantity() { return quantity; } public Double getPrice() { return price; } public String getType() { return type; } public Timestamp getTimestamp() { return timestamp; } public String getBuyerName() { return buyerName; } public String getBuyerAddress() { return buyerAddress; } public String getBuyerPhoneNumber() { return buyerPhoneNumber; } }<file_sep>import javax.swing.*; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.util.ArrayList; // Created On: 7/24/2020. public class Login extends JPanel{ // CREATE ONE AND ONLY OBJECT OF HOME CLASS private static Home home = new Home(); public static void main(String[] args) { home.home(); } private Repository repository; JComboBox nameField; JPasswordField passField = new JPasswordField(); Login(){ ArrayList<String> stores; JLabel nameLabel = new JLabel("Store Name"); JLabel passLabel = new JLabel("Password"); JButton loginButton =new JButton("Login"); JButton registerButton = new JButton("Register"); repository = fetchRepo(); stores = repository.getStoreNames(); // ADD BLANK STRING SO THAT INITIAL SELECTION IS EMPTY stores.add(0,""); nameField = new AutoCompleteComboBox(stores.toArray()); // ADD LISTENERS loginButton.addActionListener((ActionEvent e) -> { if(repository.checkStoreValidity(nameField.getSelectedItem().toString(), String.valueOf(passField.getPassword()))) { home.logInStoreUser(nameField.getSelectedItem().toString()); }else{ JOptionPane.showMessageDialog(Login.super.getComponent(1),"Incorrect Credentials"); } } ); registerButton.addActionListener((ActionEvent e) -> { Register register = new Register(); register.register(home); } ); // MANAGE POSITIONS nameLabel.setBounds((getWidth()+200)/2,110,200,30); nameField.setBounds((getWidth()+200)/2,140,200,30); passLabel.setBounds((getWidth()+200)/2,180,200,30); passField.setBounds((getWidth()+200)/2,210,200,30); loginButton.setBounds((getWidth()+200)/2,250,150,40); registerButton.setBounds((getWidth()+200)/2,300,150,40); // ADD WIDGETS TO SCREEN add(nameLabel); add(nameField); add(passLabel); add(passField); add(loginButton); add(registerButton); // SETUP THE PANEL setBorder(new CompoundBorder(BorderFactory.createMatteBorder(4,4,4,4,Color.BLACK), new EmptyBorder(5,5,5,5))); setLayout(null); setPreferredSize(new Dimension(800,270)); setVisible(true); } private Repository fetchRepo(){ return new Repository(); } }<file_sep>import javax.swing.*; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.util.ArrayList; // Created on: 3/28/2021 public class StoreSalesReport extends JFrame { private final Repository repository; private final String storeName; private Object []row; private int count = 0; private final DefaultTableModel model; StoreSalesReport(String storeName){ repository = new Repository(); ArrayList<StoreReportModel> storeReportModelList = repository.getStoreReportData(storeName); this.storeName = storeName; JLabel salesReportLabel = new JLabel("Sales Report"); salesReportLabel.setFont(new Font("Serif", Font.BOLD, 30)); setTitle("Sales Report"); // SETUP TABLE JTable table = new JTable(); Object[]columns = {"Sn","Item","Quantity","Price","Type","Sales Date","Buyer Name","Buyer Address", "Buyer Phone Number"}; model = new DefaultTableModel(); model.setColumnIdentifiers(columns); table.setModel(model); row = new Object[9]; // ADD TABLE ROW FROM LIST storeReportModelList.forEach(this::addTableRow); buildTableUI(table); JScrollPane pane=new JScrollPane(); pane.getViewport().add(table); // MANAGE POSITIONS pane.setBounds(20,50,1460,600); salesReportLabel.setBounds(600,10,200,40); // ADD WIDGETS TO SCREEN add(pane); add(salesReportLabel); // SETUP PANEL setResizable(false); setSize(1500,700); setLocationRelativeTo(null); setLayout(null); setVisible(true); } private void buildTableUI(JTable table) { DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer(); centerRenderer.setHorizontalAlignment( JLabel.CENTER ); for(int x=0;x<9;x++){ table.getColumnModel().getColumn(x).setCellRenderer( centerRenderer ); } table.getTableHeader().setReorderingAllowed(false); table.getTableHeader().setFont(new Font("Segoe UI", Font.BOLD, 22)); table.getTableHeader().setOpaque(true); table.getTableHeader().setBackground(new Color(32, 136, 203)); table.getTableHeader().setForeground(new Color(255,255,255)); table.setRowHeight(25); table.setFocusable(false); table.setIntercellSpacing(new Dimension(0,0)); table.setSelectionBackground(new Color(232,57,95)); table.setShowVerticalLines(false); table.getColumnModel().getColumn(0).setMaxWidth(100); table.getColumnModel().getColumn(1).setMaxWidth(500); table.getColumnModel().getColumn(2).setMaxWidth(400); table.getColumnModel().getColumn(3).setMaxWidth(150); table.getColumnModel().getColumn(4).setMaxWidth(250); } void addTableRow(StoreReportModel storeReportModel){ count++; row[0] = count; row[1] = storeReportModel.getItem(); row[2] = storeReportModel.getQuantity(); row[3] = storeReportModel.getPrice(); row[4] = storeReportModel.getType(); row[5] = storeReportModel.getTimestamp(); row[6] = storeReportModel.getBuyerName(); row[7] = storeReportModel.getBuyerAddress(); row[8] = storeReportModel.getBuyerPhoneNumber(); model.addRow(row); } }<file_sep>import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.List; // Created on: 7/24/2020. class AddStock extends JPanel { private static int SUCCESS = 1; private static int FLAG = 0; private final String storeName; private JTable stockAddingTable = new JTable(); private JTable stockTable = new JTable(); private Object[] row2 = new Object[5]; private DefaultTableModel model2 = new DefaultTableModel() { public boolean isCellEditable(int row, int column) { return false; } }; private JPanel panel1 = new JPanel(); private JPanel panel2 = new JPanel(); private Repository repository = new Repository(); private JPanel mainPanel = new JPanel(); private Home home; AddStock(String storeName, Home home) { this.storeName = storeName; this.home = home; // BUILD THE FIRST AND SECOND PANEL buildFirstPanel(); buildSecondPanel(); // ADD PANELS TO MAIN PANEL mainPanel.add(panel1); mainPanel.add(panel2); // SETUP MAIN PANEL mainPanel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.BLACK)); mainPanel.setBounds(10, 10, 1440, 810); mainPanel.setLayout(null); mainPanel.setVisible(true); // ADD MAIN PANEL TO CLASS PANEL add(mainPanel); // SETUP CLASS PANEL setLayout(null); setPreferredSize(new Dimension(1460, 800)); } private void buildFirstPanel() { JLabel addStockLabel = new JLabel("Add Stock"); JLabel itemLabel = new JLabel("Item"); JLabel quantityLabel = new JLabel("Quantity"); JLabel priceLabel = new JLabel("Price"); JLabel typeLabel = new JLabel("Type"); JButton addButton = new JButton("Add"); JButton deleteButton = new JButton("Delete"); JButton resetButton = new JButton("Reset"); JButton confirmButton = new JButton("Confirm"); JTextField itemField = new JTextField(); JTextField quantityField = new JTextField(); JTextField priceField = new JTextField(); List<String> types = new ArrayList<>(); // ADD BLANK STRING SO THAT INITIAL SELECTION IS EMPTY types.add(""); List<ItemModel> list = repository.getAllStoreData(); // GET A LIST OF ALL THE TYPES OF ITEMS SOLD BY ALL STORES for (ItemModel model : list) { types.add(model.getType()); } // SETUP FOR TYPE FIELD SUGGESTIONS AutoCompleteComboBox typeField = new AutoCompleteComboBox(types.stream().distinct().toArray()); // CUSTOMIZE TEXT itemField.setFont(new Font("Serif", Font.BOLD, 16)); priceField.setFont(new Font("Serif", Font.BOLD, 16)); quantityField.setFont(new Font("Serif", Font.BOLD, 16)); addStockLabel.setFont(new Font("Serif", Font.BOLD, 30)); itemLabel.setFont(new Font("Serif", Font.BOLD, 16)); quantityLabel.setFont(new Font("Serif", Font.BOLD, 16)); priceLabel.setFont(new Font("Serif", Font.BOLD, 16)); typeLabel.setFont(new Font("Serif", Font.BOLD, 16)); addButton.setFont(new Font("Serif", Font.BOLD, 16)); deleteButton.setFont(new Font("Serif", Font.BOLD, 16)); resetButton.setFont(new Font("Serif", Font.BOLD, 16)); confirmButton.setFont(new Font("Serif", Font.BOLD, 16)); // SETUP SCROLL PANE AND TABLE JScrollPane pane = new JScrollPane(); pane.getViewport().add(stockAddingTable); DefaultTableModel model = new DefaultTableModel() { public boolean isCellEditable(int row, int column) { return false; } }; Object columns[] = {"No.", "Items", "Quantity", "Price", "Type"}; model.setColumnIdentifiers(columns); stockAddingTable.setModel(model); Object row[] = new Object[5]; // BUILD TABLE LOOKS buildTableUI(stockAddingTable); // ADD BUTTON FUNCTIONALITY addListeners(addButton, deleteButton, resetButton, confirmButton, itemField, quantityField, priceField, typeField, model, row); // MANAGE POSITIONS addStockLabel.setBounds(260, 20, 200, 50); itemLabel.setBounds(40, 80, 200, 40); itemField.setBounds(220, 80, 200, 40); quantityLabel.setBounds(40, 130, 200, 40); quantityField.setBounds(220, 130, 200, 40); priceLabel.setBounds(40, 180, 200, 40); priceField.setBounds(220, 180, 200, 40); typeLabel.setBounds(40, 230, 200, 40); typeField.setBounds(220, 230, 200, 40); addButton.setBounds(500, 230, 150, 50); pane.setBounds(40, 300, 660, 200); deleteButton.setBounds(300, 520, 150, 50); resetButton.setBounds(50, 520, 150, 50); confirmButton.setBounds(550, 520, 150, 50); // ADD WIDGETS TO SCREEN panel1.add(addStockLabel); panel1.add(itemLabel); panel1.add(quantityLabel); panel1.add(priceLabel); panel1.add(itemField); panel1.add(quantityField); panel1.add(priceField); panel1.add(typeLabel); panel1.add(typeField); panel1.add(addButton); panel1.add(deleteButton); panel1.add(resetButton); panel1.add(confirmButton); panel1.add(pane); // SETUP THE PANEL panel1.setVisible(true); panel1.setBounds(10, 0, 720, 810); panel1.setLayout(null); panel1.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.BLACK)); } private void buildSecondPanel() { Repository repository = new Repository(); List<ItemModel> list = repository.getParticularStoreData(storeName); JLabel availableStockLabel = new JLabel("Available stock"); availableStockLabel.setFont(new Font("Serif", Font.BOLD, 30)); JButton salesReportButton = new JButton("Sales Report"); // SETUP SCROLL PANE AND TABLE JScrollPane pane = new JScrollPane(); Object[] columns = {"No.", "Item", "Quantity", "Price", "Type"}; model2.setColumnIdentifiers(columns); stockTable.setModel(model2); // BUILD TABLE LOOKS buildTableUI(stockTable); // LOOP OVER EACH VALUE AND ADD THEM IN TABLE list.forEach(value -> { row2[0] = stockTable.getRowCount() + 1; row2[1] = value.getItem(); row2[2] = value.getQuantity(); row2[3] = value.getPrice(); row2[4] = value.getType(); model2.addRow(row2); }); pane.getViewport().add(stockTable); // MANAGE POSITIONS pane.setBounds(30, 90, 650, 500); availableStockLabel.setBounds(260, 20, 200, 50); salesReportButton.setBounds(300, 650, 200, 50); // ADD LISTENER salesReportButton.addActionListener((ActionListener) -> { new StoreSalesReport(storeName); }); // ADD WIDGET TO SCREEN panel2.add(salesReportButton); panel2.add(availableStockLabel); panel2.add(pane); // SETUP PANEL panel2.setBounds(720, 0, 710, 810); panel2.setLayout(null); panel2.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.BLACK)); panel2.setVisible(true); } // HELPER METHODS // CHECK IF DUPLICATE ITEM EXISTS IN STOCK ADDING TABLE AND // CHECK IF THEIR TYPES ARE DIFFERENT private boolean checkDuplicateTypeInTable(String item, String type) { for (int i = 0; i < stockAddingTable.getModel().getRowCount(); i++) { if (stockAddingTable.getModel().getValueAt(i, 1).toString().toLowerCase().equals(item.toLowerCase()) && !stockAddingTable.getModel().getValueAt(i, 4).toString().toLowerCase().equals(type.toLowerCase())) { return true; } } return false; } // CHECK IF DUPLICATE ITEM EXISTS IN STOCK ADDING TABLE AND // CHECK IF THEIR PRICES ARE DIFFERENT private boolean checkDuplicatePriceInTable(String item, String price) { for (int i = 0; i < stockAddingTable.getModel().getRowCount(); i++) { if (stockAddingTable.getModel().getValueAt(i, 1).toString().toLowerCase().equals(item.toLowerCase()) && !(stockAddingTable.getModel().getValueAt(i, 3).equals(price))) { return true; } } return false; } // CHECK IF DUPLICATE ITEM EXISTS IN STOCK ADDING TABLE AND // ADD QUANTITY OF SAME ITEMS private int checkDuplicateItemInTableAndAdd(String item) { for (int i = 0; i < stockAddingTable.getModel().getRowCount(); i++) { if (stockAddingTable.getModel().getValueAt(i, 1).toString().toLowerCase().equals(item.toLowerCase())) { return i; } } return -1; } private void buildTableUI(JTable table) { table.getTableHeader().setReorderingAllowed(false); table.getTableHeader().setFont(new Font("Segoe UI", Font.BOLD, 20)); table.getTableHeader().setOpaque(true); table.getTableHeader().setBackground(new Color(32, 136, 203)); table.getTableHeader().setForeground(new Color(255, 255, 255)); table.setRowHeight(25); table.setFocusable(false); table.setIntercellSpacing(new Dimension(0, 0)); table.setSelectionBackground(new Color(232, 57, 95)); table.setShowVerticalLines(false); } // ADD BUTTON LISTENERS private void addListeners(JButton addButton, JButton deleteButton, JButton resetButton, JButton confirmButton, JTextField itemField, JTextField quantityField, JTextField priceField, AutoCompleteComboBox typeField, DefaultTableModel model, Object[] row) { addButton.addActionListener((ActionEvent e) -> { // CHECK IF ANY FIELDS ARE EMPTY if ((itemField.getText().equals("") || quantityField.getText().equals("") || priceField.getText().equals("") || typeField.getSelectedItem().equals(""))) { JOptionPane.showMessageDialog(AddStock.super.getComponent(0), "Please Complete the Form"); return; } // CHECK IF THERE ARE DUPLICATE ITEMS WITH SAME PRICES OR TYPES // IF NOT, CHECK IF THE ITEM ALREADY EXISTS IN THE STORE STOCK // IF YES, JUST ADD THE QUANTITY // OTHERWISE JUST ADD THE ITEM if (repository.checkDuplicateItemWithDifferentPrice( storeName, itemField.getText(), priceField.getText()) || checkDuplicatePriceInTable( itemField.getText(), priceField.getText()) ) { JOptionPane.showMessageDialog(AddStock.super.getComponent(0), "Same Items cannot have Different Prices"); } else if (repository.checkDuplicateItemWithDifferentType( storeName, itemField.getText(), typeField.getSelectedItem().toString()) || checkDuplicateTypeInTable(itemField.getText(), typeField.getSelectedItem().toString())) { JOptionPane.showMessageDialog(AddStock.super.getComponent(0), "Same Items cannot have Different Types"); } else if (checkDuplicateItemInTableAndAdd(itemField.getText()) > -1) { int dup = checkDuplicateItemInTableAndAdd(itemField.getText()); model.setValueAt(Double.parseDouble(model.getValueAt(dup, 2).toString()) + Double.parseDouble(quantityField.getText()), dup, 2); } else { row[0] = stockAddingTable.getRowCount() + 1; row[1] = itemField.getText(); row[2] = quantityField.getText(); row[3] = priceField.getText(); row[4] = typeField.getSelectedItem(); model.addRow(row); itemField.setText(""); quantityField.setText(""); priceField.setText(""); itemField.grabFocus(); } } ); // DELETE THE SELECTED ROW deleteButton.addActionListener((ActionEvent e) -> { int i = stockAddingTable.getSelectedRow(); if (i >= 0) { model.removeRow(i); } } ); // CLEAR THE TABLE resetButton.addActionListener((ActionEvent e) -> model.setRowCount(0)); // CONFIRM TRANSACTION confirmButton.addActionListener((ActionEvent e) -> { for (int i = 0; i < stockAddingTable.getModel().getRowCount(); i++) { ItemModel itemModel = new ItemModel( storeName, stockAddingTable.getModel().getValueAt(i, 1).toString(), Double.parseDouble(stockAddingTable.getModel().getValueAt(i, 2).toString()), Double.parseDouble(stockAddingTable.getModel().getValueAt(i, 3).toString()), String.valueOf(stockAddingTable.getModel().getValueAt(i, 4))); if (repository.addStoreItems(itemModel) == 0) { SUCCESS = 0; } } if (SUCCESS == 0) { JOptionPane.showMessageDialog(AddStock.super.getComponent(1), "Data Insertion Failed"); SUCCESS = 1; } else { JOptionPane.showMessageDialog(AddStock.super.getComponent(0), "Data Insertion Complete"); for (int i = 0; i < model.getRowCount(); i++) { for (int j = 0; j < model2.getRowCount(); j++) { if (model.getValueAt(i, 1).toString().toLowerCase().equals(model2.getValueAt(j, 1).toString().toLowerCase())) { model2.setValueAt(Double.parseDouble(model.getValueAt(i, 2).toString()) + Double.parseDouble(model2.getValueAt(j, 2).toString()), j, 2); FLAG = 1; break; } } if (FLAG == 0) { row2[0] = model2.getRowCount() + 1; row2[1] = model.getValueAt(i, 1); row2[2] = model.getValueAt(i, 2); row2[3] = model.getValueAt(i, 3); row2[4] = model.getValueAt(i, 4); model2.addRow(row2); } FLAG = 0; } // CLEAR THE STOCK ADDING TABLE model.setRowCount(0); // RECREATE THE LEFT PANEL home.reCreateLeftPanel(); } } ); } }
bf88206bea7f1a0cf88eeccaa0c155afa8291c10
[ "Java", "SQL" ]
7
Java
AnkitShrestha-Xenserv/InventoryManagementSoftware
4c20b73e56c5e2dad33523db6ccca7ca5bd67a3e
bbdab54a0fd32b6dcba26f1ab11ffec167d38b20
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bankomat { class bankomat { List<Money> _kol = new List<Money>(); public void input(string box) { Casseteloader cs = new Casseteloader(box); if (cs.st == State2.AllOK) { _kol = cs.ToLoadCassete(); } else { Console.WriteLine(cs.st); } } public void show_all_money() { foreach (Money mon in _kol) { Console.WriteLine(mon.val + ":" + mon.count); } } public void output(int finite_sum, List<Money> mon) { CompositionAlgorithm ca = new CompositionAlgorithm(finite_sum, _kol); if (ca.st == State1.AllOk) { mon = ca.ToOut(); asd(mon); foreach (Money m in mon) { Console.WriteLine(m.val + ":" + m.count); } Console.WriteLine("Succes Operation!"); } else {Console.WriteLine(ca.st);} } void asd(List<Money> mon) { int index; foreach (Money n in mon) { index = _kol.FindIndex(l => l.val == n.val); _kol[index].count -= n.count; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using log4net; using log4net.Config; namespace Bankomat { class Program { public static readonly ILog log = LogManager.GetLogger(typeof(Casseteloader)); static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); bankomat bank = new bankomat(); bank.input("text.txt"); List<Money> mon = new List<Money>(); bank.output(50000, mon); bank.show_all_money(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using log4net; namespace Bankomat { class CompositionAlgorithm { public static readonly ILog log = LogManager.GetLogger(typeof(CompositionAlgorithm)); List<Money> outMoney = new List<Money>(); public State1 st; public CompositionAlgorithm(int output, List<Money> mom) { if (mom.Count == 0) { st = State1.NoMoney; log.Error("Exception " + st.ToString() + "\n"); return; } StringBuilder str = new StringBuilder(); int remain = 0; int count = 0; foreach (Money c in mom) { remain = output - count; if (remain > 0 && remain / c.val != 0 && c.count != 0) { int b = c.count; if (c.count > remain / c.val) b = remain / c.val; outMoney.Add(new Money(c.val, b)); count += c.val * b; } } if (output == count) { st = State1.AllOk; log.Info(st.ToString() + "\n"); } else { st = State1.Error; outMoney.Clear(); log.Error("Exception " + st.ToString() + "\n"); } } public List<Money> ToOut() { return outMoney; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using log4net; namespace Bankomat { class Casseteloader { public static readonly ILog log = LogManager.GetLogger(typeof(CompositionAlgorithm)); List<Money> cassete = new List<Money>(); public State2 st; public Casseteloader(string box) { string str; try { StreamReader sr = File.OpenText(box); while (!sr.EndOfStream) { str = sr.ReadLine(); string[] arr = str.Split(' '); cassete.Add(new Money(Convert.ToInt32(arr[0]), Convert.ToInt32(arr[1]))); } st = State2.AllOK; log.Info(st.ToString() + "\n"); cassete.Sort(delegate(Money cas1, Money cas2) { return cas1.val.CompareTo(cas2.val); }); cassete.Reverse(); } catch (FileNotFoundException) { st = State2.NoCassete; log.Error("Exceptiom" + st.ToString() + "\n"); } } public List<Money> ToLoadCassete() { return cassete; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bankomat { class Money { public Money(int val, int count) { this.val = val; this.count = count; } public int val; public int count; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bankomat { public enum State1 { Error, AllOk, NoMoney } public enum State2 { Error, NoCassete, AllOK } public enum StateBankomat { NoMoney, AllOK } }
363aa83d1f47d2481aba6cb90e1a09f715306c2d
[ "C#" ]
6
C#
Namankevi4/ATM
aa4a060e21c16dc90dadc1f72ba6fb630009cfed
742fcb629337db6d3120d526d05225ba2039b143
refs/heads/master
<repo_name>svtvrn/DS-2020<file_sep>/src/Broker.java import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.io.*; import java.net.*; public class Broker extends Node { private String ip; private int port; private BigInteger brokerId; private int backlog; //Sockets for the server-side operations transient Socket serverConnection=null; transient ServerSocket serverSocket; //Socket for the client-side operations Socket requestSocket=null; //Input and output streams for data ObjectOutputStream out=null; ObjectInputStream in=null; //Constructs broker and adds it to the list of brokers public Broker(String ip, int port){ this.ip=ip; this.port=port; backlog=5; } List<Consumer> registeredUsers= new ArrayList<Consumer>(); List<Publisher> registeredPublishers= new ArrayList<Publisher>(); LinkedList<Value> songQueue= new LinkedList<Value>(); ArrayList<ArtistName> artists= new ArrayList<ArtistName>(); //Returns the broker id, which is the hash code public BigInteger getBrokerId(){ return brokerId; } public int getPort(){return port;} //Calculates the hash value of the broker public void calculateKeys(){ //Start of hashing of ip+port String hash = ip+Integer.toString(port); byte[] bytesOfMessage=null; MessageDigest md=null; try { bytesOfMessage = hash.getBytes("UTF-8"); }catch (UnsupportedEncodingException ex){ System.out.println("Unsupported encoding"); } try { md = MessageDigest.getInstance("MD5"); }catch (NoSuchAlgorithmException ex){ System.out.println("Unsupported hashing"); } byte[] digest = md.digest(bytesOfMessage); brokerId = new BigInteger(digest); //End of hashing of ip+port } public Publisher acceptConnection(Publisher pub){ for(Publisher publisher : registeredPublishers){ if(publisher.getPort()==pub.getPort()) return null; } registeredPublishers.add(pub); System.out.println(brokerId+ " Publisher registered successfully."); return pub; } public Consumer acceptConnection(Consumer con){ registeredUsers.add(con); System.out.println("Consumer registered successfully."); return con; } public void notifyPublisher(String notification){ requestSocket=null; out = null; try{ requestSocket= new Socket(ip,port); out = new ObjectOutputStream(requestSocket.getOutputStream()); out.writeChars(notification); out.flush(); System.out.println("Notification sent"); }catch(IOException ex) { System.out.println("Notification failed"); }finally { disconnect(); } } //Input stream that gets the music files public void pull(MusicFile request){ try { int pubPort=0; for(Publisher pub : registeredPublishers){ for(ArtistName artist: pub.getArtists()){ if(artist.getName().equalsIgnoreCase(request.getArtistName())){ pubPort = pub.getPort(); break; } } } if(pubPort==0){ System.out.println("This artist doesn't exist"); return; } requestSocket = new Socket("127.0.0.1",pubPort); out= new ObjectOutputStream(requestSocket.getOutputStream()); out.writeObject(request); System.out.println("Request sent to publisher."); }catch (IOException ex) { System.out.println("Opening stream failed"); ex.printStackTrace(); } } @Override public void init(int id){ calculateKeys(); updateNodes(); openServer(); } public void openServer(){ try { System.out.println(port+" "+backlog); serverSocket = new ServerSocket(port,backlog); while (true){ System.out.println("Awaiting connection..."); serverConnection = serverSocket.accept(); System.out.println("Client connected"); ActionHandler actionHandler = new ActionHandler(this,serverConnection); System.out.println("Broker handler created"); //actionHandler.start(); new Thread(actionHandler).start(); } }catch (IOException ex){ System.out.println("Server crashed."); ex.printStackTrace(); } finally { try { serverSocket.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } } //Begins client connection with a publisher @Override public void connect() { try{ requestSocket= new Socket(ip,port); out = new ObjectOutputStream(requestSocket.getOutputStream()); out.writeChars("Connection established"); out.flush(); }catch(IOException ex) { System.out.println("Connection failed"); } } //Ends client connection with a publisher @Override public void disconnect(){ try { out.close(); in.close(); requestSocket.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } public void run(){ init(port); System.out.println("Broker thread created: "+port); } private class ActionHandler extends Thread{ ObjectInputStream in; ObjectOutputStream out; Broker broker; public ActionHandler(Broker broker,Socket connection) { try { out = new ObjectOutputStream(connection.getOutputStream()); in = new ObjectInputStream(connection.getInputStream()); this.broker=broker; } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { try { Object input = in.readObject(); if (input instanceof String) { String command = (String) input; //Consumer Action 1: Retrieves info file. if (command.equals("C1")) { Info infoTable = new Info(); infoTable.setBrokerList(getBrokers()); infoTable.setArtistTable(); out.writeObject(infoTable); }else if (command.equals("P1")) { System.out.println("Name added"); out.writeObject("Song was not found."); }else if(command.equals("C2")){ if(!broker.songQueue.isEmpty()){ for (Value chunk: songQueue){ chunk = songQueue.getFirst(); out.writeObject(chunk); out.flush(); this.sleep(1000); } } } }else if(input instanceof MusicFile) { MusicFile request = (MusicFile) input; pull(request); }else if(input instanceof Value){ Value chunk = (Value)input; broker.songQueue.add(chunk); }else if(input instanceof Consumer) { acceptConnection((Consumer)input); }else if(input instanceof Publisher) { Publisher pub = (Publisher) input; for (ArtistName artist : pub.getArtists()) { int port = pub.hashTopic(artist).getPort(); if (broker.getPort() == port) { if(!broker.artists.contains(artist)) { System.out.println(brokerId+" "+artist.getName()); broker.artists.add(artist); } acceptConnection(pub); } } } }catch (IOException ex){ ex.printStackTrace(); }catch (ClassNotFoundException ex){ System.out.println("Invalid casting."); }catch (InterruptedException ex){ ex.printStackTrace(); } } } public static void main(String[] arg){ Broker bro1 = new Broker("127.0.0.1",5200); Broker bro2 = new Broker("127.0.0.1",5201); Broker bro3 = new Broker("127.0.0.1",5202); bro1.start(); bro2.start(); bro3.start(); } }
b9d9bc652b7514cad51549d9ad9d52456ced92a9
[ "Java" ]
1
Java
svtvrn/DS-2020
51e3dfbeccc5e4ee7e3f5e8ca6d4677f366f7ff9
782c1974c21400021215c067e859e2ed4b4ef099
refs/heads/master
<file_sep>from twilio.rest import Client from credentials import account_sid, auth_token, my_cell, my_twilio client = Client(account_sid, auth_token) my_msg = ''.join(['Sample integration \n' for i in range(50)]) # my_msg = "Just trying out this awesome messaging app powered by Twilio using Python." message = client.messages.create(to=my_cell, from_=my_twilio, body=my_msg) # call = client.calls.create(to=my_cell, from_=my_twilio, url=my_url)<file_sep>account_sid = 'YOUR_ACCOUNT_SID' auth_token = '<PASSWORD>' my_cell = 'YOUR_CELL_NUMBER' my_twilio = 'YOUR_TWILIO_NUMBER'<file_sep>## Texting App Texting app powered by twilio built with Python
01357137e0739bd0b42e271a7f014635e0cae921
[ "Markdown", "Python" ]
3
Python
yemiwebby/texting-app-python
853bc46831269b66564f9561e9140a57cfb43bcd
7b167fdb8bf105c453a278894784c7df7599514c
refs/heads/master
<repo_name>yangfan0902/img2word<file_sep>/myLab/src/service/UserServiceImpl.java package service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import bean.User; import dao.ItemDao; import dao.UserDao; @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public User findUser(String name, String password) { return userDao.findUser(name, password); } @Override public void saveUser(String name, String password) { userDao.saveUser(name,password); } } <file_sep>/bookStore/src/web/filter/TransactionFilter.java package web.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import utils.JdbcUtils; public class TransactionFilter implements Filter { @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try{ //拦截下来后,获取连接,开启事务,并把连接绑定到当前线程 JdbcUtils.StartTransaction(); chain.doFilter(request, response);//目标资源执行 //获取当前线程上绑定的连接,提交事务,并关闭连接,释放连接与当前线程的绑定 JdbcUtils.commitTransaction(); }finally{ JdbcUtils.closeConn(); } } @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub } } <file_sep>/bookStore/src/factory/dao.properties CategoryDao=dao.impl.CategoryDaoImpl BookDao=dao.impl.BookDaoImpl OrderDao=dao.impl.OrderDaoImpl UserDao=dao.impl.UserDaoImpl DBBackDao=dao.impl.DBBackDaoImpl<file_sep>/bookStore/src/dao/impl/OrderDaoImpl.java package dao.impl; import java.sql.Connection; import java.util.List; import java.util.Set; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import dao.OrderDao; import domain.Book; import domain.Order; import domain.OrderItem; import domain.User; import utils.JdbcUtils; public class OrderDaoImpl implements OrderDao { /* (non-Javadoc) * @see dao.impl.OrderDao#add(domain.Order) */ @Override public void add(Order o){ try{ Connection conn=JdbcUtils.getConnection(); QueryRunner runner=new QueryRunner(); String sql="insert into orders (id,ordertime,state,price,user_id) values(?,?,?,?,?)"; Object params[]={o.getId(),o.getOrdertime(),o.isState(),o.getPrice(),o.getUser().getId()}; runner.update(conn, sql, params); Set<OrderItem> set=o.getOrderitem(); for(OrderItem item:set){ String itemSql="insert into orderitem(id,quantity,price,book_id,order_id) values(?,?,?,?,?)"; Object itemParams[]={item.getId(),item.getQuantity(),item.getPrice(),item.getBook().getId(),o.getId()}; runner.update(conn, itemSql, itemParams); } }catch(Exception e){ throw new RuntimeException(e); } } /* (non-Javadoc) * @see dao.impl.OrderDao#find(java.lang.String) */ @Override public Order find(String id){ try{ Connection conn=JdbcUtils.getConnection(); QueryRunner runner=new QueryRunner(); //找出订单 String sql="select * from orders where id=?"; Order order=(Order) runner.query(conn, sql, id, new BeanHandler(Order.class)); //找出订单对应的订单项 sql="select * from orderitem where order_id=?"; List<OrderItem> list=(List<OrderItem>) runner.query(conn, sql, id, new BeanListHandler(OrderItem.class)); //找出订单项对应的书 for(OrderItem item:list){ sql="select b.* from book b,orderitem oi where oi.id=? and oi.book_id=b.id"; Book book=(Book) runner.query(conn, sql, item.getId(), new BeanHandler(Book.class)); item.setBook(book); } order.getOrderitem().addAll(list); //找出下单人 sql="select u.* from orders o,user u where o.id=? and o.user_id=u.id"; User user=(User) runner.query(conn, sql, id, new BeanHandler(User.class)); order.setUser(user); return order; }catch(Exception e){ throw new RuntimeException(e); } } //state true为已发货,false为未发货 /* (non-Javadoc) * @see dao.impl.OrderDao#getAll(boolean) */ @Override public List<Order> getAll(boolean state){ try{ Connection conn=JdbcUtils.getConnection(); QueryRunner runner=new QueryRunner(); String sql="select * from orders where state=?"; List<Order> list=(List<Order>) runner.query(conn, sql, state,new BeanListHandler(Order.class)); for(Order o:list){ sql="select u.* from orders o,user u where o.id=? and o.user_id=u.id"; User user=(User) runner.query(conn, sql, o.getId(), new BeanHandler(User.class)); o.setUser(user); } return list; }catch(Exception e){ throw new RuntimeException(e); } } public void update(String id,boolean state){ try{ Connection conn=JdbcUtils.getConnection(); QueryRunner runner=new QueryRunner(); String sql="update orders set state=? where id=?"; Object param[]={state,id}; runner.update(conn, sql, param); }catch(Exception e){ throw new RuntimeException(e); } } } <file_sep>/myLab/src/bean/Item.java package bean; import java.util.Date; public class Item { private int id; private String name; private long date; private String product; private double price; private int number; private double totalprice; private String description; private int user_id; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getDate() { return date; } public void setDate(long date) { this.date = date; } public String getProduct() { return product; } public void setProduct(String product) { this.product = product; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public double getTotalprice() { return this.number*this.price; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getUser_id() { return user_id; } public void setUser_id(int user_id) { this.user_id = user_id; } } <file_sep>/bookStore/src/junit/test/BookDaoTest.java package junit.test; import java.util.List; import org.junit.Test; import dao.BookDao; import dao.impl.BookDaoImpl; import domain.Book; import domain.Category; import domain.QueryResult; import utils.JdbcUtils; public class BookDaoTest { public void testQuery(){ BookDao dao=new BookDaoImpl(); dao.pageQuery(0, 4, null, 1); } public void add(){ Book b=new Book(); b.setAuthor("Сţ"); b.setCategory(new Category()); b.setDescription("css"); b.setId("6"); b.setImage("123518"); b.setName("python"); b.setPrice(89); BookDao dao=new BookDaoImpl(); dao.add(b); } } <file_sep>/bookStore/src/web/manager/BookServlet.java package web.manager; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.management.RuntimeErrorException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.BusinessService; import domain.Book; import service.impl.BusinessServiceImpl; import utils.WebUtils; public class BookServlet extends HttpServlet { private BusinessService service=new BusinessServiceImpl(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method=request.getParameter("method"); if("forAddUI".equals(method)){ forAddUI(request,response); } if("add".equals(method)){ add(request,response); } if("list".equals(method)){ list(request,response); } } private void list(HttpServletRequest request, HttpServletResponse response) { try{ List books=service.getAllBook(); request.setAttribute("books", books); request.getRequestDispatcher("/manager/listbook.jsp").forward(request, response); }catch(Exception e){ throw new RuntimeException(e); } } private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ Book b=WebUtils.upload(request, this.getServletContext().getRealPath("/images")); service.addBook(b); request.setAttribute("message", "Ìí¼Ó³É¹¦"); }catch(Exception e){ e.printStackTrace(); request.setAttribute("message", "Ìí¼Óʧ°Ü"); } request.getRequestDispatcher("/message.jsp").forward(request, response); } private void forAddUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List categories=service.getAllCategory(); request.setAttribute("categories", categories); request.getRequestDispatcher("/manager/addbook.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } <file_sep>/bookStore/src/dao/OrderDao.java package dao; import java.util.List; import domain.Order; public interface OrderDao { void add(Order o); Order find(String id); //state true为已发货,false为未发货 List<Order> getAll(boolean state); public void update(String id,boolean state); }<file_sep>/img2word/src/main/java/com/yang/dao/UserDao.java package com.yang.dao; import org.springframework.stereotype.Repository; import pojo.User; @Repository public interface UserDao { public void update(User user); public User getUserById(int id); public void deleteUser(int id); } <file_sep>/img2word/src/main/resources/application.properties server.port=8081 server.servlet.session.timeout=30 server.tomcat.uri-encoding=utf-8 spring.datasource.driver-class-name = com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://192.168.25.1:3306/lab?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT spring.datasource.username=root spring.datasource.password=<PASSWORD> spring.thymeleaf.cache=false spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html<file_sep>/myLab/src/bean/QueryVo.java package bean; import java.util.ArrayList; import java.util.List; public class QueryVo { private Item item; private ArrayList<Item> itemList; public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } public ArrayList<Item> getItemList() { return itemList; } public void setItemList(ArrayList<Item> itemList) { this.itemList = itemList; } } <file_sep>/myLab/src/bean/User.java package bean; public class User { private int id; private String name; private String password; private Item item; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } } <file_sep>/bookStore/src/dao/BusinessService.java package dao; import java.util.List; import domain.Book; import domain.Cart; import domain.Category; import domain.DBBack; import domain.Order; import domain.PageBean; import domain.QueryInfo; import domain.User; public interface BusinessService { /** * 分类相关的服务 */ void addCategory(Category c); Category findCategory(String id); List getAllCategory(); /** * 图书相关的服务 */ void addBook(Book b); Book findBook(String id); List getAllBook(); PageBean bookPageQuery(QueryInfo info); /** * 用户相关的服务 */ void addUser(User u); User findUser(String username, String password); User findUser(String id); /** * 订单关的服务 */ //用用户的购物车产生订单对象,并保存到数据库 void saveOrder(Cart cart, User user); Order findOrder(String id); List getOrderByState(boolean state); void update(String id,boolean state); /** * 数据库相关的服务 */ public void addDBBack(DBBack back); public DBBack findBack(String id); public List getAllBack(); }<file_sep>/bookStore/src/junit/test/Test.java package junit.test; import service.impl.BusinessServiceImpl; public class Test { public static void main(String[] args){ BusinessServiceImpl service=new BusinessServiceImpl(); System.out.print(service.findCategory("1").getDescription()); } }
c922491fecb5e62d2d04b39b6df656d1fc07a317
[ "Java", "INI" ]
14
Java
yangfan0902/img2word
f7275589d533fd6f91f1dcc9147bb90f17943de0
4eef8e6ee08d46df65c4c62f4f94db2e64d5760d
refs/heads/master
<file_sep> const initialState = { loading: false, vacations: [], followedVacations: [], error: '' } export const auth = (loggedUser = {}, form) => { switch (form.type) { case "LOGIN": return { ...loggedUser, loggedUser: form.payload.u_name, } default: return loggedUser } } export const getAllVacations = (state = initialState, action) => { switch (action.type) { case "GET_ALL_VACATIONS_REQUEST": return { ...state, loadding: true } case "GET_ALL_VACATIONS_SUCCESS": return { ...state, loadding: false, vacations: [...action.payload.vacations] } case "GET_ALL_VACATIONS_failure": return { ...state, loadding: false, error: action.payload.error } case "GET_ALL_FOLLOWED_VACATIONS_REQUEST": return { ...state, loadding: true } case "GET_ALL_FOLLOWED_VACATIONS_SUCCESS": return { ...state, loadding: false, followedVacations: [...action.payload.followedVacations] } case "GET_ALL_FOLLOWED_VACATIONS_failure": return { ...state, loadding: false, error: action.payload.error } default: return state } } // export const claims =(claimsHistory =[], form) =>{ // switch (form.type) { // case "CREATE_CLAIM": // return [...claimsHistory, form.payload] // case "CREATE_DELETE_CLAIM": // return claimsHistory.filter(p => p.name !== form.payload.name) // default: // return claimsHistory; // } // } // export const policies =(policiesFolder=[], form) =>{ // switch (form.type) { // case "CREATE_POLICY": // return [...policiesFolder, form.payload.name] // case "CREATE_DELETE_POLICY": // return policiesFolder.filter(p => p !== form.payload.name) // default: // return policiesFolder; // } // } <file_sep># ReactJsWithRedux React Js vacations app using Redux <file_sep>CREATE DATABASE Travely; USE travely; CREATE TABLE users( id INT AUTO_INCREMENT, isAdmin BOOLEAN DEFAULT FALSE, f_name VARCHAR(255) NOT NULL, l_name VARCHAR(255) NOT NULL, u_name VARCHAR(255) NOT NULL, password text NOT NULL, PRIMARY KEY(id) ); CREATE TABLE vacation( id INT AUTO_INCREMENT, destenation VARCHAR(255) NOT NULL, description VARCHAR(255) NOT NULL, img_url TEXT, from_date DATE, until_date DATE, price INT, PRIMARY KEY(id) ); INSERT INTO vacations(destenation, description, img_url, from_date, until_date, price) VALUES('Orlando', 'A destination where children and grownups alike can enjoy once-in-alifetime expriences.', 'https://cdn.pixabay.com/photo/2014/01/05/13/22/walt-disney-world-239144_1280.jpg','2020-07-10', '2020-07-20',1280), ('Cancun', 'From Mayan ruins to 5-star oceanside resorts, this paradise will transport you to bliss.', 'https://cdn.pixabay.com/photo/2016/03/10/21/16/cancun-1249301_1280.jpg', '2020-06-15','2020-06-23', 1500), ('Miami', "One of the world's liveliest, most popular vacation spots with encitements for everyone.", 'https://images.unsplash.com/photo-1571041804726-53e8bf082096?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2250&q=80', '2020-09-20', '2020-09-27', 1350), ('London', "London is a diverse and exciting city with some of the world's best sights, attractions and activities", 'https://cdn.pixabay.com/photo/2014/11/13/23/34/london-530055_1280.jpg','2020-05-05','2020-05-15', 800) CREATE TABLE followers( id INT AUTO_INCREMENT, u_id INT NOT NULL, v_id INT NOT NULL, PRIMARY KEY(id), FOREIGN KEY(u_id) REFERENCES users(id) ON DELETE CASCADE, FOREIGN KEY(v_id) REFERENCES vacations(id) ON DELETE CASCADE ) <file_sep>const express = require('express'); const cors = require('cors'); const mysql = require('mysql'); const app = express(); const onlyUsers = require('./onlyUsers'); const onlyAdmins = require('./onlyAdmins') app.use(express.json()); app.use(cors()); const db= mysql.createConnection({ host: 'localhost', port: '8889', user: 'root', password: '<PASSWORD>', database: 'Travely' }) db.connect((err) => { if (err) { throw err } console.log("connected to my sql") }) app.use("/api/auth", require("./authRoutes")) //Get all Unfollowed Vacations: app.get("/api/vacations", onlyUsers, async (req, res) => { let q = `SELECT * FROM vacations` try { const results = await Query(q) res.json(results) } catch (err) { console.log(err) } }) //Add a vacation: app.post("/api/vacations",onlyAdmins , async (req,res)=>{ const { destination, description, img_url, from_date, until_date, price } = req.body; console.log(req.body); let q = `INSERT INTO vacations (destination, description, img_url, from_date, until_date, price) VALUES ('${destination}','${description}','${img_url}', '${from_date}', '${until_date}', ${price})` try{ const results = await Query(q) res.json(results) } catch(err){ console.log(err) } } ) //Edit a Vacation: app.put("/api/vacations", onlyAdmins, async (req,res)=>{ const { id, destination, description, img_url, from_date, until_date, price } = req.body console.log(req.body); let q= `UPDATE vacations SET destination = '${destination}', description = '${description}', img_url = '${img_url}', from_date = '${from_date}', Until_date = '${until_date}', price = ${price} WHERE id = ${id}` try { const results = await Query(q) res.json(results) } catch (err) { console.log(err) } }) //Delete a Vacation: app.delete("/api/followers", onlyUsers, async (req, res) => { const { u_id, v_id } = req.body; let q = `DELETE FROM followers WHERE v_id = ${v_id} AND u_id = ${u_id}` try { const results = await Query(q) res.json(results) } catch (err) { console.log(err) } }) //Add a Follower: app.post("/api/followers",onlyUsers, async (req,res)=>{ const { u_id, v_id } = req.body; console.log(req.body); let q = `INSERT INTO followers (u_id, v_id) VALUES (${u_id}, ${v_id})` try{ const results = await Query(q) res.json(results) } catch(err){ console.log(err) } }) //get Followers: app.get("/api/followers/:id",onlyUsers, async (req, res)=>{ const id = req.params.id; console.log(id); let q =`SELECT vacations.id, vacations.destination, vacations.description, vacations.img_url, vacations.from_date, vacations.until_date, vacations.price, followers.u_id AS status FROM vacations LEFT JOIN followers ON vacations.id=followers.v_id WHERE followers.u_id= ${id} ORDER BY vacations.id` try { const results = await Query(q) res.json(results) } catch (err) { console.log(err) } }) //Get All Followed Vacations for the Reports: app.get("/api/all-followed",onlyAdmins, async (req, res)=>{ let q =`SELECT vacations.destination, COUNT(V_ID) as amount From followers INNER JOIN vacations ON vacations.id=followers.v_id GROUP BY v_id HAVING COUNT(v_id) >= 1` try { const results = await Query(q) res.json(results) } catch (err) { console.log(err) } }) //Delete a Follower: app.delete("/api/delete-followers", onlyUsers, async (req, res) => { const { u_id, v_id } = req.body; let q = `DELETE FROM followers WHERE v_id = ${v_id} AND u_id = ${u_id}` try { const results = await Query(q) res.json(results) } catch (err) { console.log(err) } }) //Get Search result app.get("/api/searchedvacations/:result", onlyUsers, async (req, res) => { const { result } = req.params let q = `SELECT DISTINCT vacations.id, vacations.destination, vacations.description, vacations.img_url, vacations.from_date, vacations.until_date, vacations.price FROM vacations LEFT JOIN followers ON vacations.id = followers.v_id WHERE destination LIKE '%${result}%' OR description LIKE '%${result}%' OR from_date LIKE '%${result}%' OR until_date LIKE '%${result}%'` try { const results = await Query(q) res.json(results) } catch (err) { console.log(err) } }) const Query = (q, ...par) => { return new Promise((resolve, reject) => { db.query(q, par, (err, results) => { if (err) { reject(err) } else { resolve(results) } }) }) } app.listen(3001, console.log("Listening on http://localhost:3001")); module.exports = {Query}; <file_sep>import React, { useEffect, useState } from 'react'; import { connect } from 'react-redux' import { login } from "../redux/Actions" const Register = (props) => { const [f_name, setF_name] = useState('') const [l_name, setL_name] = useState('') const [u_name, setU_name] = useState('') const [password, setPassword] = useState('') const [isAdmin, setIsAdmin] = useState('') useEffect(() => { }, []) const registerHandleClick = async (e) => { e.preventDefault() const data = await fetch('http://localhost:3001/api/auth/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ f_name, l_name, u_name, password}) }) if (data.ok) { alert('User has been successfully registered,you are now Logged In') const res = await data.json() console.log(res); loginSend(e) } else { console.log('err') } } const loginSend = async (e) => { const data = await fetch('http://localhost:3001/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ u_name, password }) }) if (data.ok) { const res = await data.json() sessionStorage.token = res.token sessionStorage.isAdmin = res.user[0].isAdmin setIsAdmin(res.user[0].isAdmin) sessionStorage.setItem('uId', res.user[0].id,) props.dispatch(login(u_name, password, isAdmin)) props.history.push("/") } } return ( <div className="register-container"> <div className="register-page"> <h1>Register</h1> <form className="register-payload" onSubmit={registerHandleClick}> <label htmlFor="username">First Name:</label> <input type="text" placeholder="Enter Your Firstname" onChange={e => { setF_name(e.target.value) }} /> <label htmlFor="username">Last Name:</label> <input type="text" placeholder="Enter Your Lastname" onChange={e => { setL_name(e.target.value) }} /> <label htmlFor="username">Username:</label> <input type="text" placeholder="Enter Your Username" onChange={e => { setU_name(e.target.value) }} /> <label htmlFor="password">Password: </label> <input type="password" placeholder="Enter Your Password" onChange={e => { setPassword(e.target.value) }} /> <div className="btns"> <input type="submit" value="Register" className="register-btn"/> </div> </form> </div> </div> ) } const mapStateToProps = (state) => { return { auth: state.auth, vacations: state.getAllVacations } } export default connect(mapStateToProps)(Register)<file_sep>import React from 'react' import { Link } from "react-router-dom"; function Page404() { return ( <div> <div className="page404"> <div><h1>The page you are looking for doesn't exist!</h1><Link to="/"> Go Home</Link></div> <iframe className="wrong" src="https://www.youtube.com/embed/t3otBjVZzT0?autoplay=1" frameborder="0" allow="autoplay" title="Page not Found"></iframe> </div> </div> ) } export default Page404 <file_sep>import React, { useEffect } from 'react' import { connect } from 'react-redux' import { Bar } from 'react-chartjs-2'; import { getAllFollowedVacationsfailure, getAllFollowedVacationsSuccess, getAllFollowedVacationsRequest } from "../redux/Actions" import NavBar from './NavBar'; function Chart(props) { const token = sessionStorage.getItem('token') const myHeaders = new Headers(); myHeaders.append('Content-Type', 'application/json'); myHeaders.append('Authorization', token) const fetchFollowedVacations = () => { props.dispatch(getAllFollowedVacationsRequest()) fetch('http://localhost:3001/api/all-followed', { method: 'GET', headers: myHeaders }) .then(data => data.json()) .then(res => { props.dispatch(getAllFollowedVacationsSuccess(res, false)) }) .catch(error => { props.dispatch(getAllFollowedVacationsfailure(error.message)) }) } const allFollowedDestination = props.followedVacations.map(v => v.destination) const numOfFollowers = props.followedVacations.map(v => v.amount) const state = { labels: allFollowedDestination, datasets: [ { label: 'Number Of Followers', backgroundColor:'rgba(54, 162, 235, 0.6)', borderWidth: 1, borderColor: 'rgba(0,0,0,1)', hoverBorderWidth:3, hoverBorderColor:'#000', data: numOfFollowers } ] } useEffect(() => { fetchFollowedVacations() }, []) return ( <div className="chart"> <header>< NavBar/></header> <section className="reports"> <Bar data={state} options={{ title: { display: true, text: 'Followed Vacations Reports', fontSize: 40, fontColor: 'white', fontFamily: 'Bebas Neue, cursive' , padding: 50 }, legend: { display: true, position: 'right', labels: { fontColor: 'white' } }, layout:{ padding:{ left: 50, right:0, bottom:0, top:100 }, }, scales: { yAxes: [{ ticks: { beginAtZero: true, fontColor: 'white', } }], xAxes: [{ ticks: { beginAtZero: true, fontColor: 'white' } }] } }} /> </section> </div> ) } const mapStateToProps = (state) => { return { vacations: state.getAllVacations.vacations, followedVacations: state.getAllVacations.followedVacations } } export default connect(mapStateToProps)(Chart) <file_sep>import React, { useState } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Modal from '@material-ui/core/Modal'; import Backdrop from '@material-ui/core/Backdrop'; import Fade from '@material-ui/core/Fade'; import CreateIcon from '@material-ui/icons/Create'; import { IconButton } from '@material-ui/core/'; import Button from '@material-ui/core/Button'; import { withRouter } from 'react-router-dom' const useStyles = makeStyles(theme => ({ modal: { display: 'flex', alignItems: 'center', justifyContent: 'center', backgroundColor: 'transparant' }, paper: { backgroundColor: 'transparant', padding: theme.spacing(2, 4, 3), outline: 'none', }, })); function ModifyModal(props) { const classes = useStyles(); const [open, setOpen] = React.useState(false) const [destination, setDestination] = useState(props.vacation.destination) const [description, setDescription] = useState(props.vacation.description) const [img_url, setImg_url] = useState(props.vacation.img_url) const [from_date, setFrom_date] = useState(props.vacation.from_date.split('T')[0]) const [until_date, setUntil_date] = useState(props.vacation.until_date.split('T')[0]) const [price, setPrice] = useState(props.vacation.price) const token = sessionStorage.getItem('token') // const from_date = fromDate.split('T')[0] // const until_date = untilDate.split('T')[0] const myHeaders = new Headers(); myHeaders.append('Content-Type', 'application/json'); myHeaders.append('Authorization', token) const handleOpen = () => { console.log(props.vacation.id) setOpen(true); }; const handleClose = () => { setOpen(false); }; // const formated = formatDate(props.vacation.from_date) const modifyHandleClick = async (e) => { console.log(from_date) console.log(until_date) e.preventDefault() const id = props.vacation.id const data = await fetch('http://localhost:3001/api/vacations', { method: 'PUT', headers: myHeaders, body: JSON.stringify({ id, destination, description, img_url, from_date, until_date, price }) }) if (data.ok) { alert('Vacation has been successfully modified') const res = await data.json() console.log(res); } else { console.log('err') } props.history.push('/') } return ( <div> <IconButton onClick={handleOpen}> <CreateIcon></CreateIcon> </IconButton> <Modal aria-labelledby="transition-modal-title" aria-describedby="transition-modal-description" className={classes.modal} open={open} onClose={handleClose} closeAfterTransition BackdropComponent={Backdrop} BackdropProps={{ timeout: 500, }} > <Fade in={open}> <div className={classes.paper}> <div className="modal-page"> <form className="register-payload" onSubmit={modifyHandleClick}> <label htmlFor="destination">Destination:</label> <input type="text" defaultValue={props.vacation.destination} onChange={e => { setDestination(e.target.value) }} /> <label htmlFor="description">Description:</label> <input type="text" defaultValue={props.vacation.description} onChange={e => { setDescription(e.target.value) }} /> <label htmlFor="img_url">image Url:</label> <input type="text" defaultValue={props.vacation.img_url} onChange={e => { setImg_url(e.target.value) }} /> <label htmlFor="from_date">From: </label> <input type="date" defaultValue={props.vacation.from_date.split('T')[0]} onChange={e => { setFrom_date(e.target.value.split('T')[0]) }} /> <label htmlFor="until_date">To: </label> <input type="date" defaultValue={props.vacation.until_date.split('T')[0]} onChange={e => { setUntil_date(e.target.value.split('T')[0]) }} /> <label htmlFor="price">Price:</label> <input type="number" defaultValue={props.vacation.price} onChange={e => { setPrice(e.target.value) }} /> <Button type="submit" variant="outlined" color="default"> Apply Changes </Button> </form> </div> </div> </Fade> </Modal> </div> ) } export default withRouter(ModifyModal) <file_sep>const REGISTER = (f_name, l_name, u_name, password) => { return { // form | action type: "REGISTER", payload: { f_name, l_name, u_name, password } } } const login = (u_name, password) => { return { // form | action type: "LOGIN", payload: { u_name, password } } } // const GET_ALL_VATACTIONS = (destination, description, img_url, from_date, until_date , price) =>{ // return { // form | action // type: "GET_ALL_VATACTIONS", // payload: { // destination, // description, // img_url, // from_date, // until_date, // price // } // } // } const getAllVacationsRequest = (loading) => { return { type: "GET_ALL_VACATIONS_REQUEST", payload: { loading } } } const getAllVacationsSuccess = (vacations, loading, error) => { return { // form | action type: "GET_ALL_VACATIONS_SUCCESS", payload: { vacations, loading } } } const getAllVacationsfailure = error => { return { type: "GET_ALL_VACATIONS_failure", payload: error } } const getAllFollowedVacationsRequest = (loading) => { return { type: "GET_ALL_FOLLOWED_VACATIONS_REQUEST", payload: { loading } } } const getAllFollowedVacationsSuccess = (followedVacations, loading) => { return { // form | action type: "GET_ALL_FOLLOWED_VACATIONS_SUCCESS", payload: { followedVacations, loading } } } const getAllFollowedVacationsfailure = error => { return { type: "GET_ALL_FOLLOWED_VACATIONS_failure", payload: error } } // const fetchVacations = () => { // return function(dispatch) { // dispatch(getAllVacationsRequest()) // const token = sessionStorage.getItem('token') // const myHeaders = new Headers(); // myHeaders.append('Content-Type','application/json'); // myHeaders.append('Authorization',token) // fetch('http://localhost:3001/api/vacations',{ // method: 'GET', // headers: myHeaders}) // .then(data => data.json()) // .then(res=> { // const vacations = res // dispatch(getAllVacationsSuccess(vacations)) // }) // .catch (error =>{ // dispatch(getAllVacationsfailure(error.message)) // }) // } // } const DELETE_VACATION = (id) => { return { type: "CREATE_DELETE_CLAIM", payload: { id } } } const EDIT_VACATION = (destination, description, img_url, from_date, until_date, price) => { return { type: "EDIT_VACATION", payload: { destination, description, img_url, from_date, until_date, price } } } const FOLLOW = (u_id, v_id) => { return { type: "FOLLOW", payload: { u_id, v_id } } } const UNFOLLOW = (id) => { return { type: "UNFOLLOW", payload: { id } } } export { REGISTER, login, DELETE_VACATION, EDIT_VACATION, FOLLOW, UNFOLLOW, getAllVacationsSuccess, getAllVacationsfailure, getAllVacationsRequest, getAllFollowedVacationsRequest, getAllFollowedVacationsSuccess, getAllFollowedVacationsfailure }<file_sep>import React, { useState } from 'react'; import { connect } from 'react-redux' import { login } from "../redux/Actions" import { Link } from "react-router-dom"; function Login(props) { const [u_name, setU_name] = useState(''); const [password, setPassword] = useState(''); const handleClick = async (e) => { e.preventDefault() const data = await fetch('http://localhost:3001/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ u_name, password }) }) if (data.ok) { const res = await data.json() sessionStorage.token = res.token sessionStorage.isAdmin = res.user[0].isAdmin sessionStorage.setItem('uId', res.user[0].id,) props.dispatch(login(u_name, password)) alert("User hase been successfully connected") props.history.push("/") } } return ( <div className="login-container"> <div className="login-page"> <h1>Login</h1> <form className="login-payload" onSubmit={handleClick}> <label htmlFor="userName">Username:</label> <input type="text" onChange={e => setU_name(e.target.value)} /> <label htmlFor="password">Password:</label> <input type="password" onChange={e => setPassword(e.target.value)} /> <div className="submit"> <input type="submit" value="Login" id="login-btn" /> <Link to="/register">New user? Register</Link> </div> </form> </div> </div> ) } const mapStateToProps = (state) => { return { auth: state.auth, vacations: state.getAllVacations } } export default connect(mapStateToProps)(Login)<file_sep>import React, { useEffect } from 'react' import { connect } from 'react-redux' import FavoriteBorder from '@material-ui/icons/FavoriteBorderOutlined'; import Checkbox from '@material-ui/core/Checkbox'; import Favorite from '@material-ui/icons/Favorite'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import Card from '@material-ui/core/Card'; import { makeStyles } from '@material-ui/core/styles'; import CardMedia from '@material-ui/core/CardMedia'; import Typography from '@material-ui/core/Typography'; import { CardContent } from '@material-ui/core'; import { withRouter } from 'react-router-dom'; import moment from 'moment' // const useStyles = makeStyles(theme => ({ // margin: { // margin: theme.spacing(1), // }, // extendedIcon: { // marginRight: theme.spacing(1), // }, // })); const useStyles = makeStyles({ root: { display: 'flex', flexDirection: "column", justifyContent: 'center', width: '40vh', height: '65vh', marginTop: '4em', marginBottom: '4em', marginLeft: '4em', marginRight: '4em', borderRadius: 30, background: 'rgba(19, 60, 85, 0.7);', color: 'white' }, media: { height: '50vh', }, img: { width: '100%', height: '10vh' }, card: { height: '40vh' }, unchecked:{ color: 'white' } }) const VacationCard = (props) => { const classes = useStyles(); const followedVacations = props.followedVacations const vacations = props.vacations const token = sessionStorage.getItem('token') const u_id = sessionStorage.getItem('uId') const myHeaders = new Headers(); myHeaders.append('Content-Type', 'application/json'); myHeaders.append('Authorization', token) const likeVacation = async (v_id) => { const data = await fetch('http://localhost:3001/api/followers', { method: 'POST', headers: myHeaders, body: JSON.stringify({ u_id, v_id }) }) if (data.ok) { const res = await data.json() console.log(res); props.history.push('/') } else { console.log('err') } } const unlikeVacation = async (v_id) => { await fetch(`http://localhost:3001/api/delete-followers`, { method: "DELETE", headers: myHeaders, body: JSON.stringify({ u_id, v_id }) }) .then(data => data.json()) .then(res => { props.history.push('/') }) .catch(err => { console.log(err); }) } const handleChange = (v_id) => event => { if (event.target.checked) { likeVacation(v_id) } else { unlikeVacation(v_id) } } const isChecked = vacationID => { let check = false; if (followedVacations) { followedVacations.forEach(f => { if (f.id === vacationID) { check = true; return true; } }) } return check; } useEffect(() => { }, []) return ( <div className="vacations-container"> {followedVacations.map(v => ( <Card className={classes.root} key={Math.random()}> <CardMedia className={classes.media} image={v.img_url} /> <CardContent className={classes.card}> <Typography gutterBottom variant="h5" component="h2"> {v.destination} </Typography> <Typography variant="body2" color="white" component="p"> {v.description} </Typography> <Typography gutterBottom variant="h5" component="h2"> {moment(v.from_date).format('DD/MM/YYYY')} - {moment(v.until_date).format('DD/MM/YYYY')} </Typography> <Typography gutterBottom variant="h5" component="h2"> {v.price}$ </Typography> <FormControlLabel control={<Checkbox defaultChecked={isChecked(v.id)} id={v.id} onClick={handleChange(v.id)} icon={<FavoriteBorder />} checkedIcon={<Favorite />} />} /> </CardContent> </Card> ))} {vacations.map(v => ( <Card className={classes.root} key={Math.random()} style={{ display: isChecked(v.id) === true ? "none" : "" }}> <CardMedia className={classes.media} image={v.img_url} /> <CardContent className={classes.card}> <Typography gutterBottom variant="h5" component="h2"> {v.destination} </Typography> <Typography variant="body2" color="white" component="p"> {v.description} </Typography> <Typography gutterBottom variant="h5" component="h2"> {moment(v.from_date).format('DD/MM/YYYY')} - {moment(v.until_date).format('DD/MM/YYYY')} </Typography> <Typography gutterBottom variant="h5" component="h2"> {v.price}$ </Typography> <FormControlLabel control={<Checkbox className={classes.like} defaultChecked={isChecked(v.id)} id={v.id} onClick={handleChange(v.id)} icon={<FavoriteBorder className={classes.unchecked}/>} checkedIcon={<Favorite />} />} /> </CardContent> </Card> ))} </div> ) } const mapStateToProps = (state) => { return { vacations: state.getAllVacations.vacations, followedVacations: state.getAllVacations.followedVacations } } const routedCard = withRouter(VacationCard) export default connect(mapStateToProps)(routedCard) <file_sep>import React from 'react'; import { connect } from 'react-redux'; import DeleteIcon from '@material-ui/icons/Delete'; import { IconButton, Grid } from '@material-ui/core/'; import ModifyModal from './ModifyModal'; import { Link } from 'react-router-dom'; import AddModal from './AddModal'; import CardMedia from '@material-ui/core/CardMedia'; import { makeStyles } from '@material-ui/core/styles'; import Typography from '@material-ui/core/Typography'; import { CardContent } from '@material-ui/core'; import Card from '@material-ui/core/Card'; import moment from 'moment' const useStyles = makeStyles({ root: { display: 'flex', flexDirection: "column", justifyContent: 'center', width: '40vh', height: '65vh', marginTop: '4em', marginBottom: '4em', marginLeft: '4em', marginRight: '4em', borderRadius: 30, background: 'rgba(19, 60, 85, 0.7);', color: 'white' }, media: { height: '50vh', }, img: { width: '100%', height: '10vh' }, card: { height: '40vh' }, }) function AdminDashboard(props) { const classes = useStyles(); const vacations = props.vacations console.log(props.vacations) const token = sessionStorage.getItem('token') const myHeaders = new Headers(); myHeaders.append('Content-Type', 'application/json'); myHeaders.append('Authorization', token) const del = async (event) => { const eventTargetId = event.target.parentElement.parentElement.parentElement.id await fetch(`http://localhost:3001/api/vacations/${eventTargetId}`, { method: "delete", headers: myHeaders }) .then(data => data.json()) .then(res => { props.history.push('/login') }) .catch(err => { console.log(err); }) } return ( <div> <div className="vacations-container"> {vacations.map(v => ( <Card className={classes.root} key={Math.random()}> <CardMedia className={classes.media} image={v.img_url} /> <CardContent className={classes.card}> <Typography gutterBottom variant="h5" component="h2"> {v.destination} </Typography> <Typography variant="body2" color="white" component="p"> {v.description} </Typography> <Typography gutterBottom variant="h5" component="h2"> {moment(v.from_date).format('DD/MM/YYYY')} - {moment(v.until_date).format('DD/MM/YYYY')} </Typography> <Typography gutterBottom variant="h5" component="h2"> {v.price}$ </Typography> <div className="like-icon"> <IconButton onClick={del} id={v.id}> <DeleteIcon /> </IconButton> <ModifyModal vacation= {v} component={Link}/> </div> </CardContent> </Card> ))} </div> <Grid item container xs={6} alignItems="flex-end" direction="column"> <Grid item> <AddModal /> </Grid> </Grid> {/* <Chart /> */} </div> ) } const mapStateToProps = state => { return { auth: state.auth, vacations: state.getAllVacations.vacations } } export default connect(mapStateToProps)(AdminDashboard) <file_sep>import React from 'react'; import './App.css'; import Vacations from './components/Vacations'; import Login from './components/Login'; import AdminDashboard from "./components/AdminDashboard"; import {connect } from 'react-redux' import { BrowserRouter, Switch, Route, Redirect } from "react-router-dom"; import Register from './components/Register'; import Chart from './components/Chart' import Page404 from './components/Page404'; function App(props) { return ( <div className="App"> <BrowserRouter> <Switch> <Route path="/login" component = {Login} /> <Route path="/vacations" component = {Vacations} /> <Route path="/admin" component = {AdminDashboard} /> <Route path="/register" component = {Register} /> <Route path="/reports" component ={Chart} /> <Redirect from="/" to="/vacations" exact /> <Route path="*" component = {Page404} exact/> </Switch> </BrowserRouter> </div> ); } const mapStateToProps = (state) => { return { loggedUser: state.auth, vacations: state.getAllVacations } } export default connect(mapStateToProps)(App)
a3859ad2c043c336375cc21bc4bd65827f5574ed
[ "JavaScript", "SQL", "Markdown" ]
13
JavaScript
snirisr/reactJsWithRedux
e6557cd9a92e8896ff0b8f2ca401aa2a473a8b69
418a6ada8f5077cfeb0a90b950ac80c6c34ec51e
refs/heads/master
<file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "GameFramework/PlayerState.h" #include "LittleWarsPlayerState.generated.h" /** * */ UCLASS() class LITTLEWARS_API ALittleWarsPlayerState : public APlayerState { GENERATED_BODY() public: UFUNCTION(BlueprintCallable, Category = "LobbySessions") void SetName(const FString& Name); }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "LittleWars.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, LittleWars, "LittleWars" ); <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "LittleWars.h" #include "LittleWarsGameInstance.h" ULittleWarsGameInstance::ULittleWarsGameInstance(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { OnCreateSessionCompleteDelegate = FOnCreateSessionCompleteDelegate::CreateUObject(this, &ULittleWarsGameInstance::OnCreateSessionComplete); OnStartSessionCompleteDelegate = FOnStartSessionCompleteDelegate::CreateUObject(this, &ULittleWarsGameInstance::OnStartOnlineGameComplete); OnDestroySessionCompleteDelegate = FOnDestroySessionCompleteDelegate::CreateUObject(this, &ULittleWarsGameInstance::OnDestroySessionComplete); OnFindSessionsCompleteDelegate = FOnFindSessionsCompleteDelegate::CreateUObject(this, &ULittleWarsGameInstance::OnFindSessionsComplete); OnJoinSessionCompleteDelegate = FOnJoinSessionCompleteDelegate::CreateUObject(this, &ULittleWarsGameInstance::OnJoinSessionComplete); } /* Private */ /* Create Session */ void ULittleWarsGameInstance::Set_SessionSettings(FSessionSettingsStruct& Settings) { SessionSettings = MakeShareable(new FOnlineSessionSettings()); SessionSettings->Set(SETTING_PARTYNAME, Settings.PartyName, EOnlineDataAdvertisementType::ViaOnlineService); SessionSettings->bIsLANMatch = Settings.bIsLAN; SessionSettings->bUsesPresence = Settings.bIsPresence; SessionSettings->NumPublicConnections = Settings.NumberOfPlayers; SessionSettings->NumPrivateConnections = 0; SessionSettings->bAllowInvites = true; SessionSettings->bAllowJoinInProgress = true; SessionSettings->bShouldAdvertise = true; SessionSettings->bAllowJoinViaPresence = true; SessionSettings->bAllowJoinViaPresenceFriendsOnly = false; if (Settings.bHasPassword) { SessionSettings->Set(SETTING_PASSWORD, Settings.Password, EOnlineDataAdvertisementType::ViaOnlineService); } MapName = FName(*Settings.MapName); SessionSettings->Set(SETTING_MAPNAME, Settings.MapName, EOnlineDataAdvertisementType::ViaOnlineService); } bool ULittleWarsGameInstance::HostSession(TSharedPtr<const FUniqueNetId> UserId, FName SessionName, FSessionSettingsStruct& Settings) { const auto OnlineSubsystem = IOnlineSubsystem::Get(); if (OnlineSubsystem) { const auto SessionInterface = OnlineSubsystem->GetSessionInterface(); if (SessionInterface.IsValid() && UserId.IsValid()) { Set_SessionSettings(Settings); OnCreateSessionCompleteDelegateHandle = SessionInterface->AddOnCreateSessionCompleteDelegate_Handle(OnCreateSessionCompleteDelegate); GameSessionName = SessionName; return SessionInterface->CreateSession(*UserId, SessionName, *SessionSettings); } } else { GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, TEXT("No OnlineSubsystem found!")); } return true; } void ULittleWarsGameInstance::OnCreateSessionComplete(FName SessionName, bool bWasSuccessful) { GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, FString::Printf(TEXT("OnCreateSessionComplete %s, %d"), *SessionName.ToString(), bWasSuccessful)); const auto OnlineSubsystem = IOnlineSubsystem::Get(); if (OnlineSubsystem) { auto SessionInterface = OnlineSubsystem->GetSessionInterface(); if (SessionInterface.IsValid()) { SessionInterface->ClearOnCreateSessionCompleteDelegate_Handle(OnCreateSessionCompleteDelegateHandle); if (bWasSuccessful) { OnStartSessionCompleteDelegateHandle = SessionInterface->AddOnStartSessionCompleteDelegate_Handle(OnStartSessionCompleteDelegate); SessionInterface->StartSession(SessionName); } } } } void ULittleWarsGameInstance::OnStartOnlineGameComplete(FName SessionName, bool bWasSuccessful) { GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Red, FString::Printf(TEXT("Session Started %s, %d"), *SessionName.ToString(), bWasSuccessful)); const auto OnlineSubsystem = IOnlineSubsystem::Get(); if (OnlineSubsystem) { auto SessionInterface = OnlineSubsystem->GetSessionInterface(); if (SessionInterface.IsValid()) { SessionInterface->ClearOnStartSessionCompleteDelegate_Handle(OnStartSessionCompleteDelegateHandle); } } if (bWasSuccessful) { UGameplayStatics::OpenLevel(GetWorld(), MapName, true, "listen"); } } /* Destroy Session */ void ULittleWarsGameInstance::OnDestroySessionComplete(FName SessionName, bool bWasSuccessful) { GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Blue, FString::Printf(TEXT("Session Destroyed %s, %d"), *SessionName.ToString(), bWasSuccessful)); const auto OnlineSubsystem = IOnlineSubsystem::Get(); if (OnlineSubsystem) { auto SessionInterface = OnlineSubsystem->GetSessionInterface(); if (SessionInterface.IsValid()) { SessionInterface->ClearOnDestroySessionCompleteDelegate_Handle(OnDestroySessionCompleteDelegateHandle); if (bWasSuccessful) { UGameplayStatics::OpenLevel(GetWorld(), LEVEL_MAINMENU, true); } } } } /* Find Session */ void ULittleWarsGameInstance::SetSearchSettings(bool bIsLAN, bool bIsPresence) { SessionSearch = MakeShareable(new FOnlineSessionSearch()); SessionSearch->bIsLanQuery = bIsLAN; SessionSearch->MaxSearchResults = 20; SessionSearch->PingBucketSize = 100; if (bIsPresence) { SessionSearch->QuerySettings.Set(SEARCH_PRESENCE, bIsPresence, EOnlineComparisonOp::Equals); } } void ULittleWarsGameInstance::FindSessions(TSharedPtr<const FUniqueNetId> UserId, bool bIsLAN, bool bIsPresence) { auto OnlineSubsystem = IOnlineSubsystem::Get(); if (OnlineSubsystem) { auto SessionInterface = OnlineSubsystem->GetSessionInterface(); if (SessionInterface.IsValid() && UserId.IsValid()) { SetSearchSettings(bIsLAN, bIsPresence); auto SearchSettingsRef = SessionSearch.ToSharedRef(); OnFindSessionsCompleteDelegateHandle = SessionInterface->AddOnFindSessionsCompleteDelegate_Handle(OnFindSessionsCompleteDelegate); SessionInterface->FindSessions(*UserId, SearchSettingsRef); } } else { OnFindSessionsComplete(false); } } void ULittleWarsGameInstance::OnFindSessionsComplete(bool bWasSuccessful) { OnSearchCompleted.Broadcast(bWasSuccessful); const auto OnlineSubsystem = IOnlineSubsystem::Get(); if (OnlineSubsystem) { auto SessionInterface = OnlineSubsystem->GetSessionInterface(); if (SessionInterface.IsValid()) { SessionInterface->ClearOnFindSessionsCompleteDelegate_Handle(OnFindSessionsCompleteDelegateHandle); } } } /* Join Session */ bool ULittleWarsGameInstance::Get_SearchResultOf(FString OwningUserId, FOnlineSessionSearchResult& SearchResult) { for (FOnlineSessionSearchResult Result : SessionSearch->SearchResults) { if (Result.Session.OwningUserId->ToString() == OwningUserId) { SearchResult = Result; return true; } } return false; } bool ULittleWarsGameInstance::JoinSession(TSharedPtr<const FUniqueNetId> UserId, FName SessionName, const FOnlineSessionSearchResult& SearchResult) { auto bSuccess = false; auto OnlineSubsystem = IOnlineSubsystem::Get(); if (OnlineSubsystem) { auto SessionInterface = OnlineSubsystem->GetSessionInterface(); if (SessionInterface.IsValid() && UserId.IsValid()) { OnJoinSessionCompleteDelegateHandle = SessionInterface->AddOnJoinSessionCompleteDelegate_Handle(OnJoinSessionCompleteDelegate); bSuccess = SessionInterface->JoinSession(*UserId, SessionName, SearchResult); } } return bSuccess; } void ULittleWarsGameInstance::OnJoinSessionComplete(FName SessionName, EOnJoinSessionCompleteResult::Type Result) { GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Cyan, FString::Printf(TEXT("Joined Session: %s, %d"), *SessionName.ToString(), static_cast<int32>(Result))); auto OnlineSubsystem = IOnlineSubsystem::Get(); if (OnlineSubsystem) { auto SessionInterface = OnlineSubsystem->GetSessionInterface(); if (SessionInterface.IsValid()) { SessionInterface->ClearOnJoinSessionCompleteDelegate_Handle(OnJoinSessionCompleteDelegateHandle); const auto PlayerController = GetFirstLocalPlayerController(); FString TravelURL; if (PlayerController && SessionInterface->GetResolvedConnectString(SessionName, TravelURL)) { GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Cyan, FString::Printf(TEXT("Joined Session: %s, %d"), *TravelURL)); PlayerController->ClientTravel(TravelURL, TRAVEL_Absolute); } } } } /* Public */ FName ULittleWarsGameInstance::GetGameSessionName() const { return GameSessionName; } /* Session Management */ void ULittleWarsGameInstance::StartSession(FSessionSettingsStruct Settings, FName SessionName) { const auto Player = GetFirstGamePlayer(); HostSession(Player->GetPreferredUniqueNetId(), SessionName, Settings); } void ULittleWarsGameInstance::DestroySession(FName SessionName) { const auto OnlineSubsystem = IOnlineSubsystem::Get(); if (OnlineSubsystem) { auto SessionInterface = OnlineSubsystem->GetSessionInterface(); if (SessionInterface.IsValid()) { OnDestroySessionCompleteDelegateHandle = SessionInterface->AddOnDestroySessionCompleteDelegate_Handle(OnDestroySessionCompleteDelegate); SessionInterface->DestroySession(SessionName); } } } void ULittleWarsGameInstance::DestroyActualSession() { const auto OnlineSubsystem = IOnlineSubsystem::Get(); if (OnlineSubsystem) { auto SessionInterface = OnlineSubsystem->GetSessionInterface(); if (SessionInterface.IsValid()) { OnDestroySessionCompleteDelegateHandle = SessionInterface->AddOnDestroySessionCompleteDelegate_Handle(OnDestroySessionCompleteDelegate); SessionInterface->DestroySession(GameSessionName); } } } void ULittleWarsGameInstance::FindOnlineGames() { const auto Player = GetFirstGamePlayer(); FindSessions(Player->GetPreferredUniqueNetId(), true, true); } TArray<FSessionSearchResultStruct> ULittleWarsGameInstance::GetSearchResultStructs() const { TArray<FSessionSearchResultStruct> Results; for (auto result : SessionSearch->SearchResults) { FString OwningUserId = result.Session.OwningUserId->ToString(); FString PartyName; result.Session.SessionSettings.Get(SETTING_PARTYNAME, PartyName); auto NumberOfOpenConnections = result.Session.SessionSettings.NumPublicConnections; auto NumberOfMaxConnections = result.Session.NumOpenPrivateConnections; auto bHasPassword = result.Session.SessionSettings.Settings.Contains(SETTING_PASSWORD); FString MapName; result.Session.SessionSettings.Get(SETTING_MAPNAME, MapName); FSessionSearchResultStruct resultStruct(OwningUserId, PartyName, NumberOfOpenConnections, NumberOfMaxConnections, bHasPassword, MapName); Results.Add(resultStruct); } return Results; } bool ULittleWarsGameInstance::CheckPasswordForSessionOf(FString SessionOwnerUserId, FString Password) { FOnlineSessionSearchResult SearchResult; if (Get_SearchResultOf(SessionOwnerUserId, SearchResult)) { FString SessionPassword; if (SearchResult.Session.SessionSettings.Get(SETTING_PASSWORD, SessionPassword)) { if (SessionPassword == Password) { return true; } } } return false; } void ULittleWarsGameInstance::JoinGame(FName SessionName, FString OwningUserId) { const auto Player = GetFirstGamePlayer(); FOnlineSessionSearchResult SearchResult; if (Get_SearchResultOf(OwningUserId, SearchResult)) { FString hola = SearchResult.Session.OwningUserId->ToString(); if (SearchResult.Session.OwningUserId != Player->GetPreferredUniqueNetId()) { JoinSession(Player->GetPreferredUniqueNetId(), SessionName, SearchResult); } } } <file_sep>// Fill out your copyright notice in the Description page of Project Settings. using UnrealBuildTool; public class LittleWars : ModuleRules { public LittleWars(TargetInfo Target) { PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "OnlineSubsystem", "OnlineSubsystemUtils" }); DynamicallyLoadedModuleNames.AddRange(new string[] { "OnlineSubsystemNull" }); } } <file_sep> #pragma once #include "FSessionSearchResultStruct.generated.h" USTRUCT(BlueprintType) struct LITTLEWARS_API FSessionSearchResultStruct { GENERATED_USTRUCT_BODY() UPROPERTY(BlueprintReadOnly, Category = "Session Search Result") FString OwningUserId; UPROPERTY(BlueprintReadOnly, Category = "Session Search Result") FString PartyName; UPROPERTY(BlueprintReadOnly, Category = "Session Search Result") int32 NumberOfOpenConnections; UPROPERTY(BlueprintReadOnly, Category = "Session Search Result") int32 NumberOfMaxConnections; UPROPERTY(BlueprintReadOnly, Category = "Session Search Result") bool bHasPassword; UPROPERTY(BlueprintReadOnly, Category = "Session Search Result") FString MapName; FSessionSearchResultStruct() { OwningUserId = "User Id"; PartyName = "Party Name"; NumberOfOpenConnections = 0; NumberOfMaxConnections = 2; bHasPassword = false; MapName = "TestMap1"; } FSessionSearchResultStruct(FString _OwningUserId, FString _PartyName, int32 _NumberOfOpenConnections, int32 _NumberOfMaxConnections, bool _bHasPassword, FString _MapName) : OwningUserId(_OwningUserId), PartyName(_PartyName), NumberOfOpenConnections(_NumberOfOpenConnections), NumberOfMaxConnections(_NumberOfMaxConnections), bHasPassword(_bHasPassword), MapName(_MapName) { } }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "Engine/GameInstance.h" #include "FSessionSettingsStruct.h" #include "FSessionSearchResultStruct.h" #include "LittleWarsGameInstance.generated.h" #define SETTING_PASSWORD FName(TEXT("<PASSWORD>")) #define SETTING_PARTYNAME FName(TEXT("Party Name")) #define LEVEL_MAINMENU FName(TEXT("MainMenu")) DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnSearchCompleteDelegate, bool, bWasSuccessful); UCLASS() class LITTLEWARS_API ULittleWarsGameInstance : public UGameInstance { GENERATED_BODY() private: FName MapName; FName GameSessionName; TSharedPtr<class FOnlineSessionSettings> SessionSettings; /* Create Session */ void Set_SessionSettings(FSessionSettingsStruct& Settings); bool HostSession(TSharedPtr<const FUniqueNetId> UserId, FName SessionName, FSessionSettingsStruct& Settings); FOnCreateSessionCompleteDelegate OnCreateSessionCompleteDelegate; FDelegateHandle OnCreateSessionCompleteDelegateHandle; virtual void OnCreateSessionComplete(FName SessionName, bool bWasSuccessful); FOnStartSessionCompleteDelegate OnStartSessionCompleteDelegate; FDelegateHandle OnStartSessionCompleteDelegateHandle; virtual void OnStartOnlineGameComplete(FName SessionName, bool bWasSuccessful); /* Destroy Session */ FOnDestroySessionCompleteDelegate OnDestroySessionCompleteDelegate; FDelegateHandle OnDestroySessionCompleteDelegateHandle; virtual void OnDestroySessionComplete(FName SessionName, bool bWasSuccessful); void SetSearchSettings(bool bIsLAN, bool bIsPresence); /* Find Session */ TSharedPtr<class FOnlineSessionSearch> SessionSearch; void FindSessions(TSharedPtr<const FUniqueNetId> UserId, bool bIsLAN, bool bIsPresence); FOnFindSessionsCompleteDelegate OnFindSessionsCompleteDelegate; FDelegateHandle OnFindSessionsCompleteDelegateHandle; void OnFindSessionsComplete(bool bWasSuccessful); /* Join Session */ bool JoinSession(TSharedPtr<const FUniqueNetId> UserId, FName SessionName, const FOnlineSessionSearchResult& SearchResult); bool Get_SearchResultOf(FString OwningUserId, FOnlineSessionSearchResult& SearchResult); FOnJoinSessionCompleteDelegate OnJoinSessionCompleteDelegate; FDelegateHandle OnJoinSessionCompleteDelegateHandle; virtual void OnJoinSessionComplete(FName SessionName, EOnJoinSessionCompleteResult::Type Result); public: ULittleWarsGameInstance(const FObjectInitializer& ObjectInitializer); UPROPERTY(BlueprintReadWrite, Category = "Online Session") FName PlayerName; UFUNCTION(BlueprintCallable, Category = "Online Session") FName GetGameSessionName() const; /* Session Management */ UFUNCTION(BlueprintCallable, Category = "Online Session") void StartSession(FSessionSettingsStruct Settings, FName SessionName); UFUNCTION(BlueprintCallable, Category = "Online Session") void DestroySession(FName SessionName); UFUNCTION(BlueprintCallable, Category = "Online Session") void DestroyActualSession(); UFUNCTION(BlueprintCallable, Category = "Online Session") void FindOnlineGames(); UPROPERTY(BlueprintAssignable) FOnSearchCompleteDelegate OnSearchCompleted; UFUNCTION(BlueprintCallable, Category = "Online Session") TArray<FSessionSearchResultStruct> GetSearchResultStructs() const; UFUNCTION(BlueprintCallable, Category = "Online Session") bool CheckPasswordForSessionOf(FString SessionOwnerUserId, FString Password); UFUNCTION(BlueprintCallable, Category = "Online Session") void JoinGame(FName SessionName, FString OwningUserName); }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "LittleWars.h" #include "LittleWarsPlayerState.h" void ALittleWarsPlayerState::SetName(const FString& Name) { SetPlayerName(Name); } <file_sep> #pragma once #include "FSessionSettingsStruct.generated.h" USTRUCT(BlueprintType) struct LITTLEWARS_API FSessionSettingsStruct { GENERATED_USTRUCT_BODY() UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Session Settings") FString PartyName; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Session Settings") bool bIsLAN; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Session Settings") bool bIsPresence; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Session Settings") int32 NumberOfPlayers; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Session Settings") bool bHasPassword; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Session Settings") FString Password; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Session Settings") FString MapName; FSessionSettingsStruct() { bIsLAN = false; bIsPresence = false; NumberOfPlayers = 4; bHasPassword = false; Password = FString(TEXT("<PASSWORD>")); MapName = "TestMap2"; } }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "LittleWars.h" #include "LittleWarsGameMode.h" ALittleWarsGameMode::ALittleWarsGameMode() { }
d7b1a9feb5b60fff57fe72be264939a82cefa89f
[ "C#", "C", "C++" ]
9
C++
Angelosz/CPP_LittleWars
736262728535f7b03ed1d89ca0f30612e894c55e
675baf0d78860882447cdbaa7adb09e0716d67d5
refs/heads/master
<repo_name>lihao7264/spring-source-analyze<file_sep>/spring-lihao/src/main/java/com/atlihao/MyBeanFactoryPostProcessor.java package com.atlihao; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; /** * @Author lihao * @create 2020/6/9 16:59 */ public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor { public MyBeanFactoryPostProcessor() { System.out.println("BeanFactoryPostProcessor的实现类构造函数..."); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { System.out.println("BeanFactoryPostProcessor的实现方法调用中......"); } }<file_sep>/spring-lihao/src/main/java/com/atlihao/ItBean.java package com.atlihao; /** * @author lihao * @ClassName ItBean * @Since 2020/6/16 * @Description */ public class ItBean { private LihaoBean lihaoBean; public void setLihaoBean(LihaoBean lihaoBean) { this.lihaoBean = lihaoBean; } /** * 构造函数 */ public ItBean() { System.out.println("ItBean 构造器..."); } }
2b818f8acee13bb798841243a38e1d06053ab765
[ "Java" ]
2
Java
lihao7264/spring-source-analyze
e295cfde3eb0a96493f12090c154109d6ec721f5
341ccc3b698f369fd83798320d31351dd20e8dcb
refs/heads/master
<repo_name>hbmmizan/test1<file_sep>/new2/folder3.c create file no 1 <file_sep>/README.md # test1 test1 i love my bangladesh
3b621064412df67cc2659dcb4dce9c494b6150ed
[ "Markdown", "C" ]
2
C
hbmmizan/test1
cd6e76d60672ac6f568ad370ad1018a8ac095f3a
48b0c287d607699ae0a17f1bd1e4ae83fca5b060
refs/heads/master
<file_sep>### DDD Onion Verifier *Work in Progress* Verifies the correct implementation of [DDD Onion Architecture](https://www.innoq.com/de/blog/ddd-mit-onion-architecture-umsetzen/) with [ArchUnit](https://www.archunit.org/). <file_sep>package de.company.onionverifier.application; import org.springframework.stereotype.Service; @Service public class SomeApplicationService { } <file_sep>package de.company.onionverifier; import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.core.importer.ClassFileImporter; import com.tngtech.archunit.core.importer.ImportOption; import com.tngtech.archunit.lang.ArchRule; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.stereotype.Service; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; public class BasicArchTest { private JavaClasses classes; private final String BASE_PACKAGE_NAME = "de.company.onionverifier"; @BeforeEach public void setup() { classes = new ClassFileImporter() .withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS) .importPackages(BASE_PACKAGE_NAME); } @Test public void serviceClassesShouldBeAnnotatedWithService() { classes() .that().haveNameMatching(".*Service") .should().beAnnotatedWith(Service.class) .check(classes); } @Test public void serviceClassesShouldHaveNameEndingService() { classes() .that().areAnnotatedWith(Service.class) .should().haveSimpleNameEndingWith("Service") .check(classes); } }
658cb681f0081ed6ad36d6592848d7ffbfd63f78
[ "Markdown", "Java" ]
3
Markdown
markusgl/ddd-onion-verifier
7ab230fd81ba97f62122db2dcd09876467948449
f6f086f6dd516fc53252787176e7610896dcec4e
refs/heads/master
<repo_name>JustCawa/training-olinfo<file_sep>/threshold/main.cpp #include <iostream> #include <fstream> using namespace std; int main() { ifstream in ("input.txt"); ofstream out ("output.txt"); long long n; in >> n; int voti[n]; for (long long i = 0; i < n; i++) in >> voti[i]; for (int i = 100; i >= 0; i--) { long long tot = 0; for (long long j = 0; j < n; j++) { if (voti[j]>=i) tot++; } out << tot << " "; } } <file_sep>/muffin/main.cpp #include <iostream> #include <fstream> #include <climits> using namespace std; int main() { ifstream in ("input.txt"); ofstream out ("output.txt"); int n, k; in >> n >> k; int buono[n]; int massimo = INT_MIN; for (int i = 0; i < n; i++) in >> buono[i]; for (int i = 0; i < n+1-k; i++) { int tot = 0; for (int j = i; j < i+k; j++) tot+= buono[j]; if (tot > massimo) massimo = tot; } out << massimo; } <file_sep>/shopping mall/main.cpp #include <iostream> #include <fstream> #include <vector> #include <algorithm> // 35 / 100 PER COLPA DEL TEMPO. DA OTTIMIZZARE. using namespace std; int main() { ifstream in ("input.txt"); ofstream out ("output.txt"); vector<int> posizioni_negozi; int N, K; in >> N; in >> K; for (int i = 0; i < N; i++) { int v; in >> v; posizioni_negozi.push_back(v); } sort (posizioni_negozi.begin(), posizioni_negozi.end()); int posizione_ideale; int distanza_max = 0; // che si mettano tutti >= o >, il punteggio del compilatore rimane sempre lo stesso. //I risultati in output invece cambiano. for (int i = -1; i < N; i++) { if (i == -1) { distanza_max = posizioni_negozi[0]; posizione_ideale = 0; } else if (i == N-1) { if (K - posizioni_negozi[i] > distanza_max) { posizione_ideale = K; } } else { if (posizioni_negozi[i+1] - posizioni_negozi[i] > distanza_max) { distanza_max = posizioni_negozi[i+1] - posizioni_negozi[i]; if (distanza_max % 2 == 1) posizione_ideale = posizioni_negozi[i] + (distanza_max/2) + 1; else posizione_ideale = posizioni_negozi[i] + (distanza_max/2); } } } out << posizione_ideale; } <file_sep>/rubabandiera v2/main.cpp #include <iostream> #include <fstream> using namespace std; // DOVREBBE ESSERE GIUSTO MA VUOLE DA STDIN STDOUT E NON DA FSTREAM int main() { int Q; scanf("%d", &Q); int vincitori[Q]; for (int l = 0; l < Q; l++) vincitori[l] = 0; for (int l = 0; l < Q; l++) { int N; scanf("%d", &N); int arr[N+1]; for (int i = 1; i < N+1; i++) arr[i] = 1; for (int i = 1; i < N+1; i++) if (i % 2 == 0) arr[i] = 0; int vivi = N/2; bool flag = false; bool cenesonopiudiuno = true; while (cenesonopiudiuno) { for (int k = 0; k < 2; k++) { for (int i = 1; i < N+1; i++) { if (arr[i] == 1 && flag) {arr[i] = 0; vivi--; flag = false;} else if (arr[i] == 1) flag = true; } } if (vivi < 2) cenesonopiudiuno = false; } for (int i = 1; i < N+1; i++) if (arr[i] != 0) vincitori[l] = i; } for (int l = 0; l < Q; l++) printf("%d\n", vincitori[l]); } <file_sep>/1234/main.cpp #include <iostream> using namespace std; int funz(int a, int b) { if (a == 0) return b; else return funz(a-1, b+1); } int main() {cout << funz(5, 3);} <file_sep>/LWF/main.cpp #include <iostream> #include <fstream> using namespace std; int main() { int n, t; ifstream in("input.txt"); ofstream out("output.txt"); in >> t; int fibo[30]; fibo[0] = 1; fibo[1] = 1; for (int i = 2; i < 30; i++) { fibo[i] = fibo[i-2] + fibo[i-1]; } /*for (int i = 0; i < 30; i++) { cout << fibo[i] << endl; }*/ for (int k = 0; k < t; k++) { string ris = ""; in >> n; for (int i = 30; i >= 0; i--) { if (fibo[i] <= n) { n -= fibo[i]; ris = "1" + ris; } else { if (ris != "") { ris = "0" + ris; } } } out << "Case #" << k+1 << ": " << ris << endl; } } <file_sep>/studioamico/main.cpp #include <iostream> #include <fstream> #include <vector> #include <algorithm> using namespace std; int main() { ifstream in ("input.txt"); ofstream out ("output.txt"); int N; in >> N; vector<int> voti2; vector<int> voti5; for (int i = 0; i < N; i++) {int u; in >> u; voti2.push_back(u);} for (int i = 0; i < N; i++) {int u; in >> u; voti5.push_back(u);} sort(voti2.begin(), voti2.end()); sort(voti5.begin(), voti5.end()); bool ris = true; for (int i = 0; i < N; i++) { if (voti2[i]>=voti5[i]) { ris = false; } } if (ris) out << 1; else out << 0; } <file_sep>/keylogger/main.cpp #include <iostream> #include <fstream> using namespace std; int main() { ifstream in ("input.txt"); ofstream out ("output.txt"); int n, k; in >> n >> k; int numeri[n]; for (int i = 0; i < n+1-k; i++) { } } <file_sep>/ristoranti/main.cpp #include <iostream> #include <fstream> using namespace std; int main() { ifstream in ("input.txt"); ofstream out ("output.txt"); int n; in >> n; int massimo = -2; int vincitore; for (int i = 0; i < n; i++) { int voti[n+1]; int totale = 0; for (int j = 0; j < n+1; j++) in >> voti[j]; for (int j = 0; j < n+1; j++) totale += voti[j]; if (totale > massimo) {massimo = totale; vincitore = i;} out << vincitore+1 << endl; } } <file_sep>/trisProva/main.cpp #include <iostream> #include <stdio.h> using namespace std; int as=1; int ac=2; int ad=3; int cs=4; int cc=5; int cd=6; int bs=7; int bc=8; int bd=9; int ans; void table() { printf(" | | \n"); printf(" %d | %d | %d \n", as, ac, ad); printf("_____ |_____|_____\n"); printf(" | | \n"); printf(" %d | %d | %d \n", cs, cc, cd); printf(" _____|_____|_____\n"); printf(" | | \n"); printf(" %d | %d | %d \n", bs, bc, bd); printf(" | | \n"); } int ask() { printf("Scrivi il numero di casella: "); scanf("%d", &ans); return 0; } void cambia() { switch (ans) { case (1): as = 0; break; case (2): ac = 0; break; case (3): ad = 0; break; case (4): cs = 0; break; case (5): cc = 0; break; case (6): cd = 0; break; case (7): bs = 0; break; case (8): bc = 0; break; case (9): bd = 0; break; default : printf("Valore non accettabile. Deve essere compreso tra 1 e 9"); } } int main(){ table(); ask(); cambia(); table(); return 0; } <file_sep>/formica/main.cpp #include <iostream> #include <fstream> #include <cmath> using namespace std; int fornisci_valore_passi(int a, int b) { int ra, rb, ca, cb; if (a == 0) {ra = 3; ca = 1;} else if (a == 1) {ra = 0; ca = 0;} else if (a == 2) {ra = 0; ca = 1;} else if (a == 3) {ra = 0; ca = 2;} else if (a == 4) {ra = 1; ca = 0;} else if (a == 5) {ra = 1; ca = 1;} else if (a == 6) {ra = 1; ca = 2;} else if (a == 7) {ra = 2; ca = 0;} else if (a == 8) {ra = 2; ca = 1;} else if (a == 9) {ra = 2; ca = 2;} if (b == 0) {rb = 3; cb = 1;} else if (b == 1) {rb = 0; cb = 0;} else if (b == 2) {rb = 0; cb = 1;} else if (b == 3) {rb = 0; cb = 2;} else if (b == 4) {rb = 1; cb = 0;} else if (b == 5) {rb = 1; cb = 1;} else if (b == 6) {rb = 1; cb = 2;} else if (b == 7) {rb = 2; cb = 0;} else if (b == 8) {rb = 2; cb = 1;} else if (b == 9) {rb = 2; cb = 2;} int ris; ris = fabs(ra - rb) + fabs(ca - cb) + 1; return ris; } int main() { ifstream in ("input.txt"); ofstream out ("output.txt"); string S; in >> S; int lunghezza = S.length(); int totale = 0; int caratteri[lunghezza]; for (int i = 0; i < lunghezza; i++) { if (S[i] == '0') caratteri[i] = 0; else if (S[i] == '1') caratteri[i] = 1; else if (S[i] == '2') caratteri[i] = 2; else if (S[i] == '3') caratteri[i] = 3; else if (S[i] == '4') caratteri[i] = 4; else if (S[i] == '5') caratteri[i] = 5; else if (S[i] == '6') caratteri[i] = 6; else if (S[i] == '7') caratteri[i] = 7; else if (S[i] == '8') caratteri[i] = 8; else if (S[i] == '9') caratteri[i] = 9; } for (int i = 0; i < lunghezza; i++) { if (i != 0) totale += fornisci_valore_passi(caratteri[i-1], caratteri[i]); else totale += fornisci_valore_passi(0, caratteri[i]); } out << totale; } <file_sep>/ois_uefa/main.cpp #include <iostream> #include <fstream> using namespace std; int main() { ifstream in ("input.txt"); ofstream out ("output.txt"); int n, m; in >> n >> m; string squadra[n]; string nazione[n]; for (int i = 0; i < n; i++) { in >> squadra[i] >> nazione[i]; } for (int i = 0; i < m; i++) { in } } <file_sep>/spectre/main.cpp #include <iostream> #include <fstream> using namespace std; int main() { ifstream in ("input.txt"); ofstream out ("output.txt"); int n; in >> n; string s1[n], s2[n], s3[n]; for (int i = 0; i < n; i++) { string inutile; in >> s1[i] >> inutile >> s2[i] >> inutile >> s3[i]; } } <file_sep>/Yolo/main.cpp #include <stdlib.h> #include <stdio.h> #include <time.h> int main () { int prova; int numero; srand(time(NULL)); numero = rand() % 100 + 1; //printf("%d", numero); do { printf("Indovina il numero:"); scanf("%d", &prova); if (prova < numero) { puts("Il numero casuale e' piu' grande"); } else if (prova > numero) { puts("Il numero casuale e' piu' piccolo"); } else { printf("Complimenti! \nIl numero era %d", numero); } } while (prova != numero); return 0; } <file_sep>/nimbus/main.cpp #include <iostream> #include <fstream> using namespace std; int main() { fstream in("input.txt"); fstream out("output.txt"); int t,ora1,ora2; int tempo_min; in >> t; int tempi[t]; for (int i = 0; i < t; i++) { in >> ora1; in >> ora2; tempi[i] = ora2 - ora1; } for (int i = 0; i < t; i++){ if (i == 0) { tempo_min = tempi[0]; } else { tempo_min = min(tempo_min, tempi[i]); } } out << tempo_min << endl; } <file_sep>/fluttuazioni/main.cpp #include <iostream> #include <fstream> #include <cmath> using namespace std; int main() { ifstream in ("input.txt"); ofstream out ("output.txt"); int n; in >> n; int massimo = 0; int fluttuazioni[n]; for (int i = 0; i < n; i++) in >> fluttuazioni[i]; for (int i = 0; i < n-1; i++) { if(fabs(fluttuazioni[i]-fluttuazioni[i+1]) > massimo) massimo = fabs(fluttuazioni[i]-fluttuazioni[i+1]); } out << massimo; } <file_sep>/Do_not_enter_5_pt2/main.cpp #include <iostream> #include <stdio.h> using namespace std; int valore; int tent = 0; int main() { do { if (valore != NULL) { puts("Valore non valido."); } tent++; printf("Inserisci un numero che vuoi tranne il numero %d.\n", tent); scanf("%d", &valore); /*if (tent == 10) { puts("Wow, sei molto piu' paziente di me, hai vinto."); }*/ } while (valore != tent /*&& tent != 10*/); if (valore == tent) { printf("Hey, non dovevi scrivere %d!\n", tent); } return 0; } <file_sep>/quanti plumcakes/main.cpp #include <iostream> #include <stdio.h> #include <algorithm> using namespace std; int persona[10]; int massimo; int minimo; int num_max; int num_min; int main(){ for (int i = 1; i <= 10; i++){ cout << "Quanti plumcakes ha mangiato la persona numero " << i << " ? "; scanf("%d", &persona[i]); } for (int i = 1; i <= 10; i++){ if (persona[i] > massimo) { massimo = persona[i]; num_max = i; } } for (int i = 1; i <= 10; i++){ if (persona[i] < minimo || minimo == NULL) { minimo = persona[i]; num_min = i; } } cout << "La persona che ha mangiato piu' plumcakes e' stata la persona numero " << num_max << ", e ne ha mangiati " << massimo << endl; cout << "La persona che ha mangiato meno plumcakes e' stata la persona numero " << num_min << ", e ne ha mangiati " << minimo << endl; cout << num_max << endl; return 0; } <file_sep>/yolo2/main.cpp #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n, q; scanf("%d %d", &n, &q); int matrice[n][100]; for (int i = 0; i < n; i++) { int v; scanf("%d", &v); for (int j = 0; j < v; j++) { int w = 0; scanf("%d", &w); matrice[i][j] = w; } } for (int i = 0; i < q; i++) { int a = 0; int b = 0; scanf("%d %d", &a, &b); printf("%d\n", matrice[a][b]); } return 0; } <file_sep>/bevande/main.cpp #include <iostream> #include <stdio.h> using namespace std; int scelta; int main() { puts("Ecco le mie bevande preferite, scegline una:"); puts("1 - Coca-Cola"); puts("2 - Aranciata"); puts("3 - Succo alla pesca"); puts("4 - Succo all' albicocca"); puts("5 - Acqua"); scanf("%d", &scelta); switch (scelta) { case (1): puts("Hai scelto Coca-Cola."); break; case (2): puts("Hai scelto Aranciata."); break; case (3): puts("Hai scelto Succo alla pesca."); break; case (4): puts("Hai scelto Succo all' albicocca."); break; case (5): puts("Hai scelto Acqua."); break; default: puts("Valore non valido, riprenditi le tue monete."); main(); } return 0; } <file_sep>/esercizio_voti/main.cpp #include <iostream> #include <stdio.h> using namespace std; int voto; int main() { puts("Inserisci il tuo voto: "); scanf("%d", &voto); if (voto > 100){ cout << "voto non valido" << endl; } else if (voto > 89){ cout << "Hai preso una A" << endl; } else if (voto > 79){ cout << "Hai preso una B" << endl; } else if (voto > 69){ cout << "Hai preso una C" << endl; } else if (voto > 59){ cout << "Hai preso una D" << endl; } else { cout << "Hai preso una F" << endl; } if (voto == 100) { cout << "Complimenti!!" << endl; } return 0; } <file_sep>/olympic_cake/main.cpp #include <iostream> #include <fstream> using namespace std; int main() { ifstream in ("input.txt"); ofstream out ("output.txt"); long n; in >> n; if (n == 0) out << 1; else if (n%2 == 0) out << (n/2 + 1) * (n/2 + 1); else out << ((n-1) / 2 + 1) * ((n+1) / 2 + 1); } <file_sep>/bitcoin/main.cpp #include <iostream> #include <fstream> using namespace std; int main() { ifstream in ("input.txt"); ofstream out ("output.txt"); int N; double E; int soldi = 0; int bitc = 1; in >> N >> E; int variazioni[N]; for (int i = 0; i < N; i++) in >> variazioni[i]; for (int i = 0; i < N; i++) { E += variazioni[i]; if (variazioni[i] < 0) {soldi = bitc*E; bitc = 0;} else {} } } <file_sep>/cannoniere/main.cpp #include <iostream> #include <fstream> using namespace std; int main() { ifstream in("input.txt"); ofstream out("output.txt"); int t, g, r; in >> t; int Giocatore[100]{0}; for (int p = 0; p < t; p++) { in >> g; in >> r; Giocatore[g] += r; } int massimo = 0; int num_maglia = 0; for (int j = 0; j < 100; j++) { if (Giocatore[j] > massimo) { massimo = Giocatore[j]; num_maglia = j; } } out << num_maglia << " " << massimo << endl; }
78a20153d5e98368082bb0ce01f81d312e96d0df
[ "C++" ]
24
C++
JustCawa/training-olinfo
a0295260e6659fd22f64dcd951a6e962d24ac09d
7b329ca7fa6fa82e3cea2cd2acdc1a43882a8c22
refs/heads/master
<repo_name>Udit-K/Victory-Sports<file_sep>/nbproject/private/private.properties deploy.ant.properties.file=/Users/ukhanna/Library/Application Support/NetBeans/8.1/tomcat80.properties file.reference.commons-fileupload-1.3.2.jar=/Users/ukhanna/Downloads/libraries/commons-fileupload-1.3.2.jar file.reference.commons-io-2.5-javadoc.jar=/Users/ukhanna/Downloads/libraries/commons-io-2.5.jar file.reference.commons-io-2.5.jar=/Users/ukhanna/Downloads/libraries/commons-io-2.5.jar file.reference.javax.servlet-api-3.0.1.jar=/Users/ukhanna/Downloads/libraries/javax.servlet-3.0.0.v201112011016.jar/javax.servlet-3.0.0.v201112011016.jar file.reference.mail.jar=/Users/ukhanna/Downloads/libraries/javax.mail.jar file.reference.mysql-connector-java-5.0.8-bin.jar=/Users/ukhanna/Downloads/libraries/mysql-connector-java-5.0.8-bin.jar file.reference.ojdbc6-11.2.0.4.0-atlassian-hosted.jar=/Users/ukhanna/Downloads/libraries/ojdbc6-11.2.0.4.0-atlassian-hosted.jar j2ee.server.domain=C:/Users/babys/AppData/Roaming/NetBeans/8.2/apache-tomcat-8.0.27.0_base j2ee.server.home=/Users/ukhanna/Downloads/apache-tomcat-8.5.11 j2ee.server.instance=tomcat80:home=/Users/ukhanna/Downloads/apache-tomcat-8.5.11 selected.browser=SL[/Browsers/SafariBrowser user.properties.file=/Users/ukhanna/Library/Application Support/NetBeans/8.1/build.properties <file_sep>/src/java/com/girlzone/dao/UserDB.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.girlzone.dao; import com.girlzone.business.Menu; import com.girlzone.business.Order; import com.girlzone.util.DBUtil; import com.girlzone.business.Password; import com.girlzone.business.Role; import com.girlzone.business.User; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * * @author jyoti */ public class UserDB { public static Password getPassword(String username) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; Password password = null; String query = "SELECT * FROM userpassword " + "WHERE UserName = ?"; try { ps = connection.prepareStatement(query); ps.setString(1, username); rs = ps.executeQuery(); password = new Password(); if (rs.next()) { password.setUserName(rs.getString("UserName")); password.setPassword(rs.getString("UserPassword")); password.setSalt(rs.getString("Salt")); } return password; } catch (SQLException e) { System.out.println(e); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static int insertUser(User user) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; String query = "INSERT INTO users (UserName, UserPassword, Email, FirstName, LastName) " + "VALUES (?, ?, ?, ?, ?)"; try { ps = connection.prepareStatement(query); ps.setString(1, user.getUserName()); ps.setString(2, user.getPassword()); ps.setString(3, user.getEmail()); ps.setString(4, user.getFirstName()); ps.setString(5, user.getLastName()); //ps.setString(6, String.valueOf(user.getPhoneNumber())); //ps.setString(7, user.getAddress()); //ps.setString(8, user.getCity()); //ps.setString(9, user.getState()); //ps.setString(10, String.valueOf(user.getZipcode())); return ps.executeUpdate(); } catch (SQLException e) { System.out.println(e); return 0; } finally { DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static int insertUSerPassword(String username, String passwordhash, String salt) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; String query = "INSERT INTO userpassword (UserName, UserPassword, Salt) " + "VALUES (?, ?, ?)"; try { ps = connection.prepareStatement(query); ps.setString(1, username); ps.setString(2, passwordhash); ps.setString(3, salt); return ps.executeUpdate(); } catch (SQLException e) { System.out.println(e); return 0; } finally { DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static boolean validateUser(String password, String username) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; boolean value = true; String query = "SELECT UserName, UserPassword FROM userpassword " + "WHERE UserName = ?"; try { ps = connection.prepareStatement(query); ps.setString(1, username); rs = ps.executeQuery(); User user = new User(); while (rs.next()) { user.setUserName(rs.getString("UserName")); user.setPassword(rs.getString("UserPassword")); } //value = (user.getUserName()).equals(username) && (user.getPassword()).equals(password); } catch (SQLException e) { System.out.println(e); } finally { DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } return value; } public static int insertRole(String role) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; String query = "INSERT INTO roles (RoleName) " + "VALUES (?)"; try { ps = connection.prepareStatement(query); ps.setString(1, role); return ps.executeUpdate(); } catch (SQLException e) { System.out.println(e); return 0; } finally { DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static int insertUserRole(String username, String role) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; String query = "INSERT INTO userrole (UserName,RoleName) " + "VALUES (?, ?)"; try { ps = connection.prepareStatement(query); ps.setString(1, username); ps.setString(2, role); return ps.executeUpdate(); } catch (SQLException e) { System.out.println(e); return 0; } finally { DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static ArrayList<User> selectUsers() { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; ArrayList<User> userList = new ArrayList<User>(); String query = "SELECT * FROM users"; try { ps = connection.prepareStatement(query); rs = ps.executeQuery(); User user = null; while (rs.next()) { user = new User(); user.setUserName(rs.getString("UserName")); user.setFirstName(rs.getString("FirstName")); user.setLastName(rs.getString("LastName")); user.setEmail(rs.getString("Email")); userList.add(user); } return userList; } catch (SQLException e) { System.out.println(e); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static User selectUserRole(String username) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; ArrayList<User> userList = new ArrayList<User>(); String query = "SELECT * FROM userrole " + "WHERE UserName = ?"; try { ps = connection.prepareStatement(query); ps.setString(1, username); rs = ps.executeQuery(); User user = new User(); if (rs.next()) { user.setUserName(rs.getString("UserName")); user.setRole(rs.getString("RoleName")); } return user; } catch (SQLException e) { System.out.println(e); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static ArrayList<Role> getRoles() { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; ArrayList<Role> roleList = new ArrayList<Role>(); String query = "SELECT * FROM roles"; try { ps = connection.prepareStatement(query); rs = ps.executeQuery(); Role role = null; while (rs.next()) { role = new Role(); role.setRole(rs.getString("RoleName")); roleList.add(role); } return roleList; } catch (SQLException e) { System.out.println(e); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static User getUser(String username) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; String query = "SELECT * FROM users " + "WHERE UserName = ?"; try { ps = connection.prepareStatement(query); ps.setString(1, username); rs = ps.executeQuery(); User user = new User(); while (rs.next()) { user.setUserName(rs.getString("UserName")); user.setFirstName(rs.getString("FirstName")); user.setLastName(rs.getString("LastName")); user.setEmail(rs.getString("Email")); user.setPassword(rs.getString("User<PASSWORD>")); } return user; } catch (SQLException e) { System.out.println(e); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static int updateRole(String username, String role) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; String query = "UPDATE userrole SET " + "RoleName = ? " + "WHERE UserName = ?"; try { ps = connection.prepareStatement(query); ps.setString(1, role); ps.setString(2, username); return ps.executeUpdate(); } catch (SQLException e) { System.out.println(e); return 0; } finally { DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static String getUserRole(String username) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; String role = null; String query = "SELECT RoleName FROM userrole " + "WHERE UserName = ?"; try { ps = connection.prepareStatement(query); ps.setString(1, username); rs = ps.executeQuery(); if (rs.next()) { role = (rs.getString("RoleName")); } return role; } catch (SQLException e) { System.out.println(e); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static ArrayList<String> getUsernameRole(String role) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; ArrayList<String> list = new ArrayList<String>(); String username = null; String query = "SELECT UserName FROM userrole " + "WHERE RoleName = ?"; try { ps = connection.prepareStatement(query); ps.setString(1, role); rs = ps.executeQuery(); while (rs.next()) { username = (rs.getString("UserName")); list.add(username); } return list; } catch (SQLException e) { System.out.println(e); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static ArrayList<User> getUsers(String filepath) { ArrayList<User> userList = new ArrayList<User>(); File file = new File(filepath); try { BufferedReader in = new BufferedReader( new FileReader(file)); String line = in.readLine(); while (line != null) { StringTokenizer t = new StringTokenizer(line, "|"); String username = t.nextToken(); String email = t.nextToken(); String firstname = t.nextToken(); String lastname = t.nextToken(); String password = <PASSWORD>(); String role = t.nextToken(); User user = new User(); user.setUserName(username); user.setEmail(email); user.setFirstName(firstname); user.setLastName(lastname); user.setPassword(<PASSWORD>); user.setPassword(<PASSWORD>); user.setRole(role); userList.add(user); line = in.readLine(); } in.close(); return userList; } catch (IOException e) { System.err.println(e); return null; } } public static ArrayList<Order> selectOrders() { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; ArrayList<Order> orderList = new ArrayList<Order>(); String query = "select orders.OrderID, orders.OrderStatus, orders.Quantity*menu.price as Amount, " + "orders.ProcessTime, orders.ResponseTime, orders.Quantity, orders.UserName, menu.MenuItem from orders,menu " + " where orders.MenuNumber=menu.MenuNumber"; try { ps = connection.prepareStatement(query); rs = ps.executeQuery(); Order order = null; while (rs.next()) { order = new Order(); order.setOrderId(rs.getString("OrderID")); order.setOrderStatus(rs.getString("OrderStatus")); order.setAmount(rs.getFloat("Amount")); order.setProcessingTime(rs.getString("ProcessTime")); order.setResponseTime(rs.getString("ResponseTime")); order.setQuantity(rs.getInt("Quantity")); order.setUsername(rs.getString("UserName")); order.setMenuItem(rs.getString("MenuItem")); orderList.add(order); } return orderList; } catch (SQLException e) { System.out.println(e); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static ArrayList<User> selectCustomers() { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; ArrayList<User> userList = new ArrayList<User>(); String query = "SELECT users.UserName, Email, FirstName, LastName FROM users join userrole on users.UserName=userrole.UserName where RoleName= 'Customer'"; try { ps = connection.prepareStatement(query); rs = ps.executeQuery(); User user = null; while (rs.next()) { user = new User(); user.setUserName(rs.getString("UserName")); user.setFirstName(rs.getString("FirstName")); user.setLastName(rs.getString("LastName")); user.setEmail(rs.getString("Email")); //user.setPhoneNumber(Integer.parseInt(rs.getString("PhoneNumber"))); //user.setAddress(rs.getString("Address")); //user.setCity(rs.getString("City")); //user.setState(rs.getString("State")); //user.setZipcode(Integer.parseInt(rs.getString("Zipcode"))); userList.add(user); } System.out.println("customerList" + userList.toString()); return userList; } catch (SQLException e) { System.out.println(e); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static ArrayList<User> selectStaff() { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; ArrayList<User> userList = new ArrayList<User>(); String query = "SELECT users.UserName, Email, FirstName, LastName, RoleName FROM users join userrole on users.UserName=userrole.UserName where RoleName= 'Manager' or Rolename = 'Designer'"; try { ps = connection.prepareStatement(query); rs = ps.executeQuery(); User user = null; while (rs.next()) { user = new User(); user.setUserName(rs.getString("UserName")); user.setFirstName(rs.getString("FirstName")); user.setLastName(rs.getString("LastName")); user.setEmail(rs.getString("Email")); user.setRole(rs.getString("RoleName")); userList.add(user); } System.out.println("staffList" + userList.toString()); return userList; } catch (SQLException e) { System.out.println(e); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } } <file_sep>/web/com/mystarbucks/dao/OrdersDB.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mystarbucks.dao; import com.mystarbucks.util.DBUtil; import com.mystarbucks.business.Menu; import com.mystarbucks.business.Order; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.StringTokenizer; /** * * @author jyoti */ public class OrdersDB { public static ArrayList<Menu> selectMenus() { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; ArrayList<Menu> menuList = new ArrayList<Menu>(); String query = "SELECT * FROM menu"; try { ps = connection.prepareStatement(query); rs = ps.executeQuery(); Menu menu = null; while (rs.next()) { menu = new Menu(); menu.setMenuNumber(Integer.parseInt(rs.getString("MenuNumber"))); menu.setMenuType(rs.getString("MenuType")); menu.setPrice(Double.parseDouble(rs.getString("Price"))); menu.setMenuItem(rs.getString("MenuItem")); menuList.add(menu); } return menuList; } catch (SQLException e) { System.out.println(e); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static Menu getMenuDetails(int number) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; String query = "SELECT * FROM menu " + "WHERE MenuNumber = ?"; try { ps = connection.prepareStatement(query); ps.setString(1, String.valueOf(number)); rs = ps.executeQuery(); Menu menu = null; if (rs.next()) { menu = new Menu(); menu.setMenuNumber(Integer.parseInt(rs.getString("MenuNumber"))); menu.setMenuType(rs.getString("MenuType")); menu.setPrice(Double.parseDouble(rs.getString("Price"))); menu.setMenuItem(rs.getString("MenuItem")); } return menu; } catch (SQLException e) { System.out.println(e); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static ArrayList<Order> getOrders() { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; ArrayList<Order> orderList = new ArrayList<Order>(); String query = "SELECT * FROM orders"; try { ps = connection.prepareStatement(query); rs = ps.executeQuery(); Order order = null; while (rs.next()) { ArrayList<Menu> menuList = new ArrayList<Menu>(); order = new Order(); order.setOrderId(rs.getString("OrderID")); order.setOrderTime(rs.getString("OrderTime")); order.setProcessingTime(rs.getString("ProcessTime")); order.setResponseTime(rs.getString("ResponseTime")); order.setMenuNumber(Integer.parseInt((rs.getString("MenuNumber")))); order.setQuantity(Integer.parseInt(rs.getString("Quantity"))); order.setProcessorNumber(Double.parseDouble(rs.getString("ProcessorNumber"))); order.setServerNumber(Double.parseDouble(rs.getString("ServerNumber"))); Integer menuNumber = order.getMenuNumber(); Menu menu = getMenuDetails(menuNumber); menuList.add(menu); order.setMenuList(menuList); orderList.add(order); } return orderList; } catch (SQLException e) { System.out.println(e); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static void insertOrder(Order order, String userName) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; String id1 = "232"; String id2 = "123"; String orderStatus = "New"; String query = "INSERT INTO orders (OrderID, UserName, OrderStatus, OrderTime, ProcessTime, ResponseTime, MenuNumber, Quantity, ProcessorNumber, ServerNumber) " + "VALUES (Null, ?, ?, Now(), Now(), Now(), ?, ?, ?, ?)"; try { ps = connection.prepareStatement(query); ps.setString(1, userName); ps.setString(2, orderStatus); ps.setString(3, String.valueOf(order.getMenuNumber())); ps.setString(4, String.valueOf(order.getQuantity())); ps.setString(5, String.valueOf(id1)); ps.setString(6, String.valueOf(id2)); ps.executeUpdate(); } catch (SQLException e) { System.out.println(e); } finally { DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static void insertAmount(String userName, Double amount) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; String id1 = "232"; String id2 = "123"; String query = "INSERT INTO useramount (UserName, Total) " + "VALUES (?,?)"; try { ps = connection.prepareStatement(query); ps.setString(1, userName); ps.setString(2, String.valueOf(amount)); ps.executeUpdate(); } catch (SQLException e) { System.out.println(e); } finally { DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static void insertOrderDetails(Order order, int Tablenumber) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; String query = "INSERT INTO ordersdetails (OrderID, MenuNumber, Quantity) " + "VALUES (?, ?, ?)"; try { ps = connection.prepareStatement(query); ps.setString(1, String.valueOf(Tablenumber)); ps.setString(2, String.valueOf(order.getMenuNumber())); ps.setString(3, String.valueOf(order.getQuantity())); ps.executeUpdate(); } catch (SQLException e) { System.out.println(e); } finally { DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static int deleteOrders() { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; String query = "DELETE FROM orders"; try { ps = connection.prepareStatement(query); return ps.executeUpdate(); } catch (SQLException e) { System.out.println(e); return 0; } finally { DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static int updateOrder(String OrderId) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; String orderStatus = "Completed"; String query = "Update orders set OrderStatus=? where OrderID=?"; try { ps = connection.prepareStatement(query); ps.setString(1, orderStatus); ps.setString(2, OrderId); return ps.executeUpdate(); } catch (SQLException e) { System.out.println(e); return 0; } finally { DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static Order getOrder(String OrderId, String filepath) throws ParseException { Order order = new Order(); File file = new File(filepath); try { BufferedReader in = new BufferedReader( new FileReader(file)); String line = in.readLine(); while (line != null) { StringTokenizer t = new StringTokenizer(line, "|"); String orderNumber = t.nextToken(); if (orderNumber.equalsIgnoreCase(OrderId)) { String number = t.nextToken(); String orderTime = t.nextToken(); String processTime = t.nextToken(); String responseTime = t.nextToken(); String menuNumber = t.nextToken(); String quantity = t.nextToken(); String processorNumber = t.nextToken(); String serverNumber = t.nextToken(); SimpleDateFormat df = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa"); Date date1 = df.parse(orderTime); Date date2 = df.parse(processTime); Date date3 = df.parse(responseTime); order.setMenuNumber(Integer.parseInt(menuNumber)); order.setOrderId(OrderId); order.setOrderTime(orderTime); order.setProcessingTime(orderTime); order.setProcessorNumber(Double.parseDouble(processorNumber)); order.setServerNumber(Double.parseDouble(serverNumber)); order.setQuantity(Integer.parseInt(quantity)); order.setResponseTime(orderTime); line = in.readLine(); } } in.close(); return order; } catch (IOException e) { System.err.println(e); return null; } } public static List<Order> geTableOrders(String TNumber, String filepath) throws ParseException { List<Order> orderList = new ArrayList<Order>(); File file = new File(filepath); try { BufferedReader in = new BufferedReader( new FileReader(file)); String line = in.readLine(); while (line != null) { StringTokenizer t = new StringTokenizer(line, "|"); Order order = new Order(); String orderNumber = t.nextToken(); String number = t.nextToken(); if (number.equalsIgnoreCase(TNumber)) { String orderTime = t.nextToken(); String processTime = t.nextToken(); String responseTime = t.nextToken(); String menuNumber = t.nextToken(); String quantity = t.nextToken(); String processorNumber = t.nextToken(); String serverNumber = t.nextToken(); SimpleDateFormat df = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa"); Date date1 = df.parse(orderTime); Date date2 = df.parse(processTime); Date date3 = df.parse(responseTime); order.setMenuNumber(Integer.parseInt(menuNumber)); order.setOrderId(orderNumber); order.setOrderTime(orderTime); order.setProcessingTime(orderTime); order.setProcessorNumber(Double.parseDouble(processorNumber)); order.setServerNumber(Double.parseDouble(serverNumber)); order.setQuantity(Integer.parseInt(quantity)); order.setResponseTime(orderTime); orderList.add(order); line = in.readLine(); } } in.close(); return orderList; } catch (IOException e) { System.err.println(e); return null; } } } <file_sep>/src/java/com/girlzone/servlet/JavaConnectDb.java package com.girlzone.servlet; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.naming.InitialContext; import javax.sql.DataSource; import org.apache.jasper.tagplugins.jstl.core.Catch; public class JavaConnectDb { public static Connection connectDb() { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/nbad?autoReconnect=true&useSSL=false", "root", "root"); Statement myStmt = conn.createStatement(); ResultSet myRs = myStmt.executeQuery("select * from user"); while (myRs.next()) { //System.out.println(myRs.getString("name") + ", " + myRs.getString("email")); } } catch (Exception e) { System.err.println(e); } return conn; } } /* package com.girlzone.servlet; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.naming.InitialContext; import javax.sql.DataSource; import org.apache.jasper.tagplugins.jstl.core.Catch; public class JavaConnectDb { public static Connection connectDb() { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://assignment2.czcorxm8kkgd.us-west-2.rds.amazonaws.com:3306/nbad?user=bnakka&password=<PASSWORD>"); Statement myStmt = conn.createStatement(); ResultSet myRs = myStmt.executeQuery("select * from user"); while (myRs.next()) { //System.out.println(myRs.getString("name") + ", " + myRs.getString("email")); } } catch (Exception e) { System.err.println(e); } return conn; } } */<file_sep>/src/java/com/girlzone/servlet/UserController.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.girlzone.servlet; import com.girlzone.business.Order; import com.girlzone.business.Password; import com.girlzone.business.User; import com.girlzone.dao.OrdersDB; import com.girlzone.util.PasswordUtil; import com.girlzone.dao.UserDB; import java.io.IOException; import java.io.PrintWriter; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author jyoti */ public class UserController extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet UserController</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet UserController at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String abc = "hi"; String action = request.getParameter("action"); String url = ""; if (abc.equals("hi")) { String serverInfo = request.getServerName() + " :: " + request.getServerPort(); Cookie cookie1 = new Cookie("host", request.getServerName()); cookie1.setMaxAge(60 * 60 * 24 * 365 * 2); cookie1.setPath("/"); response.addCookie(cookie1); Cookie cookie2 = new Cookie("port", String.valueOf(request.getServerPort())); cookie2.setMaxAge(60 * 60 * 24 * 365 * 2); cookie2.setPath("/"); response.addCookie(cookie2); Cookie cookie = new Cookie("server", serverInfo); log("Cookie" + cookie1.getValue()); response.addCookie(cookie); response.addCookie(cookie); url = "/index.jsp"; } ServletContext sc = getServletContext(); HttpSession session = request.getSession(); // String url = "/index.jsp"; String msg; User user = null; String username = request.getParameter("username"); String password = request.getParameter("password"); if (action == null) { url = "/index.jsp"; } if (action.equals("deleteorder")) { String orderId = request.getParameter("param1"); OrdersDB.updateOrder(orderId); ArrayList<Order> orderList = UserDB.selectOrders(); session.setAttribute("orderList", orderList); url = "/waiter.jsp"; } if (action.equals("deleteorderbar")) { String orderId = request.getParameter("param1"); //OrdersDB.deleteOrder(orderId); List<Order> orderList = OrdersDB.getOrders(); session.setAttribute("orderList", orderList); url = "/barattend.jsp"; } if (action.equals("signup")) { String usernameCustomer = request.getParameter("username"); String firstname = request.getParameter("fname"); String lastaname = request.getParameter("lname"); String role = request.getParameter("role"); String email = request.getParameter("email"); String passwordCustomer = request.getParameter("password"); //String address = request.getParameter("address"); //String city = request.getParameter("city"); //String state = request.getParameter("state"); //String zipcode = request.getParameter("zipcode"); //String phonenumber = request.getParameter("number"); try { PasswordUtil.checkPasswordStrength(password); } catch (Exception ex) { Logger.getLogger(ManagerController.class.getName()).log(Level.SEVERE, null, ex); String pass = "<PASSWORD>"; session.setAttribute("password", pass); sc.getRequestDispatcher("/signup.jsp") .forward(request, response); } String passwordhash = null; String salt = PasswordUtil.getSalt(); try { passwordhash = PasswordUtil.hashAndSaltPassword(passwordCustomer, salt); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ManagerController.class.getName()).log(Level.SEVERE, null, ex); } User userCustomer = new User(); userCustomer.setEmail(email); userCustomer.setLastName(lastaname); userCustomer.setFirstName(firstname); userCustomer.setPassword(<PASSWORD>); userCustomer.setRole(role); userCustomer.setUserName(usernameCustomer); //userCustomer.setAddress(address); //userCustomer.setCity(city); //userCustomer.setZipcode(Integer.parseInt(zipcode)); //userCustomer.setState(state); //userCustomer.setPhoneNumber(Integer.parseInt(phonenumber)); // Integer i=UserDB.insertUser(userCustomer); Integer i = UserDB.insertUser(userCustomer); UserDB.insertUSerPassword(username, passwordhash, salt); if (i == 1) { if (!(role.isEmpty())) { UserDB.insertUserRole(username, role); url = "/login.jsp"; } } else { String msg3 = "User already exist"; request.setAttribute("msg3", msg3); url = "/signup.jsp"; } } if (action.equals("login")) { Password pass; pass = UserDB.getPassword(username); String passwordhash = null; try { String salt = pass.getSalt(); passwordhash = PasswordUtil.hashPassword(password + salt); log("passwordHash" + passwordhash); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } Boolean value = UserDB.validateUser(passwordhash, username); log("Value" + value); if (value) { user = UserDB.getUser(username); String role = UserDB.getUserRole(username); user.setRole(role); session.setAttribute("user", user); log("Role " + role); if (role.equals("Manager")) { url = "/manager.jsp"; } else if (role.equals("Designer")) { ArrayList<Order> orderList = UserDB.selectOrders(); request.setAttribute("orderList", orderList); url = "/waiter.jsp"; } else if (role.equals("Customer")) { String cookie_customername = user.getUserName(); Cookie c = new Cookie("cookie_customername", cookie_customername); c.setMaxAge(60 * 60 * 24 * 365 * 2); c.setPath("/"); response.addCookie(c); log(user.getUserName()); url = "/index.jsp"; } } else { msg = "Invalid Credentials"; request.setAttribute("message", msg); url = "/login.jsp"; } //user = UserDB.getUser(username); } else if (action.equals("logout")) { if (session.getAttribute("user") != null) { session.invalidate(); url = "/login.jsp"; } else { url = "/login.jsp"; } } sc.getRequestDispatcher(url) .forward(request, response); processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
8881471277cb8b8aafeb7828583fbc8a5ac4a2a6
[ "Java", "INI" ]
5
INI
Udit-K/Victory-Sports
103aa9522d29f05cae8f290c6ace8413cb11c402
470b15786dec31649b34d7963cd3f8046a3eb8bf
refs/heads/master
<file_sep>package problems_A; import java.util.Scanner; public class A1009 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int[] ar1 = new int[n]; for (int i = 0; i < n; i++) { ar1[i] = in.nextInt(); } int[] ar2 = new int[m]; for (int i = 0; i < m; i++) { ar2[i] = in.nextInt(); } int cnt = 0; for (int i = 0, j = 0; i < n && j < m; i++) { if (ar2[j] >= ar1[i]) { cnt++; j++; } } System.out.println(cnt); } }<file_sep>package problems_B; import java.util.Scanner; public class B1080 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] res = new int[n]; for (int i = 0; i < n; i++) { int l = in.nextInt(); int r = in.nextInt(); if (r % 2 != 0 && l % 2 == 0) res[i] = (r - l + 1) / -2; else if (r % 2 == 0 && l % 2 != 0) res[i] = (r - l + 1) / 2; else if (l % 2 == 0 && r % 2 == 0) res[i] = (l + r) / 2; else if (r % 2 != 0 && l % 2 != 0) res[i] = (l + r) / -2; else if (l - r == 0) res[i] = l % 2 == 0 ? l : -1 * l; } for (int i : res) { System.out.println(i); } } // private static int computeAnswer(int l, int r) { // int res = 0; // for (int i = l; i <= r; i++) { // res += i % 2 == 0 ? i : i * -1; // } // return res; // } } <file_sep>package problems_A; import java.util.Scanner; public class A1080 { public static void main(String[] args) { Scanner in = new Scanner(System.in); double friends = in.nextInt(); double pagesPerNotebook = in.nextInt(); double redSheetsNeeded = 2 * friends; double greenSheetsNeeded = 5 * friends; double blueSheetsNeeded = 8 * friends; int res = (int) Math.ceil(redSheetsNeeded / pagesPerNotebook); res += (int) Math.ceil(greenSheetsNeeded / pagesPerNotebook); res += (int) Math.ceil(blueSheetsNeeded / pagesPerNotebook); System.out.println(res); } }<file_sep>package problems_A; import java.util.Scanner; public class A1060 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); String s = in.next(); int count8 = 0; for (char c : s.toCharArray()) { count8 = c == '8' ? count8 + 1 : count8; } System.out.println((int) Math.min(count8, (Math.floor(n / 11)))); } }<file_sep>package problems_A; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class A1028 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); List<String> list = new ArrayList<>(); int indexOfFirstB = -1; int indexOfFirstBRow = -1; for (int i = 0; i < n; i++) { String s = in.next(); list.add(s); if (indexOfFirstB == -1) { indexOfFirstB = s.indexOf('B'); indexOfFirstBRow = i; } } int cntB = 0; for (int i = 0; i < n; i++) cntB = list.get(i).contains("B") ? cntB + 1 : cntB; int[] center = new int[2]; center[0] = (indexOfFirstB + (cntB - 1) / 2) + 1; center[1] = indexOfFirstBRow + (cntB - 1) / 2 + 1; System.out.println(center[1] + " " + center[0]); } } <file_sep>package problems_B; import java.util.Scanner; public class B1017 { public static void main(String[] args) { Scanner in = new Scanner(System.in); long n = in.nextLong(); String a = in.next(); String b = in.next(); long[] cnts = new long[4]; for (int i = 0; i < n; i++) { String curr = Character.toString(a.charAt(i)) + Character.toString(b.charAt(i)); if ("00".equals(curr)) cnts[0]++; else if ("10".equals(curr)) cnts[1]++; else if ("11".equals(curr)) cnts[2]++; else cnts[3]++; } System.out.println(cnts[0] * cnts[1] + cnts[0] * cnts[2] + cnts[3] * cnts[1]); } } <file_sep>package problems_A; import java.util.Scanner; public class A1027 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { int size = in.nextInt(); String s = in.next(); boolean isPalindrome = true; //loop over string s for (int j = 0; j < size / 2; j++) { char start = s.charAt(j); char end = s.charAt(size - j - 1); if (Math.abs(start - end) > 2 || Math.abs(start - end) == 1) { isPalindrome = false; break; } } sb.append(isPalindrome ? "YES" : "NO"); sb.append("\n"); } System.out.println(sb.toString().trim()); } }
4eb4704ae5ade9ba09939c20fa7855862bc2a16f
[ "Java" ]
7
Java
Ephilipz/codeforces
690ba6c2a1ec7adbdb090f0a8b8647a883c47c7f
d639f12f7dad923dd97fc45af1ee02cc715ccc78
refs/heads/main
<file_sep># CienciaDatos PAPD - Ciencia de datos ## GIT Git es una herramiento para llevar el control de proyectos. **Colección** de Directorios y archivos Incluye: - Manejo de Versiones - Facilita la colaboración - Integra cambios paralelos al mismo código - Diferentes personas pueden trabajar en la misma parte del código - Puedo saber quien, cuando y donde cambiaron alguna parte del código No utiliza un modelo lineal, es algo mas complejo, pues puede crear ramas del mismo código para que 2 o mas personas lo trabajen y posteriormente se pueda *integrar* en la versión difinitiva Como exactamente se representa tipos de objetos: - blob (array(byte)) - map <string, tree | blob> - commit = estructura Cada rama es un snapshot de los directorios y archivos, con metadata adicional que ayudan posteriormente a la unificación del código. Al final lo que guarda son punteros en notación hexadecimal, con una referencia en lenguaje entendible. ![Conceptos principales](img/git.jpg) ### Comandos básicos Comando | descripción -- | -- init | Inicia un directorio para que trabaje con git add | añade un archivo o directorio al repositorio status | Despliega el status de nuestro repositorio checkout | elimina los cambios realizados commit | aplica los cambios realizados push | Envía los cambios al repositorio general pull | obtiene los cambios del repositorio general ### Pasos para iniciar un nuevo repositorio 1. git init 2. git add README.md 3. git commit -m "first commit" 4. git branch -M main 5. git remote add origin <URL/repositorio.git> 6. git push -u origin main ### Pasos para agregar un archivo 1. Crear el archivo - make filename 2. git add filename ### pasos para enviarlo a la nube 1. git commit -m "Se agrega el archivo animal.py" ![Conceptos principales](img/Img1.png) 2. git push ![Conceptos principales](img/Img2.png) ### pasos para crear un branch 1. git checkout -b gato 2. git checkout -b perro ![Conceptos principales](img/img3.png) 3. Cambiar al branch que se necesita trabajar (gato) git checkout gato --> hacer cambios a gato git checkout perro --> hacer cambios a perro ## pasos para hacer merge de ambos cambios a master 1. git checkout main 2. git merge gato ![Conceptos principales](img/Img4.png) 3. git commit 4. git push <file_sep>import sys from datetime import datetime from datetime import date def main(): try: dia = input('Ingresa tu día de nacimiento: ') dia = int(dia) mes = input('Ingresa tu mes de nacimiento: ') mes = int(mes) if mes < 1 or mes > 12: e = 'Error: el mes debe estar entre 1 y 12' raise Exception('Error: Valor incorrecto') año = input('Ingresa tu año de nacimiento: ') año = int(año) hoyaño = datetime.today().year hoymes = datetime.today().month hoydia = datetime.today().day edad = hoyaño - año if mes > hoymes: edad = edad - 1 edadmes = 12 - (mes - hoymes) else: edadmes = hoymes - mes print(str(edadmes)) if hoydia > dia: edaddia = hoydia - dia else: edadmes = edadmes -1 edaddia = 30 - (dia - hoydia) print('Su edad es:{} años {} meses {} días'.format(edad,edadmes,edaddia)) except ValueError as f: print('Error: Debe ingresar un entero') except Exception as f: print(e) if __name__ == '__main__': main()<file_sep>import sys def main(): try: elementos = sys.argv[1] lista = [] a = 1 while a <= int(elementos): valor = input('Ingrese registro {}: '.format(a)) lista.append(valor) a = a+1 salida = '' for a in lista: salida = salida + str(a) print(salida) except IndexError as e: print('Error: Debe ingresar un parámetro') except ValueError as e: print('Error: Debe ingresar un entero') except Exception as e: print(e) if __name__ == '__main__': main()<file_sep>import sys def main(): try: Nolistas = sys.argv[1] Nolistas = int(Nolistas) print(Nolistas) glista = [] for a in range(Nolistas): glista.append([]) b = 1 valor = input('Ingrese elemento {} de la lista {}, si desea terminar la lista, ingrese 0: '.format(b,a)) print(valor) while int(valor) != 0: glista[a].append(valor) print(glista) b = b+1 valor = input('Ingrese elemento {} de la lista {}, si desea terminar la lista, ingrese 0: '.format(b,a)) print(len(glista)) promedio = [] for x in range(Nolistas): print('Esta es la lista ',glista[x]) suma = 0 for y in range(2): suma = suma + glista[x][y] print(str(suma)) except IndexError as e: print(e) except ValueError as e: print('Error: Debe ingresar un entero') except Exception as e: print(e) if __name__ == '__main__': main()<file_sep>import sys def main(): try: entrada = sys.argv[1] entrada = int(entrada) segundos = int(entrada) % 60 operador = int(entrada) // 60 minutos = operador % 60 hora = operador // 60 if hora > 24: raise Exception("Error: El valor debe ser menor a 90000") print("Horas: {} Minutos: {} Segundos: {} ".format(hora,minutos,segundos)) except IndexError as e: print('Error: Debe ingresar un parámetro') except ValueError as e: print('Error: Debe ingresar un entero') except Exception as e: print(e) if __name__ == '__main__': main()
ca046f343bbbe63d3bb8de00a61c579eca846ccc
[ "Markdown", "Python" ]
5
Markdown
KatiraOrellana/CienciaDatos
5d95b908a9b6e60c4473b2e372b62a0e0beb5734
c272a6d0b3a5ddc324f9b7bd061ff11e8e96d5ca
refs/heads/master
<file_sep>//<NAME> - 362963 //Código compilado e executado no terminal do Ubuntu #include <stdio.h> #include <stdlib.h> #include <math.h> int menu() { int escolha; printf("\nQuadraturas de Gauss-Legendre aplicadas a função F(x) = x^2 - x*log(x)\n"); printf("1 - Polinômio de Legendre com 1 ponto(s)\n"); printf("2 - Polinômio de Legendre com 2 ponto(s)\n"); printf("3 - Polinômio de Legendre com 3 ponto(s)\n"); printf("4 - Polinômio de Legendre com 4 ponto(s)\n"); printf("5 - Polinômio de Legendre com 5 ponto(s)\n"); printf("0 - Sair"); printf("\nEscolha a opção com o número de pontos de Legendre desejado: "); scanf("%d", &escolha); return escolha; } double parametrizacao(double limiteA, double limiteB, double s) { double P; P=((limiteA + limiteB)/2) + ((limiteB - limiteA)/2)*s; return P; } double funcao(double x) { double F; F=pow(x,2) - x*log(x); return F; } double calculaIntegral (int grau, double limiteInf, double limiteSup, double tamanhoIntervalo, int particao) { double p1, p2, p3, p4, p5; double integral=0; double subIntervalo; int contador; subIntervalo=tamanhoIntervalo/particao; for (contador=1; contador<=particao; contador++) { limiteSup=limiteInf+subIntervalo; switch(grau) { case 1: p1=funcao(parametrizacao(limiteInf,limiteSup,0))*2; integral=(((limiteSup-limiteInf)/2)*p1)+integral; break; case 2: p1=funcao(parametrizacao(limiteInf,limiteSup,-0.5773)); p2=funcao(parametrizacao(limiteInf,limiteSup,0.5773)); integral=(((limiteSup-limiteInf)/2)*(p1+p2))+integral; break; case 3: p1=funcao(parametrizacao(limiteInf,limiteSup,-0.7745))*0.5556; p2=funcao(parametrizacao(limiteInf,limiteSup,0))*0.8889; p3=funcao(parametrizacao(limiteInf,limiteSup,0.7745))*0.5556; integral=(((limiteSup-limiteInf)/2)*(p1+p2+p3))+integral; break; case 4: p1=funcao(parametrizacao(limiteInf,limiteSup,-0.8611))*0.3478; p2=funcao(parametrizacao(limiteInf,limiteSup,-0.3399))*0.6521; p3=funcao(parametrizacao(limiteInf,limiteSup,0.3399))*0.6521; p4=funcao(parametrizacao(limiteInf,limiteSup,0.8611))*0.3478; integral=(((limiteSup-limiteInf)/2)*(p1+p2+p3+p4))+integral; break; case 5: p1=funcao(parametrizacao(limiteInf,limiteSup,-0.9061))*0.2369; p2=funcao(parametrizacao(limiteInf,limiteSup,-0.5384))*0.4786; p3=funcao(parametrizacao(limiteInf,limiteSup,0))*0.5688; p4=funcao(parametrizacao(limiteInf,limiteSup,0.5384))*0.4786; p5=funcao(parametrizacao(limiteInf,limiteSup,0.9061))*0.2369; integral=(((limiteSup-limiteInf)/2)*(p1+p2+p3+p4+p5))+integral; break; } limiteInf=limiteSup; } return integral; } int main(int argc, char const *argv[]) { double a, b, t, delta; double integral_1, integral_2; int particao_1, particao_2; int opcao; opcao=menu(); while(opcao != 0) { system("clear"); printf("\nEntre com o valor do limite inferior: "); scanf("%lf", &a); printf("\nEntre com o valor do limite superior: "); scanf("%lf", &b); printf("\nEntre com o valor da tolerância: "); scanf("%lf", &t); printf("\ncalculando...\n"); delta=b-a; particao_1=1; particao_2=5; do { integral_1=calculaIntegral(opcao,a,b,delta,particao_1); integral_2=calculaIntegral(opcao,a,b,delta,particao_2); particao_1=particao_2; particao_2=particao_2 + 5; } while((fabs(integral_2 - integral_1)) >= t); printf("\nO valor da integral é igual a %lf\n", integral_2); opcao=menu(); } system("clear"); return EXIT_SUCCESS; } <file_sep> public class Operacoes { public static double[][] matrizIdentidade(int dimensao) { double[][] matriz_identidade = new double[dimensao][dimensao]; for(int i=0; i<dimensao; i++) { for(int j=0; j<dimensao; j++) { if(i==j) matriz_identidade[i][j] = 1; else matriz_identidade[i][j] = 0; } } return matriz_identidade; } public static double normalizar(double[] vetor) { double vetor_normalizado, somatorio=0; int tamanho = vetor.length; for(int i=0; i<tamanho; i++) { somatorio = somatorio + (vetor[i]*vetor[i]); } vetor_normalizado = Math.sqrt(somatorio); return vetor_normalizado; } public static double[] divisaoVetorEscalar(double[] vetor, double escalar) { int tamanho = vetor.length; double[] resultado = new double[tamanho]; for(int i=0; i<tamanho; i++) { resultado[i] = vetor[i]/escalar; } return resultado; } public static double[] multiplicacaoMatrizVetor(double[][] matriz, double[] vetor) { double parcial; int tamanho = matriz.length; double[] resultado = new double[tamanho]; for(int i=0; i<tamanho; i++) { parcial=0; for(int j=0; j<tamanho; j++) { parcial = parcial + matriz[i][j]*vetor[j]; } resultado[i] = parcial; } return resultado; } public static double multiplicacaoVetorVetor(double[] vetor_1, double[] vetor_2) { double resultado=0; int tamanho = vetor_1.length; for(int i=0; i<tamanho; i++) { resultado = resultado + (vetor_1[i]*vetor_2[i]); } return resultado; } public static double[][] multiplicacaoMatrizEscalar(double[][] matriz, double escalar) { int dimensao = matriz.length; double[][] matriz_resultado = new double[dimensao][dimensao]; for(int i=0; i<dimensao; i++) { for(int j=0; j<dimensao; j++) { matriz_resultado[i][j] = matriz[i][j] * escalar; } } return matriz_resultado; } public static double[][] subtracaoMatrizMatriz(double[][] matriz_1, double[][] matriz_2) { int dimensao = matriz_1.length; double[][] matriz_resultado = new double[dimensao][dimensao]; for(int i=0; i<dimensao; i++) { for(int j=0; j<dimensao; j++) { matriz_resultado[i][j] = matriz_1[i][j] - matriz_2[i][j]; } } return matriz_resultado; } public static double discosGerschgorin(double[][] matriz, int indice) { double somatorio=0, limite_superior, limite_inferior; int tamanho = matriz.length; for(int i=0; i<tamanho; i++) { if(i != indice) somatorio = somatorio + Math.abs(matriz[indice][i]); } limite_inferior = matriz[indice][indice] - somatorio; limite_superior = matriz[indice][indice] + somatorio; return (limite_inferior*indice); } }<file_sep>//<NAME> - 362963 //Código compilado e executado no terminal do Ubuntu #include <stdio.h> #include <stdlib.h> #include <math.h> int menu() { int escolha; printf("\nFórmulas abertas de Newton-Cotes aplicadas a função F(x) = x^2 - x*log(x)\n"); printf("1 - Polinômio de substituição com grau 1\n"); printf("2 - Polinômio de substituição com grau 2\n"); printf("3 - Polinômio de substituição com grau 3\n"); printf("4 - Polinômio de substituição com grau 4\n"); printf("5 - Polinômio de substituição com grau 5\n"); printf("0 - Sair"); printf("\nEscolha a opção com grau do polinômio de substituição desejado: "); scanf("%d", &escolha); return escolha; } double funcao(double x) { double F; F=pow(x,2) - x*log(x); return F; } double calculaIntegral (int grau, double limiteInf, double limiteSup, double tamanhoIntervalo, int particao) { double Fx0, Fx1, Fx2, Fx3, Fx4, Fx5; double integral=0; double subIntervalo; int contador; for (contador=1; contador<=particao; contador++) { switch(grau) { case 1: subIntervalo=(tamanhoIntervalo/3)/particao; Fx0=funcao(limiteInf + subIntervalo); Fx1=funcao(limiteInf + 2*subIntervalo); limiteInf=limiteInf + 3*subIntervalo; integral=((3*subIntervalo/2) * (Fx0 + Fx1))+integral; break; case 2: subIntervalo=(tamanhoIntervalo/4)/particao; Fx0=funcao(limiteInf + subIntervalo); Fx1=funcao(limiteInf + 2*subIntervalo); Fx2=funcao(limiteInf + 3*subIntervalo); limiteInf=limiteInf + 4*subIntervalo; integral=((4*subIntervalo/3) * (2*Fx0 - Fx1 + 2*Fx2))+integral; break; case 3: subIntervalo=(tamanhoIntervalo/5)/particao; Fx0=funcao(limiteInf + subIntervalo); Fx1=funcao(limiteInf + 2*subIntervalo); Fx2=funcao(limiteInf + 3*subIntervalo); Fx3=funcao(limiteInf + 4*subIntervalo); limiteInf=limiteInf + 5*subIntervalo; integral=((5*subIntervalo/24) * (11*Fx0 + Fx1 + Fx2 + 11*Fx3))+integral; break; case 4: subIntervalo=(tamanhoIntervalo/6)/particao; Fx0=funcao(limiteInf + subIntervalo); Fx1=funcao(limiteInf + 2*subIntervalo); Fx2=funcao(limiteInf + 3*subIntervalo); Fx3=funcao(limiteInf + 4*subIntervalo); Fx4=funcao(limiteInf + 5*subIntervalo); limiteInf=limiteInf + 6*subIntervalo; integral=((6*subIntervalo/20) * (11*Fx0 - 14*Fx1 + 26*Fx2 - 14*Fx3 + 11*Fx4))+integral; break; case 5: subIntervalo=(tamanhoIntervalo/7)/particao; Fx0=funcao(limiteInf + subIntervalo); Fx1=funcao(limiteInf + 2*subIntervalo); Fx2=funcao(limiteInf + 3*subIntervalo); Fx3=funcao(limiteInf + 4*subIntervalo); Fx4=funcao(limiteInf + 5*subIntervalo); Fx5=funcao(limiteInf + 6*subIntervalo); limiteInf=limiteInf + 7*subIntervalo; integral=((7*subIntervalo/1440) * (611*Fx0 - 453*Fx1 + 562*Fx2 + 562*Fx3 - 453*Fx4 + 611*Fx5))+integral; break; } } return integral; } int main(int argc, char const *argv[]) { double a, b, t, delta; double integral_1, integral_2; int particao_1, particao_2; int opcao; int passo; opcao=menu(); while(opcao != 0) { passo=0; system("clear"); printf("\nEntre com o valor do limite inferior: "); scanf("%lf", &a); printf("\nEntre com o valor do limite superior: "); scanf("%lf", &b); printf("\nEntre com o valor da tolerância: "); scanf("%lf", &t); printf("\ncalculando...\n"); delta=b-a; particao_1=1; particao_2=5; do { integral_1=calculaIntegral(opcao,a,b,delta,particao_1); integral_2=calculaIntegral(opcao,a,b,delta,particao_2); particao_1=particao_2; particao_2=particao_2 + 5; passo++; } while(((fabs(integral_2 - integral_1)) / integral_1) >= t); printf("\nApós %d passo(s), a tolerância foi atingida, e o valor da integral é igual a %.10f\n", passo, integral_2); opcao=menu(); } system("clear"); return EXIT_SUCCESS; }<file_sep>//<NAME> - 362963 //Compilado e executado no Ubuntu import java.util.ArrayList; public class QR { public static void main(String[] args) throws Exception { String endereco_matriz = "Matriz.txt"; double[][] matriz_A = ManipularArquivo.lerMatriz(endereco_matriz); int dimensao_matriz = matriz_A.length; String endereco_tolerancia = "Tolerancia.txt"; double tolerancia = ManipularArquivo.lerEscalar(endereco_tolerancia); double e = 0; double[][] matriz_Ast = new double[dimensao_matriz][dimensao_matriz]; double[][] matriz_Rst = new double[dimensao_matriz][dimensao_matriz]; double[][] matriz_Qst = new double[dimensao_matriz][dimensao_matriz]; double[][] matriz_Q = new double[dimensao_matriz][dimensao_matriz]; ArrayList<double[][]> matrizes = new ArrayList<double[][]>(); matriz_Q = Operacoes.matrizIdentidade(dimensao_matriz); matriz_Ast = matriz_A; do { matrizes = Operacoes.construir_QR(matriz_Ast); matriz_Rst = matrizes.get(0); matriz_Qst = matrizes.get(1); matriz_Q = Operacoes.multiplicacaoMatrizMatriz(matriz_Q, matriz_Qst); matriz_Ast = Operacoes.multiplicacaoMatrizMatriz(matriz_Rst, matriz_Qst); e = Operacoes.normaMatricial(matriz_Ast); }while(e > tolerancia); String endereco_matriz_Entrada = "MatrizEntrada.txt"; ManipularArquivo.escreverMatriz(endereco_matriz_Entrada, matriz_A); String endereco_matriz_QR = "MatrizQR.txt"; ManipularArquivo.escreverMatriz(endereco_matriz_QR, matriz_Q); String endereco_matriz_Diagonal = "MatrizDiagonal.txt"; ManipularArquivo.escreverMatriz(endereco_matriz_Diagonal, matriz_Ast); System.out.println("Matrizes geradas com sucesso."); } }<file_sep>//<NAME> - 362963 //Código compilado e executado no terminal do Ubuntu #include <stdio.h> #include <stdlib.h> #include <math.h> int menu() { int escolha; printf("\nQuadraturas de Gauss-Hermite aplicadas a integral na forma I[-infinito,infinito] = e^(-x^2) * F(x),\n"); printf("onde F(x) = x^3 - (x^2) - 1.\n"); printf("1 - Polinômio de Hermite com 1 ponto(s)\n"); printf("2 - Polinômio de Hermite com 2 ponto(s)\n"); printf("3 - Polinômio de Hermite com 3 ponto(s)\n"); printf("4 - Polinômio de Hermite com 4 ponto(s)\n"); printf("5 - Polinômio de Hermite com 5 ponto(s)\n"); printf("5 - Polinômio de Hermite com 6 ponto(s)\n"); printf("0 - Sair"); printf("\nEscolha a opção com o número de pontos de Hermite desejado: "); scanf("%d", &escolha); return escolha; } double funcao(double x) { double F; F=pow(x,3) - pow(x,2) - 1; return F; } double calculaIntegral (int op) { double p1,p2,p3,p4,p5,p6; double integral; switch(op) { case 1: p1=funcao(0)*1.7724; integral=p1; break; case 2: p1=funcao(-0.7071)*0.8862; p2=funcao(0.7071)*0.8862; integral=p1+p2; break; case 3: p1=funcao(-1.2247)*0.2954; p2=funcao(0)*1.1816; p3=funcao(1.2247)*0.2954; integral=p1+p2+p3; break; case 4: p1=funcao(-1.6506)*0.0813; p2=funcao(-0.5246)*0.8049; p3=funcao(0.5246)*0.8049; p4=funcao(1.6506)*0.0813; integral=p1+p2+p3+p4; break; case 5: p1=funcao(-2.0201)*0.0199; p2=funcao(-0.9585)*0.3936; p3=funcao(0)*0.9453; p4=funcao(0.9585)*0.3936; p5=funcao(2.0201)*0.0199; integral=p1+p2+p3+p4+p5; break; case 6: p1=funcao(-2.3506)*0.0045; p2=funcao(-1.3358)*0.1570; p3=funcao(-0.4360)*0.7246; p4=funcao(0.4360)*0.7246; p5=funcao(1.3358)*0.1570; p6=funcao(2.3506)*0.0045; integral=p1+p2+p3+p4+p5+p6; break; } return integral; } int main(int argc, char const *argv[]) { double integral; int opcao; opcao=menu(); while(opcao != 0) { system("clear"); integral=calculaIntegral(opcao); printf("\ncalculando...\n"); printf("\nO valor da integral é igual a %lf\n", integral); opcao=menu(); } system("clear"); return EXIT_SUCCESS; }<file_sep>public class Operacoes { public static double[][] matrizIdentidade(int dimensao) { double[][] matriz_identidade = new double[dimensao][dimensao]; for(int i=0; i<dimensao; i++) { for(int j=0; j<dimensao; j++) { if(i==j) matriz_identidade[i][j] = 1; else matriz_identidade[i][j] = 0; } } return matriz_identidade; } public static double normalizar(double[] vetor) { double vetor_normalizado, somatorio=0; int tamanho = vetor.length; for(int i=0; i<tamanho; i++) { somatorio = somatorio + (vetor[i]*vetor[i]); } vetor_normalizado = Math.sqrt(somatorio); return vetor_normalizado; } public static double[][] multiplicacaoMatrizMatriz(double[][] matriz_A, double[][] matriz_B) { int tamanho = matriz_A.length; double[][] resultado = new double[tamanho][tamanho]; for (int i = 0; i < tamanho; i++) for (int j = 0; j < tamanho; j++) for (int k = 0; k < tamanho; k++) resultado[i][j] += matriz_A[i][k]*matriz_B[k][j]; return resultado; } public static double[][] transposta(double[][] matriz) { int tamanho = matriz.length; double[][] matriz_transposta = new double[tamanho][tamanho]; for(int i=0; i<tamanho; i++) { for(int j=0; j<tamanho; j++) { matriz_transposta[i][j] = matriz[j][i]; } } return matriz_transposta; } public static double normaMatricial(double[][] matriz) { double norma=0; int tamanho = matriz.length; for(int i=0; i<tamanho; i++) { for(int j=0; j<tamanho; j++) { if(j<i) norma = norma + Math.abs(matriz[i][j]); } } norma = Math.sqrt(norma); return norma; } public static double[][] gerar_J(int indice_i, int indice_j, int tamanho, double a_jj, double a_ij, double a_ii) { double[][] matriz_J = new double[tamanho][tamanho]; double theta; if(a_ii == a_jj) theta = Math.PI/4; else theta = Math.atan((2*a_ij)/(a_ii-a_jj))/2; matriz_J = Operacoes.matrizIdentidade(tamanho); matriz_J[indice_j][indice_j] = Math.cos(theta); matriz_J[indice_j][indice_i] = -Math.sin(theta); matriz_J[indice_i][indice_j] = Math.sin(theta); matriz_J[indice_i][indice_i] = Math.cos(theta); return matriz_J; } }<file_sep>//<NAME> - 362963 //Código compilado e executado no terminal do Ubuntu #include <stdio.h> #include <stdlib.h> #include <math.h> double funcao_Fx(double x) { double F; F=pow(x,2)-x*log(x); return F; } double parametrizacao_1(double a, double b, double s) { double Xs; Xs = ((a+b)/2)+((b-a)/2)*(exp(s)-exp(-s))/(exp(s)+exp(-s)); return Xs; } double funcao_Gs(double limiteA, double limiteB, double S) { double G; double xS; xS=parametrizacao_1(limiteA, limiteB, S); G=(4*funcao_Fx(xS))/(exp(2*S)+2+exp(-2*S)); return G; } double simpsomTresOitavos(double limiteInf, double limiteSup, double sI, double sF, double particao) { long double Fx0, Fx1, Fx2, Fx3; long double I=0, subIntervalo, tamanhoIntervalo; int contador; tamanhoIntervalo=2*sF; subIntervalo=tamanhoIntervalo/particao; for (contador=1; contador<=particao; contador++) { subIntervalo=(tamanhoIntervalo/3)/particao; Fx0=funcao_Gs(limiteInf, limiteSup, sI); Fx1=funcao_Gs(limiteInf, limiteSup, sI + subIntervalo); Fx2=funcao_Gs(limiteInf, limiteSup, sI + 2*subIntervalo); Fx3=funcao_Gs(limiteInf, limiteSup, sI + 3*subIntervalo); sI=sI + 3*subIntervalo; I=((3*subIntervalo/8) * (Fx0 + 3*Fx1 + 3*Fx2 + Fx3))+I; } return I; } double calculaIntegral(double inferior, double superior, double pontoCorte, double tolerancia) { double I_1, I_2; double particao_1, particao_2; particao_1=1; particao_2=5; do { I_1=simpsomTresOitavos(inferior, superior, -pontoCorte, pontoCorte, particao_1); I_2=simpsomTresOitavos(inferior, superior, -pontoCorte, pontoCorte, particao_2); particao_1=particao_2; particao_2=particao_2 + 5; } while((fabs(I_2 - I_1)/I_1) >= tolerancia); return I_2; } int main(int argc, char const *argv[]) { double a, b, t; double integral_1, integral_2; double S_1, S_2; printf("\nExponencial simples aplicada a função F(x) = x^2 - x*log(x)"); printf("\nEntre com o valor do limite inferior: "); scanf("%lf", &a); printf("\nEntre com o valor do limite superior: "); scanf("%lf", &b); printf("\nEntre com o valor da tolerância: "); scanf("%lf", &t); printf("\ncalculando...\n"); S_1=10; S_2=20; do { integral_1=((b-a)/2)*calculaIntegral(a,b,S_1,t); integral_2=((b-a)/2)*calculaIntegral(a,b,S_2,t); S_1=2*S_1; S_2=2*S_2; } while((fabs(integral_2 - integral_1)/integral_1) >= t); printf("\nA tolerância foi atingida, e o valor da integral é igual a %lf\n", integral_2); return EXIT_SUCCESS; } <file_sep>//<NAME> - 362963 //Código compilado e executado no terminal do Ubuntu #include <stdio.h> #include <stdlib.h> #include <math.h> int menu() { int escolha; printf("\nFórmulas fechadas de Newton-Cotes aplicadas a função F(x) = x^2 - x*log(x)\n"); printf("1 - Polinômio de substituição com grau 1\n"); printf("2 - Polinômio de substituição com grau 2\n"); printf("3 - Polinômio de substituição com grau 3\n"); printf("4 - Polinômio de substituição com grau 4\n"); printf("5 - Polinômio de substituição com grau 5\n"); printf("0 - Sair"); printf("\nEscolha a opção com grau do polinômio de substituição desejado: "); scanf("%d", &escolha); return escolha; } float funcao(float x) { float F; F=pow(x,2) - x*log(x); return F; } float calculaIntegral (int grau, float limiteInf, float limiteSup, float tamanhoIntervalo, int particao) { float Fx0, Fx1, Fx2, Fx3, Fx4, Fx5; float integral=0; float subIntervalo; int contador; for (contador=1; contador<=particao; contador++) { switch(grau) { case 1: subIntervalo=tamanhoIntervalo/particao; Fx0=funcao(limiteInf); Fx1=funcao(limiteInf + subIntervalo); limiteInf=limiteInf + subIntervalo; integral=((subIntervalo/2) * (Fx0 + Fx1))+integral; break; case 2: subIntervalo=(tamanhoIntervalo/2)/particao; Fx0=funcao(limiteInf); Fx1=funcao(limiteInf + subIntervalo); Fx2=funcao(limiteInf + 2*subIntervalo); limiteInf=limiteInf + 2*subIntervalo; integral=((subIntervalo/3) * (Fx0 + 4*Fx1 + Fx2))+integral; break; case 3: subIntervalo=(tamanhoIntervalo/3)/particao; Fx0=funcao(limiteInf); Fx1=funcao(limiteInf + subIntervalo); Fx2=funcao(limiteInf + 2*subIntervalo); Fx3=funcao(limiteInf + 3*subIntervalo); limiteInf=limiteInf + 3*subIntervalo; integral=((3*subIntervalo/8) * (Fx0 + 3*Fx1 + 3*Fx2 + Fx3))+integral; break; case 4: subIntervalo=(tamanhoIntervalo/4)/particao; Fx0=funcao(limiteInf); Fx1=funcao(limiteInf + subIntervalo); Fx2=funcao(limiteInf + 2*subIntervalo); Fx3=funcao(limiteInf + 3*subIntervalo); Fx4=funcao(limiteInf + 4*subIntervalo); limiteInf=limiteInf + 4*subIntervalo; integral=((2*subIntervalo/45) * (7*Fx0 + 32*Fx1 + 12*Fx2 + 32*Fx3 + 17*Fx4))+integral; break; case 5: subIntervalo=(tamanhoIntervalo/5)/particao; Fx0=funcao(limiteInf); Fx1=funcao(limiteInf + subIntervalo); Fx2=funcao(limiteInf + 2*subIntervalo); Fx3=funcao(limiteInf + 3*subIntervalo); Fx4=funcao(limiteInf + 4*subIntervalo); Fx5=funcao(limiteInf + 5*subIntervalo); limiteInf=limiteInf + 5*subIntervalo; integral=((5*subIntervalo/288) * (19*Fx0 + 75*Fx1 + 60*Fx2 + 60*Fx3 + 75*Fx4 + 19*Fx5))+integral; break; } } return integral; } int main(int argc, char const *argv[]) { float a, b, t, delta; float integral_1, integral_2; int particao_1, particao_2; int opcao; int passo; opcao=menu(); while(opcao != 0) { passo=0; system("clear"); printf("\nEntre com o valor do limite inferior: "); scanf("%f", &a); printf("\nEntre com o valor do limite superior: "); scanf("%f", &b); printf("\nEntre com o valor da tolerância: "); scanf("%f", &t); printf("\ncalculando...\n"); delta=b-a; particao_1=1; particao_2=5; do { integral_1=calculaIntegral(opcao,a,b,delta,particao_1); integral_2=calculaIntegral(opcao,a,b,delta,particao_2); particao_1=particao_2; particao_2=particao_2 + 5; passo++; } while(((fabs(integral_2 - integral_1)) / integral_1) >= t); printf("\nApós %d passo(s), a tolerância foi atingida, e o valor da integral é igual a %.10f\n", passo, integral_2); opcao=menu(); } system("clear"); return EXIT_SUCCESS; }<file_sep>//<NAME> - 362963 //Código compilado e executado no terminal do Ubuntu #include <stdio.h> #include <stdlib.h> #include <math.h> int menu() { int escolha; printf("\nQuadraturas de Gauss-Chebyshev aplicadas a integral na forma I[-1,1] = (1/(sqrt(1 - x^2))) * F(x),\n"); printf("onde F(x) = x^3 - (x^2) - 1."); printf("\nDigite o número de ponto(s) de Chebyshev desejado ou 0 (zero) se deseja sair: "); scanf("%d", &escolha); return escolha; } double funcao(double x) { double F; F=pow(x,3) - pow(x,2) - 1; return F; } double calculaIntegral (int nPontos) { int contador; double Xk; double integral, somatorio=0; for (contador=1;contador<=nPontos;contador++) { Xk=cos(((contador-0.5)/nPontos)*M_PI); somatorio=somatorio+funcao(Xk); } integral=(M_PI/nPontos)*somatorio; return integral; } int main(int argc, char const *argv[]) { double integral; int n; n=menu(); while(n != 0) { system("clear"); integral=calculaIntegral(n); printf("\ncalculando...\n"); printf("\nO valor da integral é igual a %lf\n", integral); n=menu(); } system("clear"); return EXIT_SUCCESS; }<file_sep># Laboratórios - CK0048 - Métodos Numéricos II * Unidades I e II - métodos de Diferenciação e Integração * Unidade III - métodos de Autovalores e Autovetores * Unidades IV e V - métodos de Valores Iniciais e Valores de Contorno <file_sep>//<NAME> - 362963 //Código compilado e executado no terminal do Ubuntu #include <stdio.h> #include <stdlib.h> #include <math.h> int menu() { int escolha; printf("\nQuadraturas de Gauss-Hermite aplicadas a integral na forma I[0,infinito] = e^(-x) * F(x),\n"); printf("onde F(x) = x^3 - (x^2) - 1.\n"); printf("1 - Polinômio de Laguerre com 1 ponto(s)\n"); printf("2 - Polinômio de Laguerre com 2 ponto(s)\n"); printf("3 - Polinômio de Laguerre com 3 ponto(s)\n"); printf("4 - Polinômio de Laguerre com 4 ponto(s)\n"); printf("5 - Polinômio de Laguerre com 5 ponto(s)\n"); printf("5 - Polinômio de Laguerre com 6 ponto(s)\n"); printf("0 - Sair"); printf("\nEscolha a opção com o número de pontos de Laguerre desejado: "); scanf("%d", &escolha); return escolha; } double funcao(double x) { double F; F=pow(x,3) - pow(x,2) - 1; return F; } double calculaIntegral (int op) { double p1,p2,p3,p4,p5,p6; double integral; switch(op) { case 1: p1=funcao(1); integral=p1; break; case 2: p1=funcao(0.5857)*0.8535; p2=funcao(3.4142)*0.1464; integral=p1+p2; break; case 3: p1=funcao(0.4157)*0.7110; p2=funcao(2.2442)*0.2785; p3=funcao(6.2899)*0.0103; integral=p1+p2+p3; break; case 4: p1=funcao(0.3225)*0.6031; p2=funcao(1.7457)*0.3574; p3=funcao(4.5366)*0.0388; p4=funcao(9.3950)*0.0005; integral=p1+p2+p3+p4; break; case 5: p1=funcao(0.2635)*0.5217; p2=funcao(1.4134)*0.3986; p3=funcao(3.5964)*0.0759; p4=funcao(7.0858)*0.0036; p5=funcao(12.6408)*0.00002; integral=p1+p2+p3+p4+p5; break; case 6: p1=funcao(0.2228)*0.4589; p2=funcao(1.1889)*0.4170; p3=funcao(2.9927)*0.1133; p4=funcao(5.7751)*0.0103; p5=funcao(9.9374)*0.0002; p6=funcao(15.9828)*0.00000008; integral=p1+p2+p3+p4+p5+p6; break; } return integral; } int main(int argc, char const *argv[]) { double integral; int opcao; opcao=menu(); while(opcao != 0) { system("clear"); integral=calculaIntegral(opcao); printf("\ncalculando...\n"); printf("\nO valor da integral é igual a %lf\n", integral); opcao=menu(); } system("clear"); return EXIT_SUCCESS; }<file_sep> public class Operacoes { public static double normalizar(double[] vetor) { double vetor_normalizado, somatorio=0; int tamanho = vetor.length; for(int i=0; i<tamanho; i++) { somatorio = somatorio + (vetor[i]*vetor[i]); } vetor_normalizado = Math.sqrt(somatorio); return vetor_normalizado; } public static double[] divisaoVetorEscalar(double[] vetor, double escalar) { int tamanho = vetor.length; double[] resultado = new double[tamanho]; for(int i=0; i<tamanho; i++) { resultado[i] = vetor[i]/escalar; } return resultado; } public static double[] multiplicacaoMatrizVetor(double[][] matriz, double[] vetor) { double parcial; int tamanho = matriz.length; double[] resultado = new double[tamanho]; for(int i=0; i<tamanho; i++) { parcial=0; for(int j=0; j<tamanho; j++) { parcial = parcial + matriz[i][j]*vetor[j]; } resultado[i] = parcial; } return resultado; } public static double multiplicacaoVetorVetor(double[] vetor_1, double[] vetor_2) { double resultado=0; int tamanho = vetor_1.length; for(int i=0; i<tamanho; i++) { resultado = resultado + (vetor_1[i]*vetor_2[i]); } return resultado; } }
a4c6ed38b05fb06ecf9ca012010830a2627c46ee
[ "Java", "C", "Markdown" ]
12
C
mjnlima/metodos-numericos-II
070f9c50be5106663ed73a90341998813fef1306
104a19cc424315c8e24bad5412f1519a992c1a97
refs/heads/master
<file_sep>#include "FastestWay.h" #include <stdlib.h> #include <time.h> int main() { srand(time(NULL)); int e1=2,e2=1,x1=8,x2=9; //int rand(void); int a1[8]; int a2[8]; int t1[7]; int t2[7]; for(int i = 0; i<8;i++){ /*for (int k = 0; k < 7; k++) { cout << a1[k]; } for (int v = 0; v < 7; v++) { cout << a2[v]; }*/ a1[i]= rand()%10; cout << "Time at each station of Line 1=" << a1[i] <<endl; a2[i]= rand()%10; cout << "Time at each Station of Line 2=" <<a2[i]<<endl; //int k; //int v; } for(int j = 0; j<6;j++){ t1[j]= rand()%10; cout << "Transfer Time from each Station of Line 1="<< t1[j]<<endl; t2[j]= rand()%10; cout << "Transfer Time from each Station of Line 2=" << t2[j]<<endl; } //int a1[8]={1,2,3,4,5,6,7,1}; //int a2[8]={7,6,5,4,3,2,1,1}; //int t1[7]={9,8,7,6,5,4,1}; //int t2[7]={8,6,4,2,1,3,1}; int f1[100],f2[100],L1[100],L2[100],L; FastestWayAlgo(e1,e2,a1,a2,x1,x2,f1,f2,L1,L2,L,t1,t2,7); int x = fasttime(L1,L2,L,6,f1); cout << "Test Value " << x << endl; //int expected = 28; //if(x == expected) { //cout << "Test Passed: " << x << "/" << expected << endl; //} else { //cout << "Test Failed: " << x << "/" << expected << endl; //} //return 0; } <file_sep> #include<iostream> using namespace std; void FastestWayAlgo(int e1,int e2,int *a1,int *a2,int x1,int x2,int *f1,int *f2,int *L1,int *L2,int &L,int *t1,int *t2,int n) { f1[1]=e1+a1[1]; //Entrance time and time at first station in line 1 f2[1]=e2+a2[1]; //Entrance time and time at first station in line 2 int i; for(i=2;i<n;i++) //loop from station 2 to last station of Line 1 { if(f1[i-1]+a1[i]<f2[i-1]+a1[i]+t2[i-1]) { f1[i]=f1[i-1]+a1[i]; L1[i]=1; } else { f1[i]=f2[i-1]+a1[i]+t2[i-1]; L1[i]=2; } if(f2[i-1]+a2[i]<f1[i-1]+a2[i]+t1[i-1]) //loop from station 2 to last station of Line 2 { f2[i]=f2[i-1]+a2[i]; L2[i]=2; } else { f2[i]=f1[i-1]+a2[i]+t1[i-1]; L2[i]=1; } } if(f1[n-1]+x1<f2[n-1]+x2) { f1[n]=f1[n-1]+x1; L=1; } else { f1[n]=f2[n-1]+x2; L=2; } } // int fasttime(int *L1,int *L2,int L,int n,int *f1) { int i=L; cout<<"Station Number = "<<n<<" is on line = "<<i<<endl; int j; for(j=n;j>=2;j--) { if(i==1) { i=L1[j]; } else { i=L2[j]; } cout<<"Station Number = "<<j-1<<" is on line = "<<i<<endl; //<<"Fastest Time = "<<f1[length+1]<<endl; } cout<<"Fastest Time = "<<f1[n+1]<<endl; return f1[n+1]; }
e0014d3ceb4b2960cc8aa8f8aebacf67a26f968d
[ "C++" ]
2
C++
nawalathar/Malghani_Assignment1
2afcfb72c782f86f72c6ac21db770f250fd9fd55
51cfa204f4ba2ec5c114ca2126d593d9234b9914
refs/heads/master
<file_sep>package demo; import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import demo.Calculator; /** * 固件测试 * @version */ public class FixtureTestCase { private static Calculator cal = new Calculator(); /** * 测试用例初始化时,执行方法 */ @BeforeClass public static void setUpClass() { System.out.println("执行setUpClass方法!"); } /** * 所有测试方法执行完毕后,执行方法 */ @AfterClass public static void tearDownClass() { System.out.println("执行tearDownClass方法!"); } /** * 每个方法执行前 */ @Before public void setUp() { System.out.println("执行setUp方法!"); cal.clear(); } /** * 每个方法执行后 */ @After public void tearDown() { System.out.println("执行tearDown方法!"); //cal.clear(); } /** * 测试加法运算的方法 */ @Test public void testAdd() { cal.add(2); cal.add(5); //第一个参数预期值,第二个参数实际值,两值比较相等测试就通过 assertEquals(7, cal.getResult()); } /** * 测试减法运算的方法 */ @Test public void testSubstract() { //cal.clear(); cal.add(10); cal.substract(2); assertEquals(8, cal.getResult()); } } <file_sep>package demo; import org.junit.Test; import demo.Calculator; /** * Òì³£²âÊÔ * @version */ public class ExceptionTestCase { private static Calculator cal = new Calculator(); @Test(expected=ArithmeticException.class) public void testDivideByZore() { cal.divide(0); } }
d76186792a16c969a704aae30e03a9463e140d98
[ "Java" ]
2
Java
heng369/repo3
e2175cb4379c7c6808f6956ceb1aafad245f54c0
42c61bbb29b69c8b1d0bb3b957c45920d384f838
refs/heads/master
<file_sep>// // ViewController.swift // calayer // import UIKit class ViewController: UIViewController { lazy var gradientLayer: CAGradientLayer = { return CAGradientLayer() }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() gradientLayer.frame = view.bounds } func setupGradientLayer() { view.layer.addSublayer(gradientLayer) gradientLayer.colors = [UIColor.red.cgColor, UIColor.green.cgColor] gradientLayer.startPoint = CGPoint(x: 0, y: 0) gradientLayer.endPoint = CGPoint(x: 1, y: 1) view.layer.addSublayer(gradientLayer) } }
13d791203706e44ab57fef9f28b3f19fb8eb0ad2
[ "Swift" ]
1
Swift
iosjunkie/GradientLayer-Starter-Swift-5
9cd8ba90a4ade7c9ebe5c2b7b3a57be9f29c3054
6eada235ad1809409e5be081bbc154e732f9334b
refs/heads/master
<file_sep>from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): if not email: raise ValueError user = self.model(email= self.normalize_email(email), **kwargs) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, email, password): if not email: raise ValueError suser = self.create_user(email=email,password= password) suser.is_superuser = True suser.is_staff = True suser.set_password(password) suser.save() return suser class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True,) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default= False) objects = UserManager() USERNAME_FIELD = 'email' #email # Create your models here. <file_sep>from django.contrib.auth import get_user_model from django.test import TestCase class user_Create_check(TestCase): def test_user_create(self): email = "<EMAIL>" password = "<PASSWORD>" user = get_user_model().objects.create_user(email =email, password= password) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) def test_user_email(self): email = "<EMAIL>" password = "<PASSWORD>" user = get_user_model().objects.create_user(email = email, password = password) self.assertEqual(user.email, email.lower()) def test_mail_invalid(self): with self.assertRaises(ValueError): # if we execute the below create function, the model fucntion should raise value error. #if it doesnot raise, then it is a failure user = get_user_model().objects.create_user(email=None, password = "<PASSWORD>") def test_superuser_creation(self): email = "<EMAIL>" password = "<PASSWORD>" user = get_user_model().objects.create_superuser(email=email, password= <PASSWORD>) self.assertTrue(user.is_superuser) <file_sep>appdirs==1.4.3 Django==2.1.5 djangorestframework==3.9.1 pyparsing==2.3.1 pytz==2018.9 six==1.12.0 flake8>=3.6.0,<=3.7.0<file_sep>FROM python:3.7-alpine MAINTAINER Mohan ENV PYTHONUNBUFFERRED 1 COPY ./requirements.txt /requirements.txt #copy the requirements.txt file in the ubuntu system(local) to the requirements.txt inside the docker image RUN pip install -r /requirements.txt RUN mkdir /app #create a directory called /app inside the docker image WORKDIR /app #make the dir /app as the working directory inside the docker image COPY ./app/ /app #copy the content from /app dir in the local machine to the /app folder of the docker image RUN adduser -D user #creates an user called "user" and provides permission for the user to run only the application (-D) USER user #makes the current user as the user
4264df63aa3a22bc3d9c17ff4ca68c6eb02a68a2
[ "Python", "Text", "Dockerfile" ]
4
Python
Mohan-RajSP/recipee_api
f314961e583ba7c11ab13421cd525a8213f406b3
4c26e7ce50833bca08b56af7ddfba1ae251c4527
refs/heads/master
<file_sep>platform :ios, '5.0' pod 'AFNetworking', '~> 1.2' pod 'HawkClient', '~> 1.3.0' pod 'FXReachability', '~> 1.1' pod 'KNSemiModalViewController', '~> 0.3' pod 'DLStarRating', '~> 1.1' pod 'KIImagePager', '~> 0.0.2' pod 'YIPopupTextView', '~> 1.0.0' pod 'TDBadgedCell', '~> 2.3.1' xcodeproj 'STracker/STracker.xcodeproj'<file_sep>STracker iOS =========== This repository contains all code for STracker iOS Application. STracker for iOS is an application that allow his users to see all the information about television series. For more information about STracker please check our website:[STracker](http://stracker.apphb.com).
800822060e6862b74ef39102b9f10524231ce4b3
[ "Markdown", "Ruby" ]
2
Ruby
RyanTech/STrackerIOS
30e387ea87119b9088e7b59cceb16a5ad05b35f9
894f9038db6cf1e42bf7b2d3aa498c695bab1a3e
refs/heads/master
<file_sep>test("Foo.age", function () { var foo = new Foo(20); equal(foo.age, 20); }); test("Foo.fuga", function () { var foo = new Foo(20); equal(foo.fuga(), 23); }); <file_sep>module("sinon.spy jQuery.ajax", { setup: function () { }, teardown: function () { jQuery.ajax.restore(); } }); test("jQuery.getJSON", function () { var spy = sinon.spy(jQuery, "ajax"); jQuery.getJSON("/some/resource"); ok(spy.calledOnce, "method is called once"); equal(spy.getCall(0).args[0].url, "/some/resource", "url parameter"); equal(spy.getCall(0).args[0].dataType, "json", "dataType parameter"); }); module("sinon.mock"); test('mock.expects, mock.twice', function() { var Hoge = function(){}; Hoge.prototype.foo = function(name){ return name; }; var hoge = new Hoge(); var mock = sinon.mock(hoge); mock.expects("foo").withArgs("test") hoge.foo("test"); ok(mock.verify(), "method foo called."); }); test("sinon.stub, sinon.returns", function(){ var Hoge = function(){}; Hoge.prototype.ok = function() { return true; }; var hoge = new Hoge(); equal(hoge.ok(), true); var stub = sinon.stub(hoge, "ok"); stub.returns(false); equal(hoge.ok(), false, "return false"); stub.restore(); });<file_sep>var Foo = function (age) { this.age = age; }; Foo.prototype.fuga = function () { var piyo = 1; return piyo + 2 + this.age; }; <file_sep># grunt examples - nodejs v0.9.10 - [grunt](http://gruntjs.com/) v0.4.0 ## Resources ### Compass * compass `gem install compass` * require - [sassy-buttons](http://jaredhardy.com/sassy-buttons/) `gem install sassy-buttons` ### CoffeeScript Install this with `-g` * [http://coffeescript.org/](http://coffeescript.org/) `npm install -g coffee-script` ### phantomjs `brew install phantomjs` ### Grunt Install this with `-g` ``` npm uninstall -g grunt npm install -g grunt-cli ``` ### Setup ``` npm install ``` ### task `grunt watch:autotest` <file_sep>test("Animal#name", function () { var animal = new Animal('a'); ok(animal.name == "a"); }); ; //test("application#", function () { //}); ; test("Foo.age", function () { var foo = new Foo(20); equal(foo.age, 20); }); test("Foo.fuga", function () { var foo = new Foo(20); equal(foo.fuga(), 23); }); ; module("sinon.spy jQuery.ajax", { setup: function () { }, teardown: function () { jQuery.ajax.restore(); } }); test("jQuery.getJSON", function () { var spy = sinon.spy(jQuery, "ajax"); jQuery.getJSON("/some/resource"); ok(spy.calledOnce, "method is called once"); equal(spy.getCall(0).args[0].url, "/some/resource", "url parameter"); equal(spy.getCall(0).args[0].dataType, "json", "dataType parameter"); }); module("sinon.mock"); test('mock.expects, mock.twice', function() { var Hoge = function(){}; Hoge.prototype.foo = function(name){ return name; }; var hoge = new Hoge(); var mock = sinon.mock(hoge); mock.expects("foo").withArgs("test") hoge.foo("test"); ok(mock.verify(), "method foo called."); }); test("sinon.stub, sinon.returns", function(){ var Hoge = function(){}; Hoge.prototype.ok = function() { return true; }; var hoge = new Hoge(); equal(hoge.ok(), true); var stub = sinon.stub(hoge, "ok"); stub.returns(false); equal(hoge.ok(), false, "return false"); stub.restore(); });; test("User#say", function () { var user = new User('a'); var mock = sinon.mock(user); mock.expects("say").withArgs("test") user.say("test"); ok(mock.verify(), "method say called."); }); <file_sep>test("User#say", function () { var user = new User('a'); var mock = sinon.mock(user); mock.expects("say").withArgs("test") user.say("test"); ok(mock.verify(), "method say called."); }); <file_sep>//test("application#", function () { //});
b6a8200fe596b93dd99200577c6ed4cbc5c858ef
[ "JavaScript", "Markdown" ]
7
JavaScript
bluerabbit/grunt-sample
e487deb772b1511e8efffd248cd28dc552c88bb6
9fa314d2a1f63b6349558251c48ff1bac9b8215b
refs/heads/master
<repo_name>pdffiller/pdffiller-php-api-client<file_sep>/src/Core/Model.php <?php namespace PDFfiller\OAuth2\Client\Provider\Core; use Inflect\Inflect; use PDFfiller\OAuth2\Client\Provider\Traits\CastsTrait; use PDFfiller\OAuth2\Client\Provider\Contracts\Arrayable; use PDFfiller\OAuth2\Client\Provider\Contracts\Stringable; use PDFfiller\OAuth2\Client\Provider\Exceptions\IdMissingException; use PDFfiller\OAuth2\Client\Provider\Exceptions\InvalidQueryException; use PDFfiller\OAuth2\Client\Provider\Exceptions\InvalidRequestException; use PDFfiller\OAuth2\Client\Provider\Exceptions\ResponseException; use PDFfiller\OAuth2\Client\Provider\PDFfiller; use ReflectionClass; /** * Class Model * @package PDFfiller\OAuth2\Client\Provider * * @property string $id */ abstract class Model implements Arrayable { use CastsTrait; /** @var string */ protected $primaryKey = 'id'; /** @var array */ protected $mapper = []; /** @var string */ protected static $entityUri = null; /** @var PDFfiller */ protected $client = null; /** @var array cached attributes */ private $oldValues = []; /** @var array */ protected $properties = []; /** @var array */ protected $readOnly = []; /** @var bool */ public $exists = false; /** * Model constructor. * @param PDFfiller $provider * @param array $array * @throws \ReflectionException */ public function __construct(PDFfiller $provider, array $array = []) { if (isset($array['exists'])) { $this->exists = $array['exists']; unset($array['exists']); } $except = isset($array['except']) && is_array($array['except']) ? $array['except'] : []; $this->initArrayFields($except); $this->client = $provider; $this->parseArray($array); } /** * Initializes the object's arrays and lists * @param array $except * @throws \ReflectionException */ protected function initArrayFields(array $except = []) { $reflection = new ReflectionClass(static::class); $docs = ($reflection->getDocComment()); $docs = preg_replace("~[*/]+~", ' ', $docs); preg_match_all("~@property\s+(array|mixed|ListObject|FillableFieldsList)\s+\\$(.*)\r?\n+~", $docs, $result); if ($result) { $fields = array_diff($result[2], $except); foreach ($fields as $field) { $this->properties[$field] = new ListObject(); } } } /** * Returns an URL of current endpoint * * @return string */ protected static function getUri() { return static::getEntityUri() . '/'; } /** * Creates or updates model * @param array $options * @return mixed * @throws InvalidRequestException * @throws ResponseException */ public function save($options = []) { if (!isset($options['except'])) { $options['except'] = []; } $options['except'] = array_merge($options['except'], $this->readOnly); if (!$this->exists) { return $this->create($options); } return $this->update($options); } /** * @inheritdoc */ public function toArray($options = []): array { foreach ($this->properties as $key => $value) { if ($value instanceof Arrayable) { $properties[$key] = $value->toArray(); } elseif ($value instanceof Stringable) { $properties[$key] = $value->__toString(); } else { $properties[$key] = $value; } } return $properties ?? []; } /** * Extracts properties from array * * @param $array * @param array $options * @return $this */ public function parseArray($array, $options = []) { // default options $options['except'] = $options['except'] ?? []; foreach ($options['except'] as $value) { unset($array[$value]); } foreach ($array as $key => $value) { $this->properties[$key] = $this->castField($key, $value); } return $this; } /** * Caches passed fields as old fields * @param $properties */ protected function cacheFields($properties) { $this->oldValues = $properties; } /** * Sends request by given type, uri and options * @param PDFfiller $provider * @param $method * @param $uri * @param array $params * @return mixed * @throws InvalidRequestException */ protected static function apiCall($provider, $method, $uri, $params = []) { $methodName = $method . 'ApiCall'; if (method_exists($provider, $methodName)) { return $provider->{$methodName}($uri, $params); } throw new InvalidRequestException(); } /** * Builds the full url * * @param array $entities * @param array $params * @return string * @throws InvalidQueryException */ protected static function resolveFullUrl($entities = [], $params = []) { $uri = static::getUri(); if (!empty($entities)) { if (is_array($entities)) { $entities = implode('/', $entities) . '/'; } if (!is_scalar($entities)) { throw new InvalidQueryException(); } $uri .= $entities; } if (!empty($params)) { $uri .= '?' . http_build_query($params); } return $uri; } /** * Returns entity properties as a result of get request. * @param $provider * @param array $entities * @param array $params * @return mixed * @throws InvalidQueryException * @throws InvalidRequestException */ public static function query($provider, $entities = [], $params = []) { $url = self::resolveFullUrl($entities, $params); return static::apiCall($provider, 'query', $url); } /** * Returns a result of post request * @param $provider * @param $uri * @param array $params * @return mixed * @throws InvalidRequestException */ public static function post($provider, $uri, $params = []) { return static::apiCall($provider, 'post', $uri, $params); } /** * Returns a result of put request * @param $provider * @param $uri * @param array $params * @return mixed * @throws InvalidRequestException */ public static function put($provider, $uri, $params = []) { return static::apiCall($provider, 'put', $uri, $params); } /** * Returns a result of delete request * @param $provider * @param $uri * @return mixed * @throws InvalidRequestException */ public static function delete($provider, $uri) { return static::apiCall($provider, 'delete', $uri); } /** * Creates model * @param array $options * @return mixed * @throws InvalidRequestException * @throws ResponseException */ protected function create($options = []) { $params = $this->prepareFields($options); $uri = static::getUri(); $createResult = static::post($this->client, $uri, [ 'json' => $params, ]); if (isset($createResult['errors'])) { throw new ResponseException($createResult['errors']); } $this->cacheFields($params); $this->exists = true; $object = $createResult; if (isset($createResult['items'])) { $object = $createResult['items'][0]; } $this->parseArray($object); return $createResult; } /** * Updates instance/ Only changed fields will be updated * @param array $options * @return mixed * @throws InvalidRequestException */ protected function update($options = []) { $params = $this->prepareFields($options); $diff = $this->findDiff($params); $uri = static::getUri() . $this->{$this->primaryKey}; $updateResult = static::put($this->client, $uri, [ 'json' => $diff, ]); if (!isset($updateResult['errors'])) { $this->cacheFields($params); foreach($updateResult as $name => $property) { $this->__set($name, $property); } } return $updateResult; } /** * Removes current instance entity if it has an id property * @return mixed * @throws IdMissingException * @throws InvalidRequestException */ public function remove() { if (isset($this->properties[$this->primaryKey])) { $this->exists = false; return static::deleteOne($this->client, $this->{$this->primaryKey}); } throw new IdMissingException(); } /** * Removes entity by id * @param $provider * @param $id * @return mixed * @throws InvalidRequestException */ public static function deleteOne($provider, $id) { $uri = static::getUri() . $id; return static::delete($provider, $uri); } /** * Returns model instance * @param PDFfiller $provider * @param $id * @return static * @throws InvalidQueryException * @throws InvalidRequestException * @throws \ReflectionException */ public static function one(PDFfiller $provider, $id) { $params = static::query($provider, $id); $instance = new static($provider, array_merge($params, ['exists' => true])); $instance->cacheFields($params); return $instance; } /** * Returns a list of entities * @param PDFfiller $provider * @param array $queryParams * @return ModelsList * @throws InvalidQueryException * @throws InvalidRequestException * @throws \ReflectionException */ public static function all(PDFfiller $provider, array $queryParams = []) { $paramsArray = static::query($provider, null, $queryParams); $paramsArray['items'] = static::formItems($provider, $paramsArray); return new ModelsList($paramsArray); } /** * Unwrap the instances from response * @param $provider * @param $array * @return array * @throws \ReflectionException */ protected static function formItems($provider, $array) { $set = []; foreach ($array['items'] as $params) { $instance = new static($provider, array_merge($params, ['exists' => true])); $instance->cacheFields($params); if (isset($instance->id)) { $set[$instance->id] = $instance; } else { $set[] = $instance; } } return $set; } /** * @return PDFfiller */ public function getClient() { return $this->client; } /** * @param PDFfiller $client */ public function setClient(PDFfiller $client) { $this->client = $client; } /** * @return null */ public static function getEntityUri() { if (isset(static::$entityUri)) { return static::$entityUri; } $parts = explode('\\', static::class); return strtolower( preg_replace('/([^A-Z])([A-Z])/', "$1_$2", Inflect::pluralize(end($parts)) ) ); } /** * @param null $entityUri */ public static function setEntityUri($entityUri) { static::$entityUri = $entityUri; } /** * Find changed properties * * @param array $new new values * @return array all new or changed values */ private function findDiff($new) { $old = $this->oldValues; $diff = []; foreach ($new as $key => $value) { if (!isset($old[$key]) || $old[$key] !== $new[$key]) { $diff[$key] = $value; } } return $diff; } /** * Magic method, gets the object fields. * * @param $name * @return mixed|null */ public function __get($name) { if (method_exists($this, $method = 'get' . $this->snakeToCamelCase($name). 'Field')) { return $this->{$method}(); } if (isset($this->properties[$name])) { return $this->properties[$name]; } return null; } /** * Magic method, sets the object fields. * * @param $name * @param $value */ public function __set($name, $value) { if (method_exists($this, $method = 'set' . $this->snakeToCamelCase($name). 'Field')) { $this->{$method}($value); } else { $this->properties[$name] = $this->castField($name, $value); } } /** * Converts snake_cased string to camelCase * @param string $string * @param bool $smallFirst * @return string */ protected function snakeToCamelCase($string, $smallFirst = false) { $parts = explode('_', $string); array_walk($parts, function(&$element) { $element = ucfirst($element); }); $result = implode('', $parts); return $smallFirst ? lcfirst($result) : $result; } /** * Prepares fields with incorrect property name format * * @param array $options * @return array */ protected function prepareFields($options = []) { $params = $this->toArray($options); if (empty($this->mapper)) { return $params; } foreach ($this->mapper as $modelKey => $apiKey) { if(array_key_exists($modelKey,$params)) { $params[$apiKey] = $params[$modelKey]; unset($params[$modelKey]); } } return $params; } } <file_sep>/examples/templates/5_delete_template.php <?php use PDFfiller\OAuth2\Client\Provider\Template; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $template = Template::one($provider, 216865300); $e = $template->remove(); dd($e); <file_sep>/examples/custom_logo/2_create_logo_via_url.php <?php use PDFfiller\OAuth2\Client\Provider\CustomLogo; use PDFfiller\OAuth2\Client\Provider\Uploader; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $uploader = new Uploader($provider, CustomLogo::class); $uploader->type = Uploader::TYPE_URL; $uploader->file = 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/4d/2012_Transit_of_Venus_from_SF.jpg/1280px-2012_Transit_of_Venus_from_SF.jpg'; $logo = $uploader->upload(); dd($logo); <file_sep>/src/Folder.php <?php namespace PDFfiller\OAuth2\Client\Provider; use PDFfiller\OAuth2\Client\Provider\Core\Model; /** * Class Folder * @package PDFfiller\OAuth2\Client\Provider * @property string $name * @property string $documents_count * @property string $folders_count * @property string $parent_id * @property string $created * @property string $folder_id */ class Folder extends Model { protected $primaryKey = 'folder_id'; } <file_sep>/src/SignatureRequest.php <?php namespace PDFfiller\OAuth2\Client\Provider; use PDFfiller\OAuth2\Client\Provider\Core\ListObject; use PDFfiller\OAuth2\Client\Provider\Core\Model; use PDFfiller\OAuth2\Client\Provider\Core\ModelsList; use PDFfiller\OAuth2\Client\Provider\Enums\SignatureRequestMethod; use PDFfiller\OAuth2\Client\Provider\Enums\SignatureRequestSecurityPin; use PDFfiller\OAuth2\Client\Provider\Enums\SignatureRequestStatus; /** * Class SignatureRequest * @package PDFfiller\OAuth2\Client\Provider * * @property string $document_id * @property SignatureRequestMethod $method * @property SignatureRequestStatus $status * @property string $envelope_name * @property SignatureRequestSecurityPin $security_pin * @property string $sign_in_order * @property string $pin * @property ListObject $recipients * @property ListObject $callbacks * @property string $owner * @property int $signature_request_id */ class SignatureRequest extends Model { const CERTIFICATE = 'certificate'; const SIGNED_DOCUMENT = 'signed_document'; const INBOX = 'inbox'; const DOWNLOAD = 'download'; protected $primaryKey = 'signature_request_id'; /** @var array */ protected $casts = [ 'method' => SignatureRequestMethod::class, 'status' => SignatureRequestStatus::class, 'security_pin' => SignatureRequestSecurityPin::class, 'callbacks' => ['list_of', Callback::class], 'recipients' => ['list_of', SignatureRequestRecipient::class], ]; /** @var array */ protected $readOnly = [ 'status', 'date_signed', 'date_created', 'callbacks' ]; /** * SignatureRequest constructor. * @param PDFfiller $provider * @param array $array */ public function __construct($provider, $array = []) { $recipients = isset($array['recipients']) ? $array['recipients'] : []; unset($array['recipients']); parent::__construct($provider, $array); $recipients = self::formRecipients($recipients, $this->client, $this->signature_request_id); $this->recipients = new ListObject($recipients); } /** * Return signatures request list in inbox * * @param PDFfiller $provider * @param array $parameters * @return ModelsList */ public static function getInbox(PDFfiller $provider, $parameters = []) { $paramsArray = self::query($provider, [self::INBOX], $parameters); $paramsArray['items'] = array_map(function ($entry) { $entry['recipients'] = [$entry['recipients']]; $entry['except'] = ['callbacks']; return $entry; }, $paramsArray['items']); $paramsArray['items'] = static::formItems($provider, $paramsArray); return new ModelsList($paramsArray); } /** * Returns zip-archive of SendToSign inbox documents. * Supports a filter parameters such as 'status', 'perpage', 'datefrom', * 'dateto', 'order', 'orderby'. Status can be only 'signed', 'in_progress' and 'sent' * * @param $provider * @param array $params * @return string */ public static function inboxDownload($provider, $params = []) { if (isset($params['status']) && $params['status'] instanceof SignatureRequestStatus) { $params['status'] = mb_strtolower($params['status']->getValue()); } return self::query($provider, [self::INBOX, self::DOWNLOAD], $params); } public function getInboxContent(array $params = []) { return self::inboxDownload($this->getClient(), $params); } /** * Prepares recipients array * * @param $inputRecipients * @param PDFfiller $provider * @param $signatureRequestId * @return array */ protected static function formRecipients($inputRecipients, PDFfiller $provider, $signatureRequestId) { $recipients = []; foreach ($inputRecipients as $recipient) { $recipients[$recipient['id']] = new SignatureRequestRecipient($provider, $recipient, $signatureRequestId); } return $recipients; } /** * Returns certificate if document has been signed. * @return mixed */ public function certificate() { return self::query($this->client, [$this->id, self::CERTIFICATE]); } /** * Returns a signed document. * @return mixed */ public function signedDocument() { return self::query($this->client, [$this->signature_request_id, self::SIGNED_DOCUMENT]); } /** * Add recipient * * @param SignatureRequestRecipient $recipient * @return SignatureRequestRecipient recipient creation result */ public function addRecipient(SignatureRequestRecipient $recipient) { $this->recipients[] = $recipient->create(); return $recipient; } /** * Creates and returns new recipient * * @return SignatureRequestRecipient SignatureRequestRecipient */ public function createRecipient() { return new SignatureRequestRecipient($this->client, [], $this->signature_request_id); } /** * Returns current signature request recipient by id. * @param string|integer $id * @return SignatureRequestRecipient|null */ public function getRecipient($id) { if ($this->recipients[$id]) { return $this->recipients[$id]; } return null; } /** * Returns signature request recipients list. * @return ListObject */ public function getRecipients() { if ($this->recipients) { return $this->recipients; } return null; } /** * Returns signature request recipients list. * * @param PDFfiller $provider * @param integer $signatureRequestId * @return ListObject */ public static function recipients(PDFfiller $provider, $signatureRequestId) { $recipients = self::query($provider, [$signatureRequestId, SignatureRequestRecipient::RECIPIENT]); return new ListObject(self::formRecipients($recipients['items'], $provider, $signatureRequestId)); } /** * Returns current signature request recipient by id. * * @param PDFfiller $provider * @param $signatureRequestId * @param $recipientId * @return SignatureRequestRecipient */ public static function recipient(PDFfiller $provider, $signatureRequestId, $recipientId) { $recipient = self::query($provider, [$signatureRequestId, SignatureRequestRecipient::RECIPIENT, $recipientId]); return new SignatureRequestRecipient($provider, $recipient, $signatureRequestId); } } <file_sep>/examples/signature_request/11_get_signature_request_inbox_list.php <?php use PDFfiller\OAuth2\Client\Provider\SignatureRequest; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $signatureRequestEntity = new \PDFfiller\OAuth2\Client\Provider\SignatureRequest($provider); $e = SignatureRequest::getInbox($provider); dd($e->toArray()); <file_sep>/src/Core/ExceptionsMessages.php <?php namespace PDFfiller\OAuth2\Client\Provider\Core; /** * Class ExceptionsMessages * * @package PDFfiller\OAuth2\Client\Provider\Core */ class ExceptionsMessages { /** @var Exception */ private $exception; public function __construct(Exception $exception) { $this->setException($exception); } /** * @return Exception */ public function getException() { return $this->exception; } /** * @param Exception $exception */ public function setException(Exception $exception) { $this->exception = $exception; } /** * @param string $locale * @return string */ public function getMessage($locale = "en"):string { $className = (new \ReflectionClass($this->exception))->getShortName(); $class = substr($className, 0, strpos($className, 'Exception')); $class = lcfirst($class) ?: "default"; $messages = self::getMessages($locale); return $messages[$class] ?: (ucfirst($class) . "Exception"); } /** * Returns an array of possible exceptions messages * * @param string $locale * @return array */ protected function getMessages(string $locale = "en"):array { $path = __DIR__ . "/../Messages/" . $locale . "/messages.json"; if (file_exists($path)) { $jsonMessages = file_get_contents($path); return json_decode($jsonMessages, true); } return []; } } <file_sep>/src/Exceptions/InvalidBodyException.php <?php namespace PDFfiller\OAuth2\Client\Provider\Exceptions; use PDFfiller\OAuth2\Client\Provider\Core\Exception; /** * Class InvalidBodyException * Handle cases when request part 'body' isn't valid. * @package PDFfiller\OAuth2\Client\Provider\Exceptions */ class InvalidBodyException extends Exception {} <file_sep>/examples/folder/5_update_folder.php <?php use PDFfiller\OAuth2\Client\Provider\Folder; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $folder = Folder::one($provider, 4324); $folder->name = "Update folder name 1"; $e = $folder->save(); dd($e);<file_sep>/examples/user/1_get_me_info.php <?php use PDFfiller\OAuth2\Client\Provider\User; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $e = User::me($provider); dd($e); <file_sep>/src/Exceptions/IdMissingException.php <?php namespace PDFfiller\OAuth2\Client\Provider\Exceptions; use PDFfiller\OAuth2\Client\Provider\Core\Exception; /** * Class IdMissingException * Handle cases when object id is missing. * @package PDFfiller\OAuth2\Client\Provider\Exceptions */ class IdMissingException extends Exception {} <file_sep>/examples/fillable_form/2_create_fillable_forms.php <?php use PDFfiller\OAuth2\Client\Provider\FillableForm; use PDFfiller\OAuth2\Client\Provider\Enums\FillRequestNotifications; use PDFfiller\OAuth2\Client\Provider\DTO\NotificationEmail; use PDFfiller\OAuth2\Client\Provider\DTO\AdditionalDocument; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $fillRequestEntity = new FillableForm($provider); $fillRequestEntity->document_id = 23232323; $fillRequestEntity->access = "full"; $fillRequestEntity->status = "public"; $fillRequestEntity->email_required = true; $fillRequestEntity->name_required = true; $fillRequestEntity->custom_message = "Custom"; $fillRequestEntity->callback_url = "http://testhostexample.com"; $fillRequestEntity->notification_emails[] = new NotificationEmail(['name' => 'name', 'email' => '<EMAIL>']); $fillRequestEntity->additional_documents = ['test', 'test22']; $fillRequestEntity->enforce_required_fields = true; $fillRequestEntity->welcome_screen = false; $fillRequestEntity->notifications = new FillRequestNotifications(FillRequestNotifications::WITH_PDF); $e = $fillRequestEntity->save(); dd($e); <file_sep>/src/Core/AbstractObject.php <?php namespace PDFfiller\OAuth2\Client\Provider\Core; use PDFfiller\OAuth2\Client\Provider\Traits\CastsTrait; use PDFfiller\OAuth2\Client\Provider\Contracts\Arrayable; use PDFfiller\OAuth2\Client\Provider\Contracts\Stringable; /** * Class AbstractObject * * Basic data transfer class * * @package PDFfiller\OAuth2\Client\Provider\Core */ abstract class AbstractObject implements Arrayable { use CastsTrait; /** @var array */ protected $attributes = []; /** * AbstractObject constructor. * @param $properties */ public function __construct($properties) { foreach ($properties as $name => $property) { $this->{$name} = $property; } } /** * @param $name * @param $value */ public function __set($name, $value) { $attributes = $this->attributes; if (in_array($name, $attributes)) { $this->{$name} = $this->castField($name, $value); } } /** * @param $name * @return null */ public function __get($name) { $attributes = $this->attributes; if (in_array($name, $attributes) && isset($this->{$name})) { return $this->{$name}; } return null; } /** * @inheritdoc */ public function toArray(): array { $array = []; $attributes = array_intersect($this->attributes, array_keys(get_object_vars($this))); foreach ($attributes as $attribute) { if (!isset($this->{$attribute})) { continue; } $value = $this->{$attribute}; if ($value instanceof Arrayable) { $value = $value->toArray(); } elseif ($value instanceof Stringable) { $value = $value->__toString(); } $array[$attribute] = $value; } return $array; } } <file_sep>/examples/fillable_form/11_download_fillable_forms_all_filled_form.php <?php use PDFfiller\OAuth2\Client\Provider\FillableForm; use PDFfiller\OAuth2\Client\Provider\Core\Job; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $fillableForm = new FillableForm($provider, ['fillable_form_id' => 43545345]); $fillableFormAsync = new Job($fillableForm); $fillableFormAsync->download(); while (!$fillableFormAsync->isReady()) { sleep(2); } dd($fillableFormAsync); <file_sep>/examples/.env.example CLIENT_ID=xxxclientidxxx CLIENT_SECRET=xxxclientsecretxxx URL_ACCESS_TOKEN=https://api.pdffiller.com/v2/oauth/token URL_API_DOMAIN=https://api.pdffiller.com/v2/ REDIRECT_URI=https://localhost/oauth USER_EMAIL=<EMAIL> PASSWORD=<PASSWORD> <file_sep>/src/Core/Job.php <?php namespace PDFfiller\OAuth2\Client\Provider\Core; use PDFfiller\OAuth2\Client\Provider\Contracts\Arrayable; use PDFfiller\OAuth2\Client\Provider\Contracts\Async; use PDFfiller\OAuth2\Client\Provider\Contracts\Stringable; use PDFfiller\OAuth2\Client\Provider\Exceptions\JobAlreadyRunningException; class Job implements Async, Arrayable, Stringable { /** * @var Model */ private $model; /** * @var string */ private $method; /** * @var array */ private $arguments = []; /** * @var bool */ private $isReady = self::NOT_READY; /** * @var Arrayable|Stringable */ private $result; public function __construct(Model $model) { $this->model = clone $model; } /** * @return bool */ public function isReady(): bool { $this->call(); return $this->isReady; } /** * @param string $method * @param array $arguments * @return mixed * @throws JobAlreadyRunningException */ public function __call(string $method, array $arguments) { if (!empty($this->method)) { throw new JobAlreadyRunningException(); } $this->method = $method; $this->arguments = $arguments; return $this->call(); } /** * @return null|Arrayable|Stringable */ private function call() { if (empty($this->method)) { return null; } $this->result = $this->model->{$this->method}(...$this->arguments); $statusCode = $this->model->getClient()->getStatusCode(); if ($statusCode === self::HTTP_STATUS_CODE_READY) { $this->isReady = self::READY; } return $this->getResult(); } /** * @return Arrayable|Stringable */ public function getResult() { return $this->result; } /** * @return array */ public function toArray(): array { return $this->getResult()->toArray(); } /** * @return string */ public function __toString(): string { return $this->getResult()->__toString(); } } <file_sep>/examples/signature_request/6_get_signature_request_signed_document.php <?php use PDFfiller\OAuth2\Client\Provider\SignatureRequest; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $signatureRequest = SignatureRequest::one($provider, 3454); //$sr = (new SignatureRequest($provider, ['id' => 3434])); $e = $signatureRequest->signedDocument(); dd($e); <file_sep>/examples/templates/9_create_constructor.php <?php use PDFfiller\OAuth2\Client\Provider\Template; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $template = Template::one($provider, 218763307); $e = $template->createConstructor( [ 'callback_url' => 'http://google.com', 'expire' => 2, ] ); dd($e); <file_sep>/src/Contracts/AdditionalDocuments.php <?php namespace PDFfiller\OAuth2\Client\Provider\Contracts; use PDFfiller\OAuth2\Client\Provider\AdditionalDocument; /** * Interface AdditionalDocuments * @package PDFfiller\OAuth2\Client\Provider\Contracts */ interface AdditionalDocuments { const ADDITIONAL_DOCUMENTS = 'additional_documents'; const ADDITIONAL_DOCUMENTS_DOWNLOAD = 'download'; /** * Returns the list of additional documents * @param array $parameters * @return AdditionalDocument */ public function additionalDocuments($parameters = []); /** * Returns the additional document * @param $documentId * @param array $parameters * @return AdditionalDocument */ public function additionalDocument($documentId, $parameters = []); /** * Downloads all additional documents * @param array $parameters * @return mixed */ public function downloadAdditionalDocuments(array $parameters = []); /** * Creates an instance of additional document * @param array $parameters * @return AdditionalDocument */ public function createAdditionalDocument($parameters = []); } <file_sep>/examples/fillable_form/9_export_fillable_forms_filled_form.php <?php use PDFfiller\OAuth2\Client\Provider\FillableForm; use PDFfiller\OAuth2\Client\Provider\Enums\FilledFormExportFormat; use PDFfiller\OAuth2\Client\Provider\FilledForm; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $exportedForm = FillableForm::one($provider, 8494949) ->form(3434) ->export(FilledFormExportFormat::CSV); dd($exportedForm); <file_sep>/src/Callback.php <?php namespace PDFfiller\OAuth2\Client\Provider; use PDFfiller\OAuth2\Client\Provider\Core\Model; use PDFfiller\OAuth2\Client\Provider\Enums\CallbackEvent; /** * Class Callback * @package PDFfiller\OAuth2\Client\Provider * * @property int $document_id * @property CallbackEvent $event_id * @property string $callback_url */ class Callback extends Model { /** @var array */ protected $casts = [ 'event_id' => CallbackEvent::class, ]; } <file_sep>/src/Exceptions/TypeException.php <?php namespace PDFfiller\OAuth2\Client\Provider\Exceptions; use PDFfiller\OAuth2\Client\Provider\Core\Exception; /** * Class TypeException * @package PDFfiller\OAuth2\Client\Provider\Exceptions */ class TypeException extends Exception { /** @var array */ protected $typesAllowed = []; /** * TypeException constructor. * @param array $types * @param string $message * @param int $code * @param Exception|null $previous */ public function __construct($types = [], $message = "", $code = 0, Exception $previous = null) { $this->typesAllowed = $types; parent::__construct($message, $code, $previous); } /** * Returns allowed types * * @return array */ public function getTypesAllowed() { return $this->typesAllowed; } /** * @inheritdoc */ protected function getDefaultMessage() { $default = parent::getDefaultMessage(); if (!empty($this->typesAllowed)) { $default .= ". Allowed types: " . implode(', ', $this->typesAllowed); } return $default; } } <file_sep>/src/FillableForm.php <?php namespace PDFfiller\OAuth2\Client\Provider; use PDFfiller\OAuth2\Client\Provider\Core\ListObject; use PDFfiller\OAuth2\Client\Provider\Core\Model; use PDFfiller\OAuth2\Client\Provider\Core\ModelsList; use PDFfiller\OAuth2\Client\Provider\DTO\AdditionalDocument; use PDFfiller\OAuth2\Client\Provider\DTO\NotificationEmail; use PDFfiller\OAuth2\Client\Provider\Enums\DocumentAccess; use PDFfiller\OAuth2\Client\Provider\Enums\FillRequestNotifications; use PDFfiller\OAuth2\Client\Provider\Enums\FillRequestStatus; /** * Class FillRequest * @package PDFfiller\OAuth2\Client\Provider * * @property string $document_id * @property DocumentAccess $access * @property FillRequestStatus $status * @property boolean $email_required * @property boolean $name_required * @property string $custom_message * @property ListObject $notification_emails * @property boolean $required_fields * @property int $active_logo_id * @property FillRequestNotifications $notifications * @property boolean $reusable * @property array $additional_documents * @property ListObject $callbacks * @property string $callback_url * @property boolean $welcome_screen * @property boolean $enforce_required_fields * @property string $document_name * */ class FillableForm extends Model { protected $primaryKey = 'fillable_form_id'; const FORMS_URI = 'filled_forms'; const DOWNLOAD_URI = 'download'; /** @var array */ protected $casts =[ 'access' => DocumentAccess::class, 'status' => FillRequestStatus::class, 'notifications' => FillRequestNotifications::class, 'notification_emails' => ['list_of', NotificationEmail::class], 'callbacks' => ['list_of', Callback::class], ]; /** @var array */ protected $readOnly = [ 'callbacks' ]; /** * Returns filled forms * @return array|ModelsList * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException * @throws \ReflectionException */ public function forms() { $response = static::query($this->client, [$this->fillable_form_id, self::FORMS_URI]); $forms = new ModelsList(); if (isset($response['items'])) { foreach ($response['items'] as $item) { $forms[] = new FilledForm($this->client, $this->fillable_form_id, $item); } } return $forms; } /** * @param $filledFormId * @return FilledForm */ public function form($filledFormId) { $params = static::query($this->client, [$this->fillable_form_id, self::FORMS_URI, $filledFormId]); return new FilledForm($this->client, $this->fillable_form_id, $params); } /** * Downloads filled forms as a ZIP archive * * @param string $callback * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public function download(string $callback = "") { $parameters = []; if (!empty($callback) && is_string($callback)) { $parameters['callback_url'] = $callback; } return static::query($this->client, [$this->fillable_form_id, self::DOWNLOAD_URI], $parameters); } } <file_sep>/src/Enums/CallbackEvent.php <?php namespace PDFfiller\OAuth2\Client\Provider\Enums; use PDFfiller\OAuth2\Client\Provider\Core\Enum; /** * Class CallbackEvent * @package PDFfiller\OAuth2\Client\Provider\Core */ class CallbackEvent extends Enum { const FILL_REQUEST_DONE = 'fill_request.done'; const SIGNATURE_REQUEST_DONE = 'signature_request.done'; const CONSTRUCTOR_DONE = 'constructor.done'; } <file_sep>/examples/fillable_form/10_download_fillable_forms_filled_form.php <?php use PDFfiller\OAuth2\Client\Provider\FillableForm; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $e = FillableForm::one($provider, 345345) ->form(45343534) ->download(); dd($e); <file_sep>/src/SignatureRequestRecipient.php <?php namespace PDFfiller\OAuth2\Client\Provider; use PDFfiller\OAuth2\Client\Provider\Contracts\AdditionalDocuments; use PDFfiller\OAuth2\Client\Provider\Core\ListObject; use PDFfiller\OAuth2\Client\Provider\Core\Model; use PDFfiller\OAuth2\Client\Provider\Core\Exception; use PDFfiller\OAuth2\Client\Provider\Core\ModelsList; use PDFfiller\OAuth2\Client\Provider\DTO\FieldsAccess; use PDFfiller\OAuth2\Client\Provider\Enums\DocumentAccess; use PDFfiller\OAuth2\Client\Provider\Enums\SignatureRequestStatus; use PDFfiller\OAuth2\Client\Provider\Exceptions\ResponseException; /** * Class SignatureRequestRecipient * @package PDFfiller\OAuth2\Client\Provider * * @property integer $id * @property integer $user_id * @property string $email * @property string $name * @property integer $order * @property string $message_subject * @property string $message_text * @property integer $date_created unix timestamp * @property integer $date_signed unix timestamp * @property DocumentAccess $access * @property ListObject $additional_documents * @property boolean $require_photo * @property SignatureRequestStatus $status * @property FieldsAccess $fields */ class SignatureRequestRecipient extends Model implements AdditionalDocuments { const RECIPIENT = 'recipients'; const REMIND = 'remind'; /** @var int */ protected $signatureRequestId = null; /** @var string */ protected static $entityUri = 'signature_requests'; /** @var array */ protected $casts = [ 'status' => SignatureRequestStatus::class, 'access' => DocumentAccess::class, 'fields' => FieldsAccess::class, ]; /** @var array */ protected $readOnly = [ 'status', 'user_id', 'ip', 'date_signed', 'date_created', 'access', ]; /** * SignatureRequestRecipient constructor. * @param $provider * @param array $array * @param null $signatureRequestId * @throws \ReflectionException */ public function __construct($provider, $array = [], $signatureRequestId = null) { if (!is_null($signatureRequestId)) { $this->setSignatureRequestId($signatureRequestId); } parent::__construct($provider, $array); } /** * Returns request URI * * @return string */ protected function uri() { return static::getUri() . $this->signatureRequestId . '/' . self::RECIPIENT . '/'; } /** * Send the remind email to recipient * @return mixed */ public function remind() { $uri = $this->uri() . $this->id . '/' . self::REMIND; return static::put($this->client, $uri); } /** * Returns the SendToSign id * * @return int */ public function getSignatureRequestId() { return $this->signatureRequestId; } /** * Sets the signature request id * * @param int $signatureRequestId */ public function setSignatureRequestId($signatureRequestId) { $this->signatureRequestId = $signatureRequestId; } /** * Returns created recipient info. * @param array $options * @return mixed * @throws ResponseException */ public function create($options = []) { $params = $this->toArray($options); $recipients['recipients'] = [$params]; $uri = $this->uri(); $createResult = static::post($this->client, $uri, [ 'json' => $recipients, ]); if (isset($createResult['errors'])) { throw new ResponseException($createResult['errors']); } $recipientData = array_filter($createResult['recipients'], function ($recipient) use ($params) { return $recipient['email'] == $params['email']; }); return $this->parseArray(array_pop($recipientData)); } /** * @inheritdoc */ public function update($options = []) { throw new Exception("Updating instance of this items isn't supported."); } /** * @inheritdoc */ public static function all(PDFfiller $provider = null, array $params = []) { throw new Exception("Getting list of this items isn't supported."); } /** * @inheritdoc */ public static function one(PDFfiller $provider = null, $id = null) { throw new Exception("Getting instance of this items isn't supported. Use SignatureRequest class."); } /** * @inheritdoc */ public function save($options = []) { throw new Exception("Saving instance of this items isn't supported. Use SignatureRequest::addRecipient()."); } /** * @inheritdoc */ public function additionalDocuments($parameters = []) { $response = static::query($this->client, [ $this->signatureRequestId, self::RECIPIENT, $this->id, self::ADDITIONAL_DOCUMENTS ], $parameters); $response['items'] = array_map(function ($document) { return new SignatureRequestAdditionalDocument($this->client, $this->signatureRequestId, $this->id, $document); }, $response['items']); return new ModelsList($response); } /** * @inheritdoc */ public function additionalDocument($documentId, $parameters = []) { $response = static::query($this->client, [ $this->signatureRequestId, self::RECIPIENT, $this->id, self::ADDITIONAL_DOCUMENTS, $documentId, ], $parameters); return new SignatureRequestAdditionalDocument($this->client, $this->signatureRequestId, $this->id, $response); } /** * @inheritdoc */ public function downloadAdditionalDocuments($parameters = []) { return self::query($this->client, [ $this->signatureRequestId, self::RECIPIENT, $this->id, self::ADDITIONAL_DOCUMENTS, self::ADDITIONAL_DOCUMENTS_DOWNLOAD, ], $parameters); } /** * @inheritdoc */ public function createAdditionalDocument($parameters = []) { return new SignatureRequestAdditionalDocument($this->client, $this->signatureRequestId, $this->id, $parameters); } } <file_sep>/src/User.php <?php namespace PDFfiller\OAuth2\Client\Provider; use PDFfiller\OAuth2\Client\Provider\Core\Exception; use PDFfiller\OAuth2\Client\Provider\Core\Model; /** * Class User * @package PDFfiller\OAuth2\Client\Provider * @property string $id * @property string $email * @property string $avatar */ class User extends Model { const ME = 'me'; /** * @param $provider * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public static function me($provider) { return static::query($provider, [ self::ME]); } /** * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public function getMeInfo() { return self::me($this->client); } /** * @inheritdoc */ protected function create($options = []) { throw new Exception("Can't create user,."); } /** * @inheritdoc */ protected function update($options = []) { throw new Exception("Can't update user"); } /** * @inheritdoc */ public function save($options = []) { throw new Exception("Can't save user"); } } <file_sep>/examples/templates/6_get_template_info.php <?php use PDFfiller\OAuth2\Client\Provider\Template; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $e = Template::one($provider, 216865300); dd($e); <file_sep>/examples/signature_request/4_delete_signature_request.php <?php use PDFfiller\OAuth2\Client\Provider\SignatureRequest; $provider = require_once __DIR__ . '/../../examples/bootstrap/initWithFabric.php'; $e = SignatureRequest::deleteOne($provider, 333); dd($e);<file_sep>/examples/templates/16_download_original_document.php <?php use PDFfiller\OAuth2\Client\Provider\Template; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $template = new Template($provider,['id'=> 216865300]); $originalDocument = $template->getOriginalDocument(); $fp = fopen('original_document.pdf', 'w'); fwrite($fp, $originalDocument); fclose($fp); <file_sep>/examples/token/2_create_token.php <?php use PDFfiller\OAuth2\Client\Provider\Token; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $token = new Token($provider); $token->data = [ 'key1' => 'value1', 'key2' => 'value2' ]; dd($token->save()); <file_sep>/examples/signature_request/3_create_signature_request.php <?php use PDFfiller\OAuth2\Client\Provider\SignatureRequest; use PDFfiller\OAuth2\Client\Provider\SignatureRequestRecipient; use PDFfiller\OAuth2\Client\Provider\Enums\SignatureRequestMethod; use PDFfiller\OAuth2\Client\Provider\Enums\SignatureRequestSecurityPin; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $e = new SignatureRequest($provider); $e->document_id = 172423999; //$e->method = 'sendtoeach'; /////////// $e->method = new SignatureRequestMethod(SignatureRequestMethod::SEND_TO_GROUP); $e->envelope_name = 'group envelope'; $e->sign_in_order = false; ////////// $e->security_pin = new SignatureRequestSecurityPin(SignatureRequestSecurityPin::STANDARD); $e->recipients[] = new SignatureRequestRecipient($provider, [ 'email' => '<EMAIL>', 'name' => '<NAME>', 'access' => 'full', 'require_photo' => false, 'message_subject' => 'subject', 'message_text' => 'message', 'additional_documents' => [ 'doc1' ] ]); dd($e->save()); <file_sep>/src/Core/Enum.php <?php namespace PDFfiller\OAuth2\Client\Provider\Core; use PDFfiller\OAuth2\Client\Provider\Contracts\Stringable; /** * Class Enum * @package PDFfiller\OAuth2\Client\Provider\Core */ abstract class Enum implements Stringable { const __default = null; private $value = self::__default; /** * Enum constructor. * * @param null $value */ public function __construct($value = self::__default) { $constants = $this->getConstants(); if (!in_array($value, $constants)) { throw new \InvalidArgumentException("Value must be one of class constants:"); } $this->value = $value; } /** * Returns an array of possible class values. * * @param bool $includeDefault * @return array */ public function getConstants(bool $includeDefault = false): array { $constants = (new \ReflectionClass($this))->getConstants(); if (!$includeDefault) { unset($constants['__default']); } return $constants; } /** * @return null */ public function getValue() { return $this->value; } /** * @inheritdoc */ public function __toString(): string { return $this->getValue(); } } <file_sep>/examples/callback/1_get_callbacks_list.php <?php use PDFfiller\OAuth2\Client\Provider\Callback; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $list = Callback::all($provider); dd($list->toArray()); <file_sep>/src/PDFfiller.php <?php namespace PDFfiller\OAuth2\Client\Provider; use League\OAuth2\Client\Provider\Exception\IdentityProviderException; use League\OAuth2\Client\Token\AccessToken; use PDFfiller\OAuth2\Client\Provider\Enums\GrantType; use PDFfiller\OAuth2\Client\Provider\Exceptions\InvalidBodyException; use PDFfiller\OAuth2\Client\Provider\Exceptions\InvalidBodySourceException; use PDFfiller\OAuth2\Client\Provider\Exceptions\InvalidQueryException; use PDFfiller\OAuth2\Client\Provider\Exceptions\OptionsMissingException; use PDFfiller\OAuth2\Client\Provider\Exceptions\ResponseException; use PDFfiller\OAuth2\Client\Provider\Exceptions\TokenMissingException; use League\OAuth2\Client\Provider\GenericProvider; use Psr\Http\Message\RequestInterface; use \GuzzleHttp\Psr7 as Psr7; use Psr\Http\Message\ResponseInterface; /** * Represents a generic service provider that may be used to interact with any * OAuth 2.0 service provider, using Bearer token authentication. */ class PDFfiller extends GenericProvider { const USER_AGENT = 'PDFfiller Rest-API PHP-Client'; const VERSION = '2.0.0'; /** @var */ private $urlApiDomain; private $accessToken; private $statusCode; /** * PDFfiller constructor. * @param array $options * @param array $collaborators * @throws OptionsMissingException */ public function __construct(array $options = [], array $collaborators = []) { $this->assertPdffillerOptions($options); $possible = $this->getPdffillerOptions(); $configured = array_intersect_key($options, array_flip($possible)); foreach ($configured as $key => $value) { $this->$key = $value; } // Remove all options that are only used locally $options = array_diff_key($options, $configured); $options = array_merge([ 'redirectUri' => 'http://localhost/redirect_uri', 'urlAuthorize' => 'http://localhost/url_authorize', 'urlResourceOwnerDetails' => 'http://localhost/url_resource_owner_details'], $options); parent::__construct($options, $collaborators); } /** * Returns request with authentication credentials * @param string $method * @param string $url * @param AccessToken|string $token * @param array $options * @return RequestInterface */ public function getAuthenticatedRequest($method, $url, $token, array $options = []) { $baseUri = new Psr7\Uri($this->urlApiDomain); $relativeUri = new Psr7\Uri($url); $newUri = Psr7\Uri::resolve($baseUri, $relativeUri); return parent::getAuthenticatedRequest($method, $newUri, $token, $options); } /** * Applies the array of request options to a request. * @param RequestInterface $request * @param array $options * @return RequestInterface * @throws InvalidBodySourceException * @throws InvalidBodyException * @throws InvalidQueryException */ private function applyOptions(RequestInterface $request, array &$options) { $modify = []; if (isset($options['form_params'])) { if (isset($options['multipart'])) { throw new InvalidBodySourceException(); } $options['body'] = http_build_query($options['form_params'], null, '&'); unset($options['form_params']); $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded'; } if (isset($options['multipart'])) { $elements = $options['multipart']; unset($options['multipart']); $options['body'] = new Psr7\MultipartStream($elements); } if (!empty($options['decode_content']) && $options['decode_content'] !== true ) { $modify['set_headers']['Accept-Encoding'] = $options['decode_content']; } if (isset($options['headers'])) { if (isset($modify['set_headers'])) { $modify['set_headers'] = $options['headers'] + $modify['set_headers']; } else { $modify['set_headers'] = $options['headers']; } unset($options['headers']); } if (isset($options['body'])) { if (is_array($options['body'])) { throw new InvalidBodyException(); } $modify['body'] = Psr7\stream_for($options['body']); unset($options['body']); } if (!empty($options['auth'])) { $value = $options['auth']; $type = is_array($value) ? (isset($value[2]) ? strtolower($value[2]) : 'basic') : $value; $config['auth'] = $value; switch (strtolower($type)) { case 'basic': $modify['set_headers']['Authorization'] = 'Basic ' . base64_encode("$value[0]:$value[1]"); break; case 'digest': // @todo: Do not rely on curl $options['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_DIGEST; $options['curl'][CURLOPT_USERPWD] = "$value[0]:$value[1]"; break; } } if (isset($options['query'])) { $value = $options['query']; if (is_array($value)) { $value = http_build_query($value, null, '&', PHP_QUERY_RFC3986); } if (!is_string($value)) { throw new InvalidQueryException(); } $modify['query'] = $value; unset($options['query']); } if (isset($options['json'])) { $modify['body'] = Psr7\stream_for(json_encode($options['json'])); $options['_conditional']['Content-Type'] = 'application/json'; unset($options['json']); } $request = Psr7\modify_request($request, $modify); if ($request->getBody() instanceof Psr7\MultipartStream) { // Use a multipart/form-data POST if a Content-Type is not set. $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary=' . $request->getBody()->getBoundary(); } // Merge in conditional headers if they are not present. if (isset($options['_conditional'])) { // Build up the changes so it's in a single clone of the message. $modify = []; foreach ($options['_conditional'] as $k => $v) { if (!$request->hasHeader($k)) { $modify['set_headers'][$k] = $v; } } $request = Psr7\modify_request($request, $modify); // Don't pass this internal value along to middleware/handlers. unset($options['_conditional']); } return $request; } /** * Performs a request and returns the response * * @param $method * @param $url * @param array $options * @return array * @throws TokenMissingException */ public function apiCall($method, $url, $options = []) { if($this->accessToken === null) { throw new TokenMissingException(); } $options['headers']['User-Agent'] = self::USER_AGENT . '/' . self::VERSION; $request = $this->getAuthenticatedRequest($method, $url, $this->getAccessToken()->getToken(), $options); $request = $this->applyOptions($request, $options); return $this->getResponse($request); } /** * Returns result of authorized GET request * @param $url * @param array $options * @return array */ public function queryApiCall($url , $options = []) { return $this->apiCall('GET', $url, $options); } /** * Returns result of authorized POST request * @param $url * @param array $options * @return array */ public function postApiCall($url , $options = []) { return $this->apiCall('POST', $url, $options); } /** * Returns result of authorized PUT request * @param $url * @param array $options * @return array */ public function putApiCall($url , $options = []) { return $this->apiCall('PUT', $url, $options); } /** * Returns result of authorized DELETE request * @param $url * @param array $options * @return array */ public function deleteApiCall($url , $options = []) { return $this->apiCall('DELETE', $url, $options); } /** * Returns status code * * @return int|null */ public function getStatusCode() { return $this->statusCode; } /** * @inheritdoc */ public function getResponse(RequestInterface $request) { $response = $this->sendRequest($request); $parsed = $this->parseResponse($response); $this->statusCode = $response->getStatusCode(); $this->checkResponse($response, $parsed); return $parsed; } /** * Returns an array of needed options * @return array */ protected function getPdffillerOptions() { return [ 'urlApiDomain', ]; } /** * Verifies that all required options have been passed. * * @param array $options * @return void * @throws OptionsMissingException */ private function assertPdffillerOptions(array $options) { $missing = array_diff_key(array_flip($this->getPdffillerOptions()), $options); if (!empty($missing)) { throw new OptionsMissingException(array_keys($missing)); } } /** * Returns an access token object * * @param string $grant * @param array $options * @return AccessToken */ public function getAccessToken($grant = 'client_credentials', array $options = []) { if($this->accessToken !== null) { return $this->accessToken; } return $this->accessToken = $this->issueAccessToken($grant, $options); } /** * Requests a new access token * * @param $grant * @param array $options * @return AccessToken */ public function issueAccessToken($grant, array $options = []) { if ($grant instanceof GrantType) { $grant = $grant->getValue(); } return parent::getAccessToken($grant, $options); } /** * Sets an access token of current provider object * * @param AccessToken $value * @return $this */ public function setAccessToken(AccessToken $value) { $this->accessToken = $value; return $this; } /** * Checks a provider response for errors. * * @throws IdentityProviderException * @throws ResponseException * @param ResponseInterface $response * @param array|string $data Parsed response data * @return void */ protected function checkResponse(ResponseInterface $response, $data) { if (!empty($data['errors'])) { $errors = $data['errors']; throw new ResponseException($errors); } parent::checkResponse($response, $data); } } <file_sep>/src/FilledForm.php <?php namespace PDFfiller\OAuth2\Client\Provider; use PDFfiller\OAuth2\Client\Provider\Contracts\AdditionalDocuments; use PDFfiller\OAuth2\Client\Provider\Core\Model; use PDFfiller\OAuth2\Client\Provider\Core\ModelsList; use PDFfiller\OAuth2\Client\Provider\Enums\FilledFormExportFormat; /** * Class FillRequestForm * @package PDFfiller\OAuth2\Client\Provider * * @property integer $document_id * @property string $name * @property string $email * @property string $date * @property integer $filled_form_id */ class FilledForm extends Model implements AdditionalDocuments { const DOWNLOAD = 'download'; const EXPORT = 'export'; protected $primaryKey = 'filled_form_id'; /** @var int */ private $fillableFormId; /** @var string */ protected static $baseUri = 'fillable_forms'; /** * FilledForm constructor. * @param $provider * @param $fillableFormId * @param array $array * @throws \ReflectionException */ public function __construct($provider, $fillableFormId, $array = []) { $this->fillableFormId = $fillableFormId; static::setEntityUri(static::$baseUri . '/' . $fillableFormId . '/' . FillableForm::FORMS_URI); parent::__construct($provider, $array); } /** * @return int */ public function getFillableFormId() { return $this->fillableFormId; } /** * @param int $fillableFormId */ public function setFillableFormId($fillableFormId) { $this->fillableFormId = $fillableFormId; } /** * Exports form * * @param string|FilledFormExportFormat $format * @return mixed */ public function export($format = FilledFormExportFormat::JSON) { if (! $format instanceof FilledFormExportFormat) { $format = new FilledFormExportFormat($format); } return static::query($this->client, [$this->filled_form_id, self::EXPORT], ['format' => $format->getValue()]); } /** * Downloads form * * @return mixed */ public function download() { return static::query($this->client, [$this->filled_form_id, self::DOWNLOAD]); } /** * @inheritdoc */ public function additionalDocuments($parameters = []) { $response = static::query($this->client, [$this->filled_form_id, self::ADDITIONAL_DOCUMENTS], $parameters); $response['items'] = array_map(function ($document) { return $this->createAdditionalDocument($document); }, $response['items']); return new ModelsList($response); } /** * @inheritdoc */ public function additionalDocument($documentId, $parameters = []) { $response = static::query($this->client, [$this->filled_form_id, self::ADDITIONAL_DOCUMENTS, $documentId], $parameters); return $this->createAdditionalDocument($response); } /** * @param array $parameters * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public function downloadAdditionalDocuments(array $parameters = []) { return self::query($this->client, [ $this->filled_form_id, self::ADDITIONAL_DOCUMENTS, self::ADDITIONAL_DOCUMENTS_DOWNLOAD, ], $parameters); } /** * @inheritdoc */ public function createAdditionalDocument($parameters = []) { return new FillRequestAdditionalDocument($this->client, $this->fillableFormId, $this->filled_form_id, $parameters); } } <file_sep>/examples/signature_request/8_get_signature_request_recipient.php <?php use PDFfiller\OAuth2\Client\Provider\SignatureRequest; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; //$recipient = SignatureRequest::one($provider, 334721)->getRecipient(550632); $recipient = SignatureRequest::recipient($provider, 34, 545); dd($recipient->toArray()); <file_sep>/examples/signature_request/12_get_signature_request_inbox_download.php <?php use PDFfiller\OAuth2\Client\Provider\SignatureRequest; use \PDFfiller\OAuth2\Client\Provider\Enums\SignatureRequestStatus; use PDFfiller\OAuth2\Client\Provider\Core\Job; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $signatureRequestEntity = new \PDFfiller\OAuth2\Client\Provider\SignatureRequest($provider); $signatureRequests = new SignatureRequest($provider); $signatureRequestsAsync = new Job($signatureRequests); $signatureRequestsAsync->getInboxContent([ 'status' => new SignatureRequestStatus(SignatureRequestStatus::SENT) /* supports only x, in_progress, sent */, 'perpage' => 3, 'datefrom' => '2016-05-01', 'dateto' => '2016-12-30' ]); while (!$signatureRequestsAsync->isReady()) { sleep(2); } $fp = fopen('inbox.zip', 'w'); fwrite($fp, $signatureRequestsAsync->getResult()); fclose($fp); die(); <file_sep>/examples/application/1_get_application_list.php <?php use PDFfiller\OAuth2\Client\Provider\Application; use \PDFfiller\OAuth2\Client\Provider\Exceptions\ResponseException; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $application = new Application($provider); try { $response = Application::all($provider); dd($response->toArray()); } catch (ResponseException $e) { dd($e); } <file_sep>/examples/ExampleFabric.php <?php namespace Examples; use League\OAuth2\Client\Token\AccessToken; use PDFfiller\OAuth2\Client\Provider\Enums\GrantType; use PDFfiller\OAuth2\Client\Provider\PDFfiller; use Flintstone\Flintstone; use AdammBalogh\KeyValueStore\Adapter\FileAdapter; use AdammBalogh\KeyValueStore\KeyValueStore; use Carbon\Carbon; class ExampleFabric { const TIME_ZONE = 'America/New_York'; const ACCESS_TOKEN_KEY = 'access_token'; const REFRESH_TOKEN_KEY = 'refresh_token'; /** @var PDFfiller */ private $provider = null; /** @var string */ private $type = null; /** * ExampleFabric constructor. * * @param GrantType $grantType * @param array $params */ public function __construct(GrantType $grantType, $params = []) { $this->provider = new PDFfiller($params); $this->type = $grantType; } /** * Returns the provider ready to use * * @param array $accessTokenParams * @param bool $useCache * @return PDFfiller */ public function getProvider($accessTokenParams = [], $useCache = true) { if (!$useCache) { $this->provider->getAccessToken($this->type, $accessTokenParams); return $this->provider; } return $this->provider->setAccessToken($this->getToken($accessTokenParams)); } /** * Puts the given access token to the local cache * * @param AccessToken $accessToken */ private function cacheToken(AccessToken $accessToken) { $tz = self::TIME_ZONE; $kvs = $this->getKeyValueStorage(); $liveTimeInSec = Carbon::createFromTimestamp($accessToken->getExpires(), $tz)->diffInSeconds(Carbon::now($tz)); $kvs->set(self::ACCESS_TOKEN_KEY, $accessToken->getToken()); $kvs->expire(self::ACCESS_TOKEN_KEY, $liveTimeInSec); $kvs->set(self::REFRESH_TOKEN_KEY, $accessToken->getRefreshToken()); } /** * Gets the access token from the cache if it exists there * or requests the new one with given credentials. * * @param $accessTokenParams * @return AccessToken */ private function getToken($accessTokenParams) { $kvs = $this->getKeyValueStorage(); if ($kvs->has(self::ACCESS_TOKEN_KEY) && $kvs->has(self::REFRESH_TOKEN_KEY)) { return new AccessToken([ 'access_token' => $kvs->get(self::ACCESS_TOKEN_KEY), 'expires_in' => $kvs->getTtl(self::ACCESS_TOKEN_KEY), 'refresh_token' => $kvs->get(self::REFRESH_TOKEN_KEY), ]); } $accessToken = $this->provider->getAccessToken($this->type, $accessTokenParams); $this->cacheToken($accessToken); return $accessToken; } /** * Returns the local cache adapter * * @return KeyValueStore */ private function getKeyValueStorage() { $tmp_dir = sys_get_temp_dir() ?: ini_get('upload_tmp_dir'); return new KeyValueStore(new FileAdapter(Flintstone::load('usersDatabase', ['dir' => $tmp_dir]))); } } <file_sep>/src/Enums/SignatureRequestSecurityPin.php <?php namespace PDFfiller\OAuth2\Client\Provider\Enums; use PDFfiller\OAuth2\Client\Provider\Core\Enum; /** * Class SignatureRequestSecurityPin * @package PDFfiller\OAuth2\Client\Provider\Core */ class SignatureRequestSecurityPin extends Enum { const STANDARD = 'standard'; const ENHANCED = 'enhanced'; } <file_sep>/src/Core/ListObject.php <?php namespace PDFfiller\OAuth2\Client\Provider\Core; use PDFfiller\OAuth2\Client\Provider\Contracts\Arrayable; use ArrayAccess; use Iterator; /** * Class ListObject * @package PDFfiller\OAuth2\Client\Provider\Core */ class ListObject implements ArrayAccess, Arrayable, Iterator { /** @var array */ protected $items = []; /** * ListObject constructor. * @param array $items */ public function __construct($items = []) { $this->items = $items; } /** * @inheritdoc */ public function toArray(): array { return array_map(function ($entry) { if ($entry instanceof Arrayable) { return $entry->toArray(); } return $entry; }, $this->items); } /** * @inheritdoc */ public function offsetExists($offset): bool { return isset($this->items[$offset]); } /** * @inheritdoc */ public function offsetGet($offset) { if (isset($this->items[$offset])) { return $this->items[$offset]; } return null; } /** * @inheritdoc */ public function offsetSet($offset, $value) { if (is_null($offset)) { $this->items[] = $value; } else { $this->items[$offset] = $value; } } /** * @inheritdoc */ public function offsetUnset($offset) { unset($this->items[$offset]); } /** * @inheritdoc */ public function current() { return current($this->items); } /** * @inheritdoc */ public function next() { return next($this->items); } /** * @inheritdoc */ public function key() { return key($this->items); } /** * @inheritdoc */ public function valid() { return key($this->items) !== null; } /** * @inheritdoc */ public function rewind() { return reset($this->items); } } <file_sep>/examples/callback/2_create_callback.php <?php use PDFfiller\OAuth2\Client\Provider\Callback; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $callback = new Callback($provider); $callback->document_id = 172323999; $callback->event_id = "constructor.done"; $callback->callback_url = "http://pdffiller.com"; dd($callback->save()); <file_sep>/examples/token/3_get_token.php <?php use PDFfiller\OAuth2\Client\Provider\Token; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $e = Token::one($provider, 3329); dd($e); <file_sep>/examples/auth/password_grant.php <?php require_once __DIR__.'/../bootstrap/init.php'; use PDFfiller\OAuth2\Client\Provider\Enums\GrantType; use \PDFfiller\OAuth2\Client\Provider\PDFfiller; $provider = new PDFfiller([ 'clientId' => getenv('CLIENT_ID'), 'clientSecret' => getenv('CLIENT_SECRET'), 'urlAccessToken' => getenv('URL_ACCESS_TOKEN'), 'redirectUri' => getenv('REDIRECT_URI'), 'urlApiDomain' => getenv('URL_API_DOMAIN') ]); $provider->getAccessToken(new GrantType(GrantType::PASSWORD_GRANT), [ 'username' => getenv('USER_EMAIL'), 'password' => getenv('<PASSWORD>') ]); dd($provider->queryApiCall('test')); <file_sep>/examples/templates/3_get_template_list.php <?php use PDFfiller\OAuth2\Client\Provider\Template; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $e = Template::all($provider, ['order' => 'asc']); dd($e); <file_sep>/src/Token.php <?php namespace PDFfiller\OAuth2\Client\Provider; use PDFfiller\OAuth2\Client\Provider\Core\ListObject; use PDFfiller\OAuth2\Client\Provider\Core\Model; /** * Class Token * @package PDFfiller\OAuth2\Client\Provider * * @property ListObject $data * @property string $hash */ class Token extends Model { protected $casts = [ 'data' => 'list' ]; } <file_sep>/src/Core/ModelsList.php <?php namespace PDFfiller\OAuth2\Client\Provider\Core; /** * Class ModelsList * @package PDFfiller\OAuth2\Client\Provider\Core */ class ModelsList extends ListObject { /** @var int */ protected $total = 0; /** @var int */ protected $current_page = 1; /** @var int */ protected $per_page = 15; /** @var string */ protected $prev_page_url = null; /** @var string */ protected $next_page_url = null; /** * ModelsList constructor. * @param array $attributes */ public function __construct($attributes = []) { foreach($attributes as $name => $attribute) { if ($name == 'items') { parent::__construct($attribute); continue; } if (property_exists($this, $name)) { $this->{$name} = $attribute; } } } /** * @return int */ public function getTotal() { return $this->total; } /** * @param int $total */ public function setTotal($total) { $this->total = $total; } /** * @return int */ public function getCurrentPage() { return $this->current_page; } /** * @param int $currentPage */ public function setCurrentPage($currentPage) { $this->current_page = $currentPage; } /** * @return int */ public function getPerPage() { return $this->per_page; } /** * @param int $perPage */ public function setPerPage($perPage) { $this->per_page = $perPage; } /** * @return null */ public function getPrevPageUrl() { return $this->prev_page_url; } /** * @param null $prevPageUrl */ public function setPrevPageUrl($prevPageUrl) { $this->prev_page_url = $prevPageUrl; } /** * @return null */ public function getNextPageUrl() { return $this->next_page_url; } /** * @param null $nextPageUrl */ public function setNextPageUrl($nextPageUrl) { $this->next_page_url = $nextPageUrl; } /** * @return array */ public function getList() { return $this->items; } } <file_sep>/examples/folder/4_create_folder.php <?php use PDFfiller\OAuth2\Client\Provider\Folder; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $folder = new Folder($provider); $folder->name = "New folder"; $e = $folder->save(); dd($e);<file_sep>/src/Exceptions/OptionsMissingException.php <?php namespace PDFfiller\OAuth2\Client\Provider\Exceptions; use PDFfiller\OAuth2\Client\Provider\Core\Exception; /** * Class OptionsMissingException * Handle missing required options exception. * @package PDFfiller\OAuth2\Client\Provider\Exceptions */ class OptionsMissingException extends Exception { /** @var array */ protected $options = []; /** * OptionsMissingException constructor. * @param array $options * @param int $code * @param Exception|null $previous */ public function __construct($options, $code = 0, Exception $previous = null) { $this->options = $options; parent::__construct("", $code, $previous); } /** * @inheritdoc */ protected function getDefaultMessage() { return parent::getDefaultMessage() . ': ' . implode(', ', $this->options); } /** * Returns options * * @return array */ public function getOptions() { return $this->options; } } <file_sep>/examples/templates/13_fill_template.php <?php use PDFfiller\OAuth2\Client\Provider\Template; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $fillableFields = [ 'Text_1' => 'Fillable field text' ]; $template = new Template($provider,['id'=> 216865300, 'fillable_fields' => $fillableFields]); $e = $template->fill(); dd($e); <file_sep>/src/Enums/GrantType.php <?php namespace PDFfiller\OAuth2\Client\Provider\Enums; use PDFfiller\OAuth2\Client\Provider\Core\Enum; /** * Class GrantType * @package PDFfiller\OAuth2\Client\Provider\Core */ class GrantType extends Enum { const __default = self::PASSWORD_GRANT; const PASSWORD_GRANT = 'password'; const REFRESH_TOKEN_GRANT = 'refresh_token'; const AUTHORIZATION_CODE_GRANT = 'authorization_code'; } <file_sep>/src/Core/Exception.php <?php namespace PDFfiller\OAuth2\Client\Provider\Core; /** * Class Exception * * Basic exception class * * @package PDFfiller\OAuth2\Client\Provider\Core */ class Exception extends \Exception { /** @var string */ protected $defaultMessage = ""; /** * Exception constructor. * * @param string $message * @param int $code * @param Exception|null $previous */ public function __construct(string $message = "", $code = 0, Exception $previous = null) { if (empty($message)) { $message = $this->getDefaultMessage(); } parent::__construct($message, $code, $previous); } /** * Returns the default message * * @return string */ protected function getDefaultMessage() { return (new ExceptionsMessages($this))->getMessage(); } } <file_sep>/src/Exceptions/TokenMissingException.php <?php namespace PDFfiller\OAuth2\Client\Provider\Exceptions; use PDFfiller\OAuth2\Client\Provider\Core\Exception; /** * Class TokenMissingException * Handle token missing exception * @package PDFfiller\OAuth2\Client\Provider\Exceptions */ class TokenMissingException extends Exception {} <file_sep>/examples/application/4_update_application.php <?php use PDFfiller\OAuth2\Client\Provider\Application; use \PDFfiller\OAuth2\Client\Provider\Exceptions\ResponseException; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; try { $application = Application::one($provider, '84e6f23172c0c51a'); //$application->name = 'Updated App name'; $application->description = 'Some changed application description'; //$application->all_domains = true; $response = $application->save(); dd($response); } catch (ResponseException $e) { dd($e->getMessage()); } <file_sep>/examples/custom_logo/3_create_logo_multipart.php <?php use PDFfiller\OAuth2\Client\Provider\Uploader; use PDFfiller\OAuth2\Client\Provider\CustomLogo; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $uploader = new Uploader($provider, CustomLogo::class); $uploader->type = Uploader::TYPE_MULTIPART; $uploader->file = __DIR__ . '/test.jpg'; $document = $uploader->upload(); dd($document); <file_sep>/src/Application.php <?php namespace PDFfiller\OAuth2\Client\Provider; use PDFfiller\OAuth2\Client\Provider\Core\Model; use PDFfiller\OAuth2\Client\Provider\DTO\EmbeddedClient; /** * Class Application * @package PDFfiller\OAuth2\Client\Provider * * @property string $name * @property string $description * @property string $domain * @property string $all_domains * @property string $embedded_domain * @property EmbeddedClient $embedded_client */ class Application extends Model { /** @var array */ protected $mapper = [ 'all_domains' => 'all-domains', 'embedded_domain' => 'embedded-domain' ]; protected $readOnly = ['embedded_client']; protected $casts = [ 'embedded_client' => EmbeddedClient::class, ]; const RULES_KEY = 'application'; /** * @inheritdoc */ protected function prepareFields($options = []) { $embeddedClient = $this->embedded_client; $fields = parent::prepareFields($options); if (!isset($embeddedClient)) { return $fields; } if (!isset($fields['all-domains'])) { $fields['all-domains'] = $embeddedClient->allow_all_domains; } return $fields; } } <file_sep>/examples/templates/2_create_tempalate_via_url.php <?php use PDFfiller\OAuth2\Client\Provider\Uploader; use \PDFfiller\OAuth2\Client\Provider\Template; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $uploader = new Uploader($provider, Template::class); $uploader->type = Uploader::TYPE_URL; $uploader->file = 'http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf'; $template = $uploader->upload(); dd($template); <file_sep>/src/Exceptions/ErrorsException.php <?php namespace PDFfiller\OAuth2\Client\Provider\Exceptions; use PDFfiller\OAuth2\Client\Provider\Core\Exception; /** * Class ErrorsException * Handle exceptions with errors messages. * @package PDFfiller\OAuth2\Client\Provider\Exceptions */ class ErrorsException extends Exception { /** @var array */ protected $errors = []; /** * ErrorsException constructor. * @param string $errors * @param string $message * @param int $code * @param Exception|null $previous */ public function __construct($errors, $message = "", $code = 0, Exception $previous = null) { $this->errors = $errors; parent::__construct($message, $code, $previous); } /** * @return array */ public function getErrors() { return $this->errors; } } <file_sep>/src/DTO/FieldsAccess.php <?php namespace PDFfiller\OAuth2\Client\Provider\DTO; use PDFfiller\OAuth2\Client\Provider\Core\AbstractObject; use PDFfiller\OAuth2\Client\Provider\Core\ListObject; /** * Class FieldsAccess * @package PDFfiller\OAuth2\Client\DTO * * @property ListObject $allow * @property ListObject $deny */ class FieldsAccess extends AbstractObject { /** @var array */ protected $casts = [ 'allow' => 'list', 'deny' => 'list', ]; /** @var array */ protected $attributes = [ 'allow', 'deny' ]; /** * FieldsAccess constructor. * @param $properties */ public function __construct($properties) { $properties = array_merge([ 'allow' => new ListObject(), 'deny' => new ListObject() ], $properties); parent::__construct($properties); } } <file_sep>/examples/templates/8_download_signatures.php <?php use PDFfiller\OAuth2\Client\Provider\Template; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $signatures = Template::downloadSignatures($provider, 216865300); $fp = fopen('signatures.zip', 'w'); fwrite($fp, $signatures); fclose($fp); <file_sep>/src/Traits/CastsTrait.php <?php namespace PDFfiller\OAuth2\Client\Provider\Traits; use PDFfiller\OAuth2\Client\Provider\Core\AbstractObject; use PDFfiller\OAuth2\Client\Provider\Core\Enum; use PDFfiller\OAuth2\Client\Provider\Core\ListObject; use PDFfiller\OAuth2\Client\Provider\Core\Model; trait CastsTrait { /** @var array */ protected $casts= []; /** * Casts the field * * @param $option * @param $value * @return bool|float|mixed|ListObject|string */ private function castField($option, $value) { $casts = $this->casts; if (!isset($casts[$option])) { return $value; } $cast = $casts[$option]; if (is_null($value) || is_null($cast)) { return $value; } if (is_array($cast)) { return $this->complexListCast($value, $cast); } switch ($cast) { case 'int': case 'integer': return (int) $value; case 'real': case 'float': case 'double': return (float) $value; case 'string': return (string) $value; case 'bool': case 'boolean': return (bool) $value; case 'list': return $this->castToList($value); default: return $this->castToObject($value, $cast); } } private function complexListCast($value, $castInfo) { if (count($castInfo) < 2) { return $this->castToList($value); } if ($castInfo[0] !== 'list_of' || !is_array($value)) { return $value; } $class = $castInfo[1]; $result = new ListObject(); foreach ($value as $entry) { $result[] = $this->castToObject($entry, $class); } return $result; } /** * Casts value to the given class * * @param $value * @param $class * @return mixed */ private function castToObject($value, $class) { if (!class_exists($class) || $value instanceof $class) { return $value; } $parentClasses = class_parents($class); if (in_array(Enum::class, $parentClasses) || in_array(AbstractObject::class, $parentClasses)) { return new $class($value); } if (in_array(Model::class, $parentClasses)) { return new $class($this->getClient(), $value); } if (in_array(ListObject::class, $parentClasses)) { return new $class($value); } return $value; } /** * Casts value to the list * @param $value * @return ListObject */ private function castToList($value) { if ($value instanceof ListObject) { return $value; } return new ListObject((array)$value); } } <file_sep>/examples/callback/3_get_callback.php <?php use PDFfiller\OAuth2\Client\Provider\Callback; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $callback = Callback::one($provider, 34324); dd($callback); <file_sep>/src/Enums/SignatureRequestStatus.php <?php namespace PDFfiller\OAuth2\Client\Provider\Enums; use PDFfiller\OAuth2\Client\Provider\Core\Enum; /** * Class SignatureRequestStatus * @package PDFfiller\OAuth2\Client\Provider\Core */ class SignatureRequestStatus extends Enum { const IN_PROGRESS = 'IN_PROGRESS'; const NOT_SENT = 'NOT_SENT'; const REJECTED = 'REJECTED'; const SENT = 'SENT'; const SIGNED = 'SIGNED'; const COMPLETED = 'COMPLETED'; const DECLINE = 'DECLINE'; const UNSUPPORTED_STATUS_VALUE = 'UNSUPPORTED_STATUS_VALUE'; } <file_sep>/examples/templates/1_create_template_multipart.php <?php use PDFfiller\OAuth2\Client\Provider\Uploader; use \PDFfiller\OAuth2\Client\Provider\Template; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $uploader = new Uploader($provider, Template::class); $uploader->type = Uploader::TYPE_MULTIPART; $uploader->file = __DIR__ . '/pdf_open_parameters.pdf'; $uploader->setAdditionalAttributes(['folder_id' => 318140]); $template = $uploader->upload(); dd($template); <file_sep>/src/Uploader.php <?php namespace PDFfiller\OAuth2\Client\Provider; use PDFfiller\OAuth2\Client\Provider\Core\Exception; use PDFfiller\OAuth2\Client\Provider\Core\Model; use PDFfiller\OAuth2\Client\Provider\Contracts\Uploadable; use PDFfiller\OAuth2\Client\Provider\Exceptions\TypeException; /** * Class Uploader * @package PDFfiller\OAuth2\Client\Provider * * @property string $file absolute file path or url * @property string $type */ class Uploader extends Model { const TYPE_URL = "url"; const TYPE_MULTIPART = "multipart"; /** @var string */ protected static $entityUri = 'document'; /** @var array|null */ protected $class = null; /** @var array */ protected $attributesAdditional = []; /** * Uploader constructor. * @param PDFfiller $provider * @param array $class * @param array $array * @throws Exception */ public function __construct($provider, $class, array $array = []) { if (!in_array(Uploadable::class, class_implements($class))) { throw new Exception("Given class must implements Uploadable interface"); } if (!is_subclass_of($class, Model::class)) { throw new Exception("Given class must be a subclass of Model"); } $this->class = $class; parent::__construct($provider, $array); } /** * Sets additional attributes * * @param $attributes */ public function setAdditionalAttributes($attributes) { $this->attributesAdditional = $attributes; } /** * Returns additional attributes * * @return array */ public function getAdditionalAttributes() { return $this->attributesAdditional; } /** * Prepares upload request parameters * * @return array|null */ public function getUploadParams() { if ($this->type === self::TYPE_URL) { return [ 'json' => array_merge($this->getAdditionalAttributes(), ['file' => $this->file]), ]; } if ($this->type === self::TYPE_MULTIPART) { $params[] = [ 'name' => 'file', 'contents' => fopen($this->file, 'r'), ]; foreach ($this->getAdditionalAttributes() as $key => $value) { $params[] = [ 'name' => $key, 'contents' => $value, ]; } return [ 'multipart' => $params ]; } return null; } /** * @inheritdoc */ public function attributes() { return $this->attributes; } /** * Uploads file and returns the model * * @return null|Model */ public function upload() { $params = $this->getUploadParams(); if ($params) { $class = $this->class; $uri = $class::getUri(); $document = static::post($this->client, $uri, $params); /** @var Model $instance */ $instance = new $this->class($this->client, $document); $instance->exists = true; $instance->cacheFields($document); return $instance; } return null; } /** * @param string $type must be "url" or "multipart", use Uploader::TYPE_URL and Uploader::TYPE_MULTIPART * @throws TypeException */ public function setType($type) { if ($type != self::TYPE_MULTIPART && $type !=self::TYPE_URL) { throw new TypeException([self::TYPE_MULTIPART, self::TYPE_URL]); } $this->type = $type; } } <file_sep>/examples/signature_request/13_signature_request_additional_documents.php <?php use PDFfiller\OAuth2\Client\Provider\SignatureRequestRecipient; use PDFfiller\OAuth2\Client\Provider\Core\Job; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $recipient = new SignatureRequestRecipient($provider, ['id' => 1308788], 807461); // Getting the list of additional documents //$list = $recipient->additionalDocuments(); //dd($list->toArray()); // Getting the additional documents by ID //$document = $recipient->additionalDocument(1770196); //dd($document); // Downloading the additional documents by ID $document = $recipient->additionalDocument(1770196); dd($document->download()); $recipientAsync = new Job($recipient); $recipientAsync->downloadAdditionalDocuments(); while (!$recipientAsync->isReady()) { sleep(2); } dd($recipientAsync);<file_sep>/examples/callback/4_update_callback.php <?php use PDFfiller\OAuth2\Client\Provider\Callback; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $callback = Callback::one($provider, 324234); $callback->document_id = 45345345; $callback->event_id = "constructor.done"; $callback->callback_url = "http://pdffiller.com/callback_destination"; dd($callback->save()); <file_sep>/src/Enums/FilledFormExportFormat.php <?php namespace PDFfiller\OAuth2\Client\Provider\Enums; use PDFfiller\OAuth2\Client\Provider\Core\Enum; /** * Class SignatureRequestMethod * @package PDFfiller\OAuth2\Client\Provider\Core */ class FilledFormExportFormat extends Enum { const JSON = 'json'; const XLS = 'xls'; const XLSX = 'xlsx'; const CSV = 'csv'; const HTML = 'html'; const __default = self::JSON; } <file_sep>/examples/folder/3_delete_folder.php <?php use PDFfiller\OAuth2\Client\Provider\Folder; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $folder = Folder::one($provider, 23); $e = $folder->remove(); dd($e); <file_sep>/src/FillRequestAdditionalDocument.php <?php namespace PDFfiller\OAuth2\Client\Provider; /** * Class FillRequestAdditionalDocument * @package PDFfiller\OAuth2\Client\DTO * * @property string $name * @property string $filename * @property string $ip * @property int $date_created */ class FillRequestAdditionalDocument extends AdditionalDocument { protected static $entityUri = 'fillable_forms'; /** * @inheritdoc */ protected function getResourceIdentifier() { return 'filled_forms'; } } <file_sep>/examples/token/5_delete_token.php <?php use PDFfiller\OAuth2\Client\Provider\Token; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $token = Token::one($provider, 3329); $e = $token->remove(); dd($e); <file_sep>/src/DTO/FillableField.php <?php namespace PDFfiller\OAuth2\Client\Provider\DTO; use PDFfiller\OAuth2\Client\Provider\Core\AbstractObject; use PDFfiller\OAuth2\Client\Provider\Core\ListObject; /** * Class FillableField * @package PDFfiller\OAuth2\Client\Provider * * @property string $name * @property string $type * @property string $format * @property mixed $initial * @property boolean $required * @property string $maxChars * @property string $maxLines * @property ListObject $list * @property bool $allowCustomText * @property string $value * @property string $label * @property string $radioGroup * @property bool $fillable */ class FillableField extends AbstractObject { /** @var array */ protected $attributes = [ 'name', 'type', 'format', 'initial', 'required', 'maxChars', 'maxLines', 'list', 'radioGroup', 'allowCustomText', 'value', 'label', 'fillable', ]; protected $casts = [ 'list' => 'list', 'allowCustomText' => 'bool', 'fillable' => 'bool', ]; } <file_sep>/src/Contracts/Async.php <?php namespace PDFfiller\OAuth2\Client\Provider\Contracts; /** * Interface async * @package PDFfiller\OAuth2\Client\Provider\Contracts */ interface Async { const HTTP_STATUS_CODE_READY = 200; const READY = true; const NOT_READY = false; public function isReady(): bool; } <file_sep>/src/Enums/FillRequestNotifications.php <?php namespace PDFfiller\OAuth2\Client\Provider\Enums; use PDFfiller\OAuth2\Client\Provider\Core\Enum; /** * Class FillRequestNotifications * @package PDFfiller\OAuth2\Client\Provider\Enums */ class FillRequestNotifications extends Enum { const __default = self::DISABLED; const DISABLED = 'disabled'; const ENABLED = 'enabled'; const WITH_PDF = 'with_pdf'; }<file_sep>/src/DTO/NotificationEmail.php <?php namespace PDFfiller\OAuth2\Client\Provider\DTO; use PDFfiller\OAuth2\Client\Provider\Core\AbstractObject; /** * Class NotificationEmails * @package PDFfiller\OAuth2\Client\DTO * * @property string $name * @property string $email */ class NotificationEmail extends AbstractObject { /** @var array */ protected $attributes = [ 'name', 'email' ]; } <file_sep>/src/Exceptions/InvalidRequestException.php <?php namespace PDFfiller\OAuth2\Client\Provider\Exceptions; use PDFfiller\OAuth2\Client\Provider\Core\Exception; /** * Class InvalidRequestException * Handle invalid request type exception. * @package PDFfiller\OAuth2\Client\Provider\Exceptions */ class InvalidRequestException extends Exception {} <file_sep>/src/Enums/SignatureRequestMethod.php <?php namespace PDFfiller\OAuth2\Client\Provider\Enums; use PDFfiller\OAuth2\Client\Provider\Core\Enum; /** * Class SignatureRequestMethod * @package PDFfiller\OAuth2\Client\Provider\Core */ class SignatureRequestMethod extends Enum { const SEND_TO_GROUP = 'sendtogroup'; const SEND_TO_EACH = 'sendtoeach'; } <file_sep>/examples/folder/2_get_folder_info.php <?php use PDFfiller\OAuth2\Client\Provider\Folder; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $e = Folder::one($provider, 43434); dd($e); <file_sep>/examples/fillable_form/12_fillable_forms_additional_documents.php <?php use PDFfiller\OAuth2\Client\Provider\FilledForm; use PDFfiller\OAuth2\Client\Provider\Core\Job; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $filledForm = new FilledForm($provider, 219116971, ['filled_form_id' => 1167457]); // Getting the list of additional documents //$list = $filledForm->additionalDocuments(); //dd($list->toArray()); // Getting the additional documents by ID //$document = $filledForm->additionalDocument(109758); //dd($document); // Downloading the additional documents by ID //$document = $filledForm->additionalDocument(109758); //dd($document->download()); $filledFormAsync = new Job($filledForm); $filledFormAsync->downloadAdditionalDocuments(); while (!$filledFormAsync->isReady()) { sleep(2); } dd($filledFormAsync); <file_sep>/examples/fillable_form/1_get_fillable_forms_list.php <?php use PDFfiller\OAuth2\Client\Provider\FillableForm; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $fillRequest = FillableForm::all($provider); dd($fillRequest->toArray()); <file_sep>/src/Template.php <?php namespace PDFfiller\OAuth2\Client\Provider; use PDFfiller\OAuth2\Client\Provider\Core\Model; use PDFfiller\OAuth2\Client\Provider\Contracts\Uploadable; /** * Class Document * @package PDFfiller\OAuth2\Client\Provider * @property string $name * @property string $type * @property string $created * @property array $folder */ class Template extends Model implements Uploadable { const DOWNLOAD = 'download'; const DOWNLOAD_SIGNATURES = 'download_signatures'; const FILLED_DOCUMENTS = 'filled_documents'; const ORIGINAL_DOCUMENT = 'original_document'; const META = 'meta'; const WATERMARK = 'watermark'; const VALUES = 'values'; const FIELDS = 'fields'; const TYPE_CHECKBOX = 'checkmark'; /** * Return template content * @param $provider * @param $templateId * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public static function download($provider, $templateId) { return static::query($provider, [$templateId, self::DOWNLOAD]); } /** * Return zip-archive of template signatures * @param $provider * @param $templateId * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public static function downloadSignatures($provider, $templateId) { return static::query($provider, [$templateId, self::DOWNLOAD_SIGNATURES]); } /** * Return zip-archive of template signatures * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public function getDocumentSignatures() { return self::downloadSignatures($this->client, $this->id); } /** * Return template content * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public function getContent() { return self::download($this->client, $this->id); } /** * Create link to edit a specific template * @param array $params * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public function createConstructor(array $params) { $url = self::resolveFullUrl([$this->id, 'constructor']); $options = [ 'json' => $params, ]; return static::post($this->client, $url, $options); } /** * Retrieve a list of url's and hash's for a specific template * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public function getConstructorList() { return static::query($this->client, [$this->id, 'constructor']); } /** * Removing one (if hash is specified) or all shared link('s) to template * @param null $hash * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public function deleteConstructor($hash = null) { $url = self::resolveFullUrl([$this->id, 'constructor']); if (isset($hash)) { $url = self::resolveFullUrl([$this->id, 'constructor', $hash]); } return static::delete($this->client, $url); } /** * Fill template with named fields * @param array $fields * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public function fill($fields = []) { $url = self::resolveFullUrl([$this->id]); if(isset($this->properties['fillable_fields'])) { $fields = $this->properties['fillable_fields']; } foreach ($fields as $index => $field) { if (!is_array($field)) { continue; } unset($fields[$index]); if (!isset($field['name']) || !isset($field['value'])) { continue; } $name = $field['name']; $value = $field['value']; $type = isset($field['type']) ? $field['type'] : ''; if ($type === self::TYPE_CHECKBOX) { $value = intval(boolval($value)); } $fields[$name] = $value; } return static::post($this->client, $url, [ 'json' => [ 'fillable_fields' => $fields ] ]); } /** * Get all fields from template * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public function fields() { return static::query($this->client, [$this->id, self::FIELDS]); } /** * Get all filled documents from template * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public function getFilledDocument() { return static::query($this->client, [$this->id, self::FILLED_DOCUMENTS]); } /** * Return original document * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public function getOriginalDocument() { return self::downloadOriginalDocument($this->client, $this->id); } /** * Download original document * @param $provider * @param $templateId * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public function downloadOriginalDocument($provider, $templateId) { return static::query($provider, [$templateId, self::ORIGINAL_DOCUMENT]); } /** * Get template meta * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public function meta() { return static::query($this->client, [$this->id, self::META]); } /** * Get template meta * @param $watermarkText * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public function watermark($watermarkText) { $url = self::resolveFullUrl([$this->id, self::WATERMARK], ['text' => $watermarkText]); return static::post($this->client, $url); } } <file_sep>/src/Exceptions/JobAlreadyRunningException.php <?php namespace PDFfiller\OAuth2\Client\Provider\Exceptions; use PDFfiller\OAuth2\Client\Provider\Core\Exception; /** * Class JobAlreadyRunningException * @package PDFfiller\OAuth2\Client\Provider\Exceptions */ class JobAlreadyRunningException extends Exception {} <file_sep>/src/Exceptions/InvalidBodySourceException.php <?php namespace PDFfiller\OAuth2\Client\Provider\Exceptions; use PDFfiller\OAuth2\Client\Provider\Core\Exception; /** * Class InvalidBodySourceException * Handle case with multiple request body sources. * @package PDFfiller\OAuth2\Client\Provider\Exceptions */ class InvalidBodySourceException extends Exception {} <file_sep>/src/DTO/FillableFieldsList.php <?php namespace PDFfiller\OAuth2\Client\Provider\DTO; use PDFfiller\OAuth2\Client\Provider\Core\ListObject; use Closure; use InvalidArgumentException; class FillableFieldsList extends ListObject { /** * FillableFieldsList constructor. * @param array $items */ public function __construct($items = []) { $fields = []; foreach ($items as $ndx => $item) { if ($item instanceof FillableField) { $fields[] = $item; continue; } if (!is_array($item)) { $item = [ 'name' => $ndx, 'value' => (string)$item, ]; } $fields[] = new FillableField($item); } parent::__construct($fields); } /** * Returns the fields names in simple array * @return array */ private function getFields() { $fields = []; foreach ($this->items as $name => $field) { if (is_array($field) && isset($field['name'])) { $fields[] = $field['name']; } else if ($field instanceof FillableField){ $fields[] = $field->name; } else if (is_string($name)){ $fields[] = $name; } else { $fields[] = ''; } } return $fields; } /** * @inheritdoc */ public function offsetExists($offset) { $fields = $this->getFields(); return in_array($offset, $fields); } /** * @inheritdoc */ public function offsetGet($offset) { $fields = array_flip($this->getFields()); if (!isset($fields[$offset])) { return null; } $key = $fields[$offset]; return parent::offsetGet($key); } /** * @inheritdoc */ public function offsetSet($offset, $value) { if ($value instanceof FillableField) { $offset = !is_null($value->name) ? $value->name : $offset; } else if (is_array($value)) { $value = new FillableField($value); } else if (is_scalar($value)) { $value = new FillableField(['name' => $offset, 'value' => $value]); } if (! $value instanceof FillableField) { throw new InvalidArgumentException('The value must be scalar, array or FillableField'); } if (is_null($value->name) && !is_null($offset)) { $value->name = $offset; } $fields = array_flip($this->getFields()); if (!isset($fields[$offset]) || is_null($offset)) { $this->items[] = $value; return true; } $key = $fields[$offset]; $this->items[$key] = $value; return true; } /** * @inheritdoc */ public function offsetUnset($offset) { $fields = array_flip($this->getFields()); $key = isset($fields[$offset]) ? $fields[$offset] : $offset; parent::offsetUnset($key); } /** * Walks through the list and calls the closure on each field that can be filled. * * @param Closure $closure */ public function eachFillable(Closure $closure) { /** @var FillableField $item */ foreach ($this->items as $item) { if ($item->fillable) { $closure($item); } } } /** * Returns a new list containing only fields that can be filled * * @return FillableFieldsList */ public function getOnlyFillable() { $list = []; foreach ($this->items as $item) { if ($item->fillable) { $list[] = $item; } } return new static($list); } } <file_sep>/examples/callback/5_delete_callback.php <?php use PDFfiller\OAuth2\Client\Provider\Callback; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $e = Callback::deleteOne($provider, 34545); dd($e); <file_sep>/src/Enums/FillRequestStatus.php <?php namespace PDFfiller\OAuth2\Client\Provider\Enums; use PDFfiller\OAuth2\Client\Provider\Core\Enum; /** * Class FillRequestStatus * @package PDFfiller\OAuth2\Client\Provider\Core */ class FillRequestStatus extends Enum { const STATUS_PUBLIC = 'public'; const STATUS_PRIVATE = 'private'; } <file_sep>/examples/application/2_create_application.php <?php use PDFfiller\OAuth2\Client\Provider\Application; use \PDFfiller\OAuth2\Client\Provider\Exceptions\ResponseException; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $application = new Application($provider); $application->name = 'App name'; $application->description = 'Some application description'; $application->domain = 'http://some.domain.com/callback'; $application->embedded_domain = 'http://some.domain.com'; $application->all_domains = false; try { $response = $application->save(); dd($response); } catch (ResponseException $e) { dd($e->getMessage()); } <file_sep>/src/Contracts/Arrayable.php <?php namespace PDFfiller\OAuth2\Client\Provider\Contracts; /** * Interface Arrayable * @package PDFfiller\OAuth2\Client\Provider\Contracts */ interface Arrayable { /** * Returns array representation of given object * * @return array */ public function toArray(): array ; } <file_sep>/README.md # PDFfiller PHP Client [![Join the chat at https://gitter.im/pdffiller/pdffiller-php-api-client](https://badges.gitter.im/pdffiller/pdffiller-php-api-client.svg)](https://gitter.im/pdffiller/pdffiller-php-api-client?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [PDFfiller API](https://api.pdffiller.com) You can sign up for the API [here](https://www.pdffiller.com/en/developers#tab-pricing) ## System Requirements * PHP >= 7.0 but the latest stable version of PHP is recommended; * `mbstring` extension; * `intl` extension; ## Installation The library is available on Packagist and can be installed using Composer. This is done by running the following command on a composer installed box: ``` $ composer require pdffiller/pdffiller-php-api-client ``` Most modern frameworks include Composer out of the box. However, please ensure that the following file is included: ````php // Include the Composer autoloader require 'vendor/autoload.php'; ```` ### Troubleshooting If you have the following error: ``` [RuntimeException] Could not load package pdffiller/pdffiller-php-api-client in http://packagi st.org: [UnexpectedValueException] Could not parse version constraint ^5.2: Invalid version string "^5.2" [UnexpectedValueException] Could not parse version constraint ^5.2: Invalid version string "^5.2" ``` Try running ``` composer self-update ``` Also you might encounter the following: ``` Warning: require_once(../../vendor/autoload.php): failed to open stream: No such file or directory ``` This issue is easily fixed by installing composer dependencies: ``` composer install ``` ### Quick getting started steps Install required libraries using composer ``` cd pdffiller-php-api-client/ composer install ``` Edit `.env` file in examples directory setting client_id, client_secret, username and password (for authorization via `password_grant`) ``` cd examples/ cp .env.example .env vi .env ``` Run any example ``` cd signature_request/ php 1_get_signature_request_list.php ``` ## Authentication Access tokens automatically initialize when they’re successfully retrieved from the given user's credentials (after PDFfiller\OAuth2\Client\Provider\PDFfiller::getAccessToken($grant_type, $options) method), according to the example below: ````php <?php require_once __DIR__.'/vendor/autoload.php'; use \PDFfiller\OAuth2\Client\Provider\Enums\GrantType; use \PDFfiller\OAuth2\Client\Provider\PDFfiller; $oauthParams = [ 'clientId' => 'YOUR_CLIENT_ID', 'clientSecret' => 'YOUR_CLIENT_SECRET', 'urlAccessToken' => 'https://api.pdffiller.com/v2/oauth/token', 'urlApiDomain' => 'https://api.pdffiller.com/v2/' ]; $passwordGrantCredentials = [ 'username' => '<EMAIL>', 'password' => '<PASSWORD>' ]; /** @var \PDFfiller\OAuth2\Client\Provider\PDFfiller $provider */ $provider = new PDFfiller($oauthParams); $accessToken = $provider->getAccessToken(GrantType::PASSWORD_GRANT, $passwordGrantCredentials); print_r($accessToken); ```` When your authorization has been completed successfully you can use the provider for retrieving, creating, updating or deleting information from your profile. ## Usage Use a static method to retrieve a list of all applications: `PDFfiller\OAuth2\Client\Provider\Core\Model::all(PDFfiller $provider)` ````php $list = Application::all($provider); print_r($list); ```` For retrieving information about one application, call static: `PDFfiller\OAuth2\Client\Provider\Core\Model::one(PDFfiller $provider, $appClientId)` ````php $application = Application::one($provider, 'app_client_id'); print_r($application); ```` If you want to create a new application, you must create a new Application object with the necessary information and save it using the following method: `PDFfiller\OAuth2\Client\Provider\Core\Model::save()` ````php $application = new Application($provider); $application->name = 'App name'; $application->description = 'Some application description'; $application->domain = 'http://some.domain.com'; print_r($application->save()); ```` If you want to update an instance, you must retrieve an Application object and save it by using the following method: `PDFfiller\OAuth2\Client\Provider\Core\Model::save()` ````php $application = Application::one($provider, 'app_client_id'); $application->name = 'Updated App name'; $application->description = 'Some changed application description'; $result = $application->save(); print_r($result); ```` Updating information is easy by using: `PDFfiller\OAuth2\Client\Provider\Core\Model::save()` method. If you wish to remove an application, use: `PDFfiller\OAuth2\Client\Provider\Core\Model::remove()` method ````php $application = Application::one($provider, 'app_client_id'); $result = $application->remove(); print_r($result); ```` All examples with other endpoints are available in the [examples](https://github.com/pdffiller/pdffiller-php-api-client/tree/master/examples) folder ## Support If you have any problems feel free to contact us: * On our issues page https://github.com/pdffiller/pdffiller-php-api-client/issues * Via chat or phone at our tech site http://developers.pdffiller.com * Join our Gitter chat room for technical advice https://gitter.im/pdffiller/pdffiller-php-api-client ## License This software is licensed under the following MIT [license](https://github.com/pdffiller/pdffiller-php-api-client/blob/3.0.0/LICENSE) ## Author API Team (<EMAIL>) <file_sep>/src/DTO/EmbeddedClient.php <?php namespace PDFfiller\OAuth2\Client\Provider\DTO; use PDFfiller\OAuth2\Client\Provider\Core\AbstractObject; /** * Class FieldsAccess * @package PDFfiller\OAuth2\Client\DTO * * @property string $domain * @property bool $allow_all_domains */ class EmbeddedClient extends AbstractObject { /** @var array */ protected $casts = [ 'allow_all_domains' => 'bool', ]; /** @var array */ protected $attributes = [ 'domain', 'allow_all_domains' ]; } <file_sep>/examples/application/5_delete_application.php <?php use PDFfiller\OAuth2\Client\Provider\Application; use \PDFfiller\OAuth2\Client\Provider\Exceptions\ResponseException; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; try { $application = Application::one($provider, 'a5fefwe7bef001ce6'); $response = $application->remove(); dd($response); } catch (ResponseException $e) { dd($e->getMessage()); } <file_sep>/src/Enums/DocumentAccess.php <?php namespace PDFfiller\OAuth2\Client\Provider\Enums; use PDFfiller\OAuth2\Client\Provider\Core\Enum; /** * Class FillRequestAccess * @package PDFfiller\OAuth2\Client\Provider\Core */ class DocumentAccess extends Enum { const ACCESS_FULL = 'full'; const ACCESS_SIGNATURE = 'signature'; } <file_sep>/examples/signature_request/9_create_signature_request_recipient.php <?php use PDFfiller\OAuth2\Client\Provider\SignatureRequestRecipient; use PDFfiller\OAuth2\Client\Provider\SignatureRequest; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; //creating recipient by the signature request $signatureRequest = SignatureRequest::one($provider, 45435); $recipient = $signatureRequest->createRecipient(); //creating recipient as independent instance //$recipient = new SignatureRequestRecipient($provider, 334721); //filling recipient fields $recipient->email = '<EMAIL>'; $recipient->name = '<NAME>'; $recipient->access = 'full'; $recipient->require_photo = false; $recipient->message_subject = 'Email new subject'; $recipient->message_text = 'Hi, its a new message'; $recipient->additional_documents = []; $recipient->order = 1; //saving as independent instance $e = $signatureRequest->addRecipient($recipient); dd($e->toArray(), $signatureRequest->recipients, $e == $recipient); <file_sep>/examples/custom_logo/4_get_logo.php <?php use PDFfiller\OAuth2\Client\Provider\CustomLogo; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $e = CustomLogo::one($provider, 4534); dd($e); <file_sep>/src/CustomLogo.php <?php namespace PDFfiller\OAuth2\Client\Provider; use PDFfiller\OAuth2\Client\Provider\Core\Exception; use PDFfiller\OAuth2\Client\Provider\Core\Model; use PDFfiller\OAuth2\Client\Provider\Contracts\Uploadable; /** * Class CustomLogo * @package PDFfiller\OAuth2\Client\Provider * * @property int $id * @property int $user_id * @property int $width * @property int $height * @property int $filesize */ class CustomLogo extends Model implements Uploadable { /** @var string */ protected static $entityUri = 'custom_branding/custom_logo'; /** * @inheritdoc */ protected function create($options = []) { throw new Exception("Can't create logo, use Uploader."); } /** * @inheritdoc */ protected function update($options = []) { throw new Exception("Can't update logo, delete old and upload new logo."); } /** * @inheritdoc */ public function save($options = []) { throw new Exception("Can't save logo, use Uploader."); } } <file_sep>/examples/fillable_form/3_get_fillable_forms.php <?php use PDFfiller\OAuth2\Client\Provider\FillableForm; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $e = FillableForm::one($provider, 219116971); dd($e); <file_sep>/examples/signature_request/7_get_signature_request_all_recipients.php <?php use PDFfiller\OAuth2\Client\Provider\SignatureRequest; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; //$recipient = SignatureRequest::one($provider, 345345)->getRecipients(); $recipient = SignatureRequest::recipients($provider, 345345); dd($recipient->toArray()); <file_sep>/examples/fillable_form/4_update_fillable_forms.php <?php use PDFfiller\OAuth2\Client\Provider\FillableForm; use PDFfiller\OAuth2\Client\Provider\DTO\AdditionalDocument; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $fillableFormEntity = FillableForm::one($provider, 165825280); //dd($fillableFormEntity->toArray()); $fillableFormEntity->custom_message = "Updated custom message for example"; //$fillableFormEntity->additional_documents[] = ['add_doc2']; $e = $fillableFormEntity->save(); dd($e); <file_sep>/src/Exceptions/ResponseException.php <?php namespace PDFfiller\OAuth2\Client\Provider\Exceptions; /** * Class ResponseException * Handle response errors. * @package PDFfiller\OAuth2\Client\Provider\Exceptions */ class ResponseException extends ErrorsException { /** * @inheritdoc */ public function getDefaultMessage() { $string = ""; foreach ($this->errors as $error) { $message = isset($error['message']) ? $error['message'] : $error; $id = isset($error['id']) ? ". ID: " . $error['id'] : ""; $string .= trim($message, '.') . $id . '. '; } return parent::getDefaultMessage() . '.' . PHP_EOL . $string; } } <file_sep>/examples/custom_logo/5_delete_logo.php <?php use PDFfiller\OAuth2\Client\Provider\CustomLogo; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $e = CustomLogo::deleteOne($provider, 34543); dd($e); <file_sep>/examples/auth/authorization_code_grant.php <?php require_once __DIR__.'/../bootstrap/init.php'; use PDFfiller\OAuth2\Client\Provider\Enums\GrantType; use PDFfiller\OAuth2\Client\Provider\PDFfiller; $code = 'PLACE_YOUR_CODE_HERE'; $provider = new PDFfiller([ 'clientId' => getenv('CLIENT_ID'), 'clientSecret' => getenv('CLIENT_SECRET'), 'urlApiDomain' => getenv('URL_API_DOMAIN'), 'urlAccessToken' => getenv('URL_ACCESS_TOKEN'), 'redirectUri' => getenv('REDIRECT_URI'), ]); $provider->getAccessToken(new GrantType(GrantType::AUTHORIZATION_CODE_GRANT), [ 'code' => urldecode($code), ]); dd($provider->queryApiCall('test')); <file_sep>/examples/signature_request/10_remind_signature_request_recipient.php <?php use PDFfiller\OAuth2\Client\Provider\SignatureRequest; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; //$signatureRequest = SignatureRequest::one($provider, 337730); //$recipient = $signatureRequest->getRecipient(554689); $recipients = SignatureRequest::recipients($provider, 111); $recipient = $recipients[1258405]; $e = $recipient->remind(); dd($e); <file_sep>/examples/templates/7_download_template.php <?php use PDFfiller\OAuth2\Client\Provider\Template; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $contents = Template::download($provider, 216865300); dd($contents); <file_sep>/src/Exceptions/MethodNotSupportedException.php <?php namespace PDFfiller\OAuth2\Client\Provider\Exceptions; use PDFfiller\OAuth2\Client\Provider\Core\Exception; /** * Class MethodNotSupportedException * @package PDFfiller\OAuth2\Client\Provider\Exceptions */ class MethodNotSupportedException extends Exception { } <file_sep>/examples/templates/18_create_watermark.php <?php use PDFfiller\OAuth2\Client\Provider\Template; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $template = new Template($provider,['id'=> 216865300]); $templateWithWatermark = $template->watermark('Watermark text'); dd($templateWithWatermark); <file_sep>/src/Contracts/Uploadable.php <?php namespace PDFfiller\OAuth2\Client\Provider\Contracts; /** * Interface Uploadable * Describes behavior of entities that can be uploaded by Uploader. * @package PDFfiller\OAuth2\Client\Provider\Core * */ interface Uploadable { } <file_sep>/examples/token/4_update_token.php <?php use PDFfiller\OAuth2\Client\Provider\Token; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $token = Token::one($provider, 3329); $token->data['key3'] = 'data30'; dd($token->save()); <file_sep>/src/Exceptions/InvalidQueryException.php <?php namespace PDFfiller\OAuth2\Client\Provider\Exceptions; use PDFfiller\OAuth2\Client\Provider\Core\Exception; /** * Class InvalidQueryException * Handle invalid query exception. * @package PDFfiller\OAuth2\Client\Provider\Exceptions */ class InvalidQueryException extends Exception {} <file_sep>/examples/signature_request/5_get_signature_request_certificate.php <?php use PDFfiller\OAuth2\Client\Provider\SignatureRequest; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; //$e = SignatureRequest::one($provider, 129121)->certificate(); $sr = new SignatureRequest($provider, ['id' => 5454]); $e = $sr->certificate(); dd($e); <file_sep>/src/AdditionalDocument.php <?php namespace PDFfiller\OAuth2\Client\Provider; use PDFfiller\OAuth2\Client\Provider\Contracts\AdditionalDocuments; use PDFfiller\OAuth2\Client\Provider\Core\Model; use PDFfiller\OAuth2\Client\Provider\Exceptions\MethodNotSupportedException; /** * Class AdditionalDocument * @package PDFfiller\OAuth2\Client\Provider * * @property string $name * @property string $document_request_notification * @property string $filename * @property string $ip * @property int $date_created */ abstract class AdditionalDocument extends Model { /** * FillRequestId or SignatureRequestId * @var int|null */ protected $requestId = null; /** * Recipient for SignatureRequest and FilledForm for FillRequest * @var int|null */ protected $resourceId = null; /** * AdditionalDocument constructor. * @param PDFfiller $provider * @param int $requestId * @param int $resourceId * @param array $properties * @throws \ReflectionException */ public function __construct(PDFfiller $provider, int $requestId, int $resourceId, array $properties = []) { $this->requestId = $requestId; $this->resourceId = $resourceId; parent::__construct($provider, $properties); static::setEntityUri(implode('/', [ static::getEntityUri(), $this->requestId, $this->getResourceIdentifier(), $this->resourceId, AdditionalDocuments::ADDITIONAL_DOCUMENTS, ])); } /** * @param array $parameters * @return mixed * @throws Exceptions\InvalidQueryException * @throws Exceptions\InvalidRequestException */ public function download($parameters = []) { return self::query( $this->client, [ $this->{$this->primaryKey}, AdditionalDocuments::ADDITIONAL_DOCUMENTS_DOWNLOAD, ], $parameters ); } /** * @inheritdoc */ public static function one(PDFfiller $provider, $id) { throw new MethodNotSupportedException("Can't get document, see FillRequestForm and SignatureRequestRecipient classes"); } /** * @inheritdoc */ public static function all(PDFfiller $provider, array $queryParams = []) { throw new MethodNotSupportedException("Can't get documents, see FillRequestForm and SignatureRequestRecipient classes"); } /** * Returns the resource identifier * @return string */ protected abstract function getResourceIdentifier(); } <file_sep>/src/Contracts/Stringable.php <?php namespace PDFfiller\OAuth2\Client\Provider\Contracts; /** * Interface Stringable * @package PDFfiller\OAuth2\Client\Provider\Contracts */ interface Stringable { /** * Returns string representation of given object * * @return string */ public function __toString(); } <file_sep>/examples/custom_logo/1_get_logos_list.php <?php use PDFfiller\OAuth2\Client\Provider\CustomLogo; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $e = CustomLogo::all($provider); dd($e); <file_sep>/examples/fillable_form/5_delete_fillable_forms.php <?php use PDFfiller\OAuth2\Client\Provider\FillableForm; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $e = FillableForm::deleteOne($provider, 232323); dd($e); <file_sep>/examples/token/1_get_tokens_list.php <?php use PDFfiller\OAuth2\Client\Provider\Token; $provider = require_once __DIR__ . '/../bootstrap/initWithFabric.php'; $tokenEntity = new \PDFfiller\OAuth2\Client\Provider\Token($provider); $e = Token::all($provider); dd($e);
96e434cc9c86518ad75d5d8b15ce08d4eaff15eb
[ "Markdown", "PHP", "Shell" ]
115
PHP
pdffiller/pdffiller-php-api-client
281532a984d798055e29a4fa6c4587d5138b4bfd
586ff9d040af8cafa6aba267259f847b42d73d93
refs/heads/master
<file_sep>import chalk from 'chalk'; import * as fs from 'fs'; export function updatePackageConfig(path: string, name: string, verbose: boolean): void { const file: string = `${path}/package.json`; const contents: string = fs.readFileSync(file, 'utf8'); const modified: string = contents.replace(/{{ name }}/g, name); if (verbose) { console.log(chalk.green('Updated package.json')); } fs.writeFileSync(file, modified); } <file_sep># Boilerplate I use this project as a boilerplate for projects and libraries that use TypeScript. To start a project use: `node ./script/setup.js p <project_name>` To start a library use: `node ./script/setup.js l <library_name>` Start a project/lib by doing: - `mkdir <project_name>` - `cd <project_name>` - `git clone https://github.com/joppe/boilerplate.git .` - `node ./script/setup.js l <project_name>` - `rm -rf script` - `rm -rf .git` - ... do the steps to create a new project described as on github.com <file_sep>import chalk from 'chalk'; import * as fs from 'fs'; export function createDirs(root: string, dirs: Array<string>, verbose: boolean): void { dirs.forEach((dir: string): void => { const path: string = `${root}/${dir}`; if (!fs.existsSync(path)) { if (verbose) { console.log(chalk.magenta(`Create dir: ${chalk.bold(path)}`)); } fs.mkdirSync(path); } }); } <file_sep>import chalk from 'chalk'; import { Config } from '../common/Config'; import { copyFiles } from '../common/copy-files'; import { createDirs } from '../common/create-dirs'; import { initializeGit } from '../common/initialize-git'; import { installPackages } from '../common/install-packages'; import { updatePackageConfig } from '../common/update-package-config'; const ASSET_PATH: string = `${__dirname}/../../assets/project`; export function createProject(config: Config, path: string, verbose: boolean): void { if (verbose) { console.log(chalk.green(`Create project "${config.name}"`)); } createDirs( path, [ 'public', 'sass', 'src', 'test', 'test/unit' ], verbose ); copyFiles( `${ASSET_PATH}/`, `${path}/`, [ ['editorconfig', '.editorconfig'], ['gitignore', '.gitignore'], ['npmrc', '.npmrc'], ['karma.conf.js'], ['package.json'], ['tsconfig.json'], ['tslint.json'], ['webpack.config.js'] ], verbose ); copyFiles( `${ASSET_PATH}/`, `${path}/public/`, [ ['index.html'] ], verbose ); copyFiles( `${ASSET_PATH}/sass/`, `${path}/sass/`, [ ['main.jscss'], ['main.scss'] ], verbose ); copyFiles( `${ASSET_PATH}/test/`, `${path}/test/`, [ ['tslint.json'] ], verbose ); updatePackageConfig(path, config.name, verbose); installPackages(path, verbose); if (config.git) { initializeGit(path, verbose); } } <file_sep>import chalk from 'chalk'; import { copyFile } from './copy-file'; export function copyFiles(sourcePath: string, targetPath: string, files: Array<Array<string>>, verbose: boolean): void { files.forEach((names: Array<string>): void => { if (names.length === 1) { copyFile(sourcePath, targetPath, names[0], undefined, verbose); } else if (names.length === 2) { copyFile(sourcePath, targetPath, names[0], names[1], verbose); } else { console.log(chalk.bold.red('Cannot copy file, illegal config')); } }); } <file_sep>import chalk from 'chalk'; import * as program from 'commander'; import * as fs from 'fs'; import * as inquirer from 'inquirer'; import * as path from 'path'; import { Config, TYPE_LIBRARY, TYPE_PROJECT } from './common/Config'; import { createLibrary } from './library/create-library'; import { createProject } from './project/create-project'; let root: string; const version: string = JSON.parse( fs.readFileSync( path.resolve(__dirname, '../package.json'), 'utf8' ) ).version; program .version(version) .arguments('<dir>') .action((dir: string): void => { root = dir; }) .option('-v, --verbose', 'Provide extra feedback') .parse(process.argv); if (root === undefined) { console.log(chalk.bold.red(`Please provide a path`)); } else if (!fs.existsSync(root)) { console.log(chalk.bold.red(`Could not find given path "${root}"`)); } else { // tslint:disable-next-line inquirer.prompt( [ { type: 'input', message: 'Name', name: 'name', validate: (name: string): boolean | string => { if (name.trim() !== '') { return true; } return 'Please provide a name'; } }, { type: 'list', message: 'Type', name: 'type', choices: [ { name: 'Project' }, { name: 'Library' } ], default: 'Project' }, { type: 'confirm', message: 'Initialize Git', name: 'git', default: true } ] ) .then((answers: Config): void => { if (answers.type === TYPE_LIBRARY) { createLibrary(answers, root, program.verbose === true); } else if (answers.type === TYPE_PROJECT) { createProject(answers, root, program.verbose === true); } else { console.log(chalk.bold.red(`Unrecognized type: ${answers.type}`)); } }); } <file_sep>export const TYPE_LIBRARY: string = 'Library'; export const TYPE_PROJECT: string = 'Project'; export type Config = { name: string; type: 'Library' | 'Project'; git: boolean; }; <file_sep>import chalk from 'chalk'; import * as childProcess from 'child_process'; export function initializeGit(path: string, verbose: boolean): void { if (verbose) { console.log(chalk.green('Initialize Git')); } childProcess.exec(`cd ${path} && git init`, (error: childProcess.ExecException | null, stdout: string, stderr: string): void => { if (verbose) { console.log(chalk.gray(`${stdout}`)); console.log(chalk.yellow(`${stderr}`)); } if (error !== null) { console.log(chalk.bold.red(`Error while initializing Git: ${error}`)); } }); } <file_sep>import chalk from 'chalk'; import * as fs from 'fs'; export function copyFile(sourcePath: string, targetPath: string, file: string, renameTo: string | undefined, verbose: boolean): void { const from: string = `${sourcePath}${file}`; const to: string = `${targetPath}${renameTo !== undefined ? renameTo : file}`; if (verbose) { console.log(chalk.blue(`Copy file from: ${chalk.bold(from)} to: ${chalk.bold(to)}`)); } fs.copyFileSync(from, to); }
b0cba15c1162234ff826c535ef7406720a26a6ce
[ "Markdown", "TypeScript" ]
9
TypeScript
joppe/boilerplate
7fa975d73ed3aa7f48ff4b3a1964a3a3904cb217
f9c81aab6cdd65ce01a6b114a7ef74688294b49e
refs/heads/master
<file_sep><!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="user-scalable= no, width=device-width, initial-scale=1"> <link rel="stylesheet" href="estiloo.css"> <link rel="icon" href="pngegg.ico"> <title><NAME></title> </head> <body> <div id="contenedor"> <a name="INICIO"></a> <header><h1><u>¡BIENVENIDOS!</u></h1></header> <nav class= "navegacion" id="nav"> <ul class="menu"> <li><a href="#INICIO">INICIO</a></li> <li><a href="#soy-Ruben">¿QUIÉN SOY?</a></li> <li><a href="#xxx"> CONTACTAME </a></li> </ul></nav><br><br> <section id="Contenido"> <h1><NAME></h1> <img src="Foto.jpeg"> </section> <aside> <h1><b><u>Un poco sobre mi:</u></b></h1> <br> <br> <p>Mi nombre es Rubén, soy oriundo de la Provincia de Misiones , pero vivo actualmente en Buenos Aires, me estoy introduciendo en el mundo de la Programación, con conocimientos<br> en HTML, CSS y PHP. Realizo trabajos de maquetado web, frontend y back end.<br> Gracias por visitar mi sitio web.</p> <button><a name="soy-Ruben">¿QUIÉN SOY?</a></button></aside> <div class="contactame"> <a name="xxx"></a> <hr> <p>Podés enviar tu consulta via correo Electrónico, por llamada telefónica o simplemente por Whatsapp.</p> <h2><b>CONTACTAME</b></h2> <form action="enviar.php" method="POST" class="form_contact"> <input type="text" name="nombre" placeholder="<NAME>" required/><br> <input type="number" name="telefono" placeholder="NÚMERO DE TELÉFONO" required/><br> <input type="email" name="email" placeholder="<NAME>" required/><br> <input type="text" name="mensaje" placeholder="MENSAJE" required/><br> <button class="submit entry" onclick="Gracias()">Enviar</button> </form> </div><br><br><br> <iframe width="560" height="315" src="https://www.youtube.com/embed/uAY0Da2vlDE" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> <footer> <hr> <div class="contact"> <h3><b><u> INFORMACIÓN DE CONTACTO </u></b></h3><br> <p><b><u>Correo Electrónico:</u></b> <EMAIL> </p> <p><b><u>Teléfono:</u></b> 3764-534608</p> <p><a href="https://www.instagram.com/rubenbornet/" target="_blank"><img src="Ig.png" width="40px"></a></p> <button style="background-color:rgb(23, 23, 116);"><a href="#INICIO" style="color: white;">INICIO</a></button> </footer> </div> </body> </html><file_sep><?php session_start(); $conn = mysqli_connect( 'localhost', 'root', '', 'mi primer base de datos' ); if (isset($conn)){ echo "<h1>CONEXIÓN EXITOSA<h1/>"; } ?>
2d889f9d9ac67e6de591be3f602983961b090d58
[ "HTML", "PHP" ]
2
HTML
Ruben-a-bot/CV
7082772f4205d851b1844dd450ebb36a626f7670
359228e55675e08dbaa8e1c1254c48b64e9e0254
refs/heads/master
<file_sep>namespace NXHub.Constants { /// <summary> /// GUID 格式化参数 /// 注意: 所有格式化后的字符串均为小写, 如需转大写需要自行处理, 如: .ToUpper(); /// </summary> public class F_Guid { /// <summary> /// 无括号, 无连字符, 如: 102447989a344245b1ef9143f9b1e68a /// </summary> public const string N = nameof(N); /// <summary> /// 无括号, 有连字符, 如: 10244798-9a34-4245-b1ef-9143f9b1e68a /// </summary> public const string D = nameof(D); /// <summary> /// 花括号, 连字符, 如: {10244798-9a34-4245-b1ef-9143f9b1e68a} /// </summary> public const string B = nameof(B); /// <summary> /// 小括号, 连字符, 如: (10244798-9a34-4245-b1ef-9143f9b1e68a) /// </summary> public const string P = nameof(P); /// <summary> /// 六进制, 如: {0x10244798,0x9a34,0x4245,{0xb1,0xef,0x91,0x43,0xf9,0xb1,0xe6,0x8a}} /// </summary> public const string X = nameof(X); } } <file_sep>namespace NXHub.Constants { public partial class F_Date { /// <summary> /// 组合参数: 月中的某一天, 一位数的日期没有前导零 /// </summary> public const string d = nameof(d); /// <summary> /// 组合参数: 月中的某一天, 一位数的日期有一个前导零 /// </summary> public const string dd = nameof(dd); /// <summary> /// 组合参数: 周中某天的缩写名称 <see cref="AbbreviatedDayNames"/> /// </summary> public const string ddd = nameof(ddd); /// <summary> /// 组合参数: 周中某天的完整名称 <see cref="DayNames"/> /// </summary> public const string dddd = nameof(dddd); /// <summary> /// 组合参数: 月份数字, 一位数的月份没有前导零 /// </summary> public const string M = nameof(M); /// <summary> /// 组合参数: 月份数字, 一位数的月份有前导零 /// </summary> public const string MM = nameof(MM); /// <summary> /// 组合参数: 月份的缩写名称 <see cref="AbbreviatedMonthNames"/> /// </summary> public const string MMM = nameof(MMM); /// <summary> /// 组合参数: 月份的完整名称 <see cref="MonthNames"/> /// </summary> public const string MMMM = nameof(MMMM); /// <summary> /// 组合参数: 不包含纪元的年份, 如果不包含纪元的年份小于 10, 则显示不具有前导零的年份 /// </summary> public const string y = nameof(y); /// <summary> /// 组合参数: 不包含纪元的年份, 如果不包含纪元的年份小于 10, 则显示具有前导零的年份 /// </summary> public const string yy = nameof(yy); /// <summary> /// 组合参数: 包括纪元的四位数的年份 /// </summary> public const string yyyy = nameof(yyyy); /// <summary> /// 组合参数: 小时制的小时, 一位数的小时数没有前导零 /// </summary> public const string h = nameof(h); /// <summary> /// 组合参数: 12 小时制的小时, 一位数的小时数有前导零 /// </summary> public const string hh = nameof(hh); /// <summary> /// 组合参数: 24 小时制的小时, 一位数的小时数没有前导零 /// </summary> public const string H = nameof(H); /// <summary> /// 组合参数: 24 小时制的小时, 一位数的小时数有前导零 /// </summary> public const string HH = nameof(HH); /// <summary> /// 组合参数: 分钟, 一位数的分钟数没有前导零 /// </summary> public const string m = nameof(m); /// <summary> /// 组合参数: 分钟, 一位数的分钟数有一个前导零 /// </summary> public const string mm = nameof(mm); /// <summary> /// 组合参数: 秒, 一位数的秒数没有前导零 /// </summary> public const string s = nameof(s); /// <summary> /// 组合参数: 秒, 一位数的秒数有前导零 /// </summary> public const string ss = nameof(ss); /// <summary> /// 组合参数: 秒的小数精度为一位, 其余数字被截断 /// </summary> public const string f = nameof(f); /// <summary> /// 组合参数: 秒的小数精度为两位, 其余数字被截断 /// </summary> public const string ff = nameof(ff); /// <summary> /// 组合参数: 秒的小数精度为三位, 其余数字被截断 /// </summary> public const string fff = nameof(fff); /// <summary> /// 组合参数: 秒的小数精度为四位, 其余数字被截断 /// </summary> public const string ffff = nameof(ffff); /// <summary> /// 组合参数: 秒的小数精度为五位, 其余数字被截断 /// </summary> public const string fffff = nameof(fffff); /// <summary> /// 组合参数: 秒的小数精度为六位, 其余数字被截断 /// </summary> public const string ffffff = nameof(ffffff); /// <summary> /// 组合参数: 秒的小数精度为七位, 其余数字被截断 /// </summary> public const string fffffff = nameof(fffffff); /// <summary> /// 组合参数: AM/PM 指示项的第一个字符 /// </summary> public const string t = nameof(t); /// <summary> /// 组合参数: AM/PM 指示项 /// </summary> public const string tt = nameof(tt); /// <summary> /// 组合参数: 一位数的小时数没有前导零, 例如: 太平洋标准时间是 "-8" /// </summary> public const string z = nameof(z); /// <summary> /// 组合参数: 一位数的小时数有前导零, 例如: 太平洋标准时间是 "-08" /// </summary> public const string zz = nameof(zz); /// <summary> /// 组合参数: 一位数的小时数和分钟数有前导零, 例如: 太平洋标准时间是 "-08:00" /// </summary> public const string zzz = nameof(zzz); /// <summary> /// 默认时间分隔符 /// </summary> public const string TimeSeparator = ":"; /// <summary> /// 默认日期分隔符 /// </summary> public const string DateSeparator = "/"; } } <file_sep>namespace NXHub.Constants { public partial class F_Date { public enum AbbreviatedDayNames { /// <summary> /// 星期一 /// </summary> Mon, /// <summary> /// 星期二 /// </summary> Tue, /// <summary> /// 星期三 /// </summary> Wed, /// <summary> /// 星期四 /// </summary> Thu, /// <summary> /// 星期五 /// </summary> Fri, /// <summary> /// 星期六 /// </summary> Sat, /// <summary> /// 星期天 /// </summary> Sun, } public enum DayNames { /// <summary> /// 星期一 /// </summary> Monday, /// <summary> /// 星期二 /// </summary> Tuesday, /// <summary> /// 星期三 /// </summary> Wednesday, /// <summary> /// 星期四 /// </summary> Thursday, /// <summary> /// 星期五 /// </summary> Friday, /// <summary> /// 星期六 /// </summary> Saturday, /// <summary> /// 星期天 /// </summary> Sunday, } public enum AbbreviatedMonthNames { /// <summary> /// 一月 /// </summary> Jan, /// <summary> /// 二月 /// </summary> Feb, /// <summary> /// 三月 /// </summary> Mar, /// <summary> /// 四月 /// </summary> Apr, /// <summary> /// 五月 /// </summary> May, /// <summary> /// 六月 /// </summary> Jun, /// <summary> /// 七月 /// </summary> Jul, /// <summary> /// 八月 /// </summary> Aug, /// <summary> /// 九月 /// </summary> Sep, /// <summary> /// 十月 /// </summary> Oct, /// <summary> /// 十一月 /// </summary> Nov, /// <summary> /// 十二月 /// </summary> Dec, } public enum MonthNames { /// <summary> /// 一月 /// </summary> January, /// <summary> /// 二月 /// </summary> February, /// <summary> /// 三月 /// </summary> March, /// <summary> /// 四月 /// </summary> April, /// <summary> /// 五月 /// </summary> May, /// <summary> /// 六月 /// </summary> June, /// <summary> /// 七月 /// </summary> July, /// <summary> /// 八月 /// </summary> August, /// <summary> /// 九月 /// </summary> Septemper, /// <summary> /// 十月 /// </summary> October, /// <summary> /// 十一月 /// </summary> November, /// <summary> /// 十二月 /// </summary> December } } } <file_sep>namespace NXHub.Constants { public class C_Lang { /// <summary> /// 中文 - 简体 /// </summary> public const string zh_cn = nameof(zh_cn); /// <summary> /// 中文 - 台湾 /// </summary> public const string zh_tw = nameof(zh_tw); /// <summary> /// 中文 - 香港 /// </summary> public const string zh_hk = nameof(zh_hk); /// <summary> /// 中文 - 澳门 /// </summary> public const string zh_mo = nameof(zh_mo); /// <summary> /// 中文 - 新加坡 /// </summary> public const string zh_sg = nameof(zh_sg); /// <summary> /// 中文(单一化) /// </summary> public const string zh_chs = nameof(zh_chs); /// <summary> /// 中文(传统的) /// </summary> public const string zh_cht = nameof(zh_cht); /// <summary> /// 英语 /// </summary> public const string en = nameof(en); /// <summary> /// 英语 - 英国 /// </summary> public const string en_gb = nameof(en_gb); /// <summary> /// 英语 - 美国 /// </summary> public const string en_us = nameof(en_us); /// <summary> /// 英语 - 加拿大 /// </summary> public const string en_ca = nameof(en_ca); /// <summary> /// 英语 - 澳洲 /// </summary> public const string en_au = nameof(en_au); /// <summary> /// 英语 - 伯利兹 /// </summary> public const string en_bz = nameof(en_bz); /// <summary> /// 英语 - 加勒比海 /// </summary> public const string en_cb = nameof(en_cb); /// <summary> /// 英语 - 爱尔兰 /// </summary> public const string en_ie = nameof(en_ie); /// <summary> /// 英语 - 牙买加 /// </summary> public const string en_jm = nameof(en_jm); /// <summary> /// 英语 - 新西兰 /// </summary> public const string en_nz = nameof(en_nz); /// <summary> /// 英语 - 菲律宾共和国 /// </summary> public const string en_ph = nameof(en_ph); /// <summary> /// 英语 - 南非 /// </summary> public const string en_za = nameof(en_za); /// <summary> /// 英语 - 千里达托贝哥共和国 /// </summary> public const string en_tt = nameof(en_tt); /// <summary> /// 英语 - 津巴布韦 /// </summary> public const string en_zw = nameof(en_zw); /// <summary> /// 西班牙语 /// </summary> public const string es = nameof(es); /// <summary> /// 西班牙语 - 西班牙 /// </summary> public const string es_es = nameof(es_es); /// <summary> /// 西班牙语 - 阿根廷 /// </summary> public const string es_ar = nameof(es_ar); /// <summary> /// 西班牙语 - 玻利维亚 /// </summary> public const string es_bo = nameof(es_bo); /// <summary> /// 西班牙语 - 智利 /// </summary> public const string es_cl = nameof(es_cl); /// <summary> /// 西班牙语 - 哥伦比亚 /// </summary> public const string es_co = nameof(es_co); /// <summary> /// 西班牙语 - 哥斯达黎加 /// </summary> public const string es_cr = nameof(es_cr); /// <summary> /// 西班牙语 - 多米尼加共和国 /// </summary> public const string es_do = nameof(es_do); /// <summary> /// 西班牙语 - 厄瓜多尔 /// </summary> public const string es_ec = nameof(es_ec); /// <summary> /// 西班牙语 - 萨尔瓦多 /// </summary> public const string es_sv = nameof(es_sv); /// <summary> /// 西班牙语 - 危地马拉 /// </summary> public const string es_gt = nameof(es_gt); /// <summary> /// 西班牙语 - 洪都拉斯 /// </summary> public const string es_hn = nameof(es_hn); /// <summary> /// 西班牙语 - 墨西哥 /// </summary> public const string es_mx = nameof(es_mx); /// <summary> /// 西班牙语 - 尼加拉瓜 /// </summary> public const string es_ni = nameof(es_ni); /// <summary> /// 西班牙语 - 巴拿马 /// </summary> public const string es_pa = nameof(es_pa); /// <summary> /// 西班牙语 - 巴拉圭 /// </summary> public const string es_py = nameof(es_py); /// <summary> /// 西班牙语 - 秘鲁 /// </summary> public const string es_pe = nameof(es_pe); /// <summary> /// 西班牙语 - 波多黎各 /// </summary> public const string es_pr = nameof(es_pr); /// <summary> /// 西班牙语 - 乌拉圭 /// </summary> public const string es_uy = nameof(es_uy); /// <summary> /// 西班牙语 - 委内瑞拉 /// </summary> public const string es_ve = nameof(es_ve); /// <summary> /// 瑞典 /// </summary> public const string sv = nameof(sv); /// <summary> /// 瑞典 - 芬兰 /// </summary> public const string sv_fi = nameof(sv_fi); /// <summary> /// 瑞典 - 瑞典 /// </summary> public const string sv_se = nameof(sv_se); /// <summary> /// 越南语 /// </summary> public const string vi = nameof(vi); /// <summary> /// 越南语 - 越南 /// </summary> public const string vi_vn = nameof(vi_vn); /// <summary> /// 泰国语 /// </summary> public const string th = nameof(th); /// <summary> /// 泰国语 - 泰国 /// </summary> public const string th_th = nameof(th_th); /// <summary> /// 土耳其语 /// </summary> public const string tr = nameof(tr); /// <summary> /// 土耳其语 - 土耳其 /// </summary> public const string tr_tr = nameof(tr_tr); /// <summary> /// 乌克兰语 /// </summary> public const string uk = nameof(uk); /// <summary> /// 乌克兰语 - 乌克兰 /// </summary> public const string uk_ua = nameof(uk_ua); /// <summary> /// 蒙古 /// </summary> public const string mn = nameof(mn); /// <summary> /// 蒙古语 - 蒙古 /// </summary> public const string mn_mn = nameof(mn_mn); /// <summary> /// 挪威语 /// </summary> public const string no = nameof(no); /// <summary> /// 挪威语 (bokm?l) - 挪威 /// </summary> public const string nb_no = nameof(nb_no); /// <summary> /// 挪威 (nynorsk)- 挪威 /// </summary> public const string nn_no = nameof(nn_no); /// <summary> /// 波兰语 /// </summary> public const string pl = nameof(pl); /// <summary> /// 波兰语 - 波兰 /// </summary> public const string pl_pl = nameof(pl_pl); /// <summary> /// 俄语 /// </summary> public const string ru = nameof(ru); /// <summary> /// 俄语 - 俄国 /// </summary> public const string ru_ru = nameof(ru_ru); /// <summary> /// Tatar- 俄国 /// </summary> public const string tt_ru = nameof(tt_ru); /// <summary> /// 葡萄牙语 /// </summary> public const string pt = nameof(pt); /// <summary> /// 葡萄牙语 - 巴西 /// </summary> public const string pt_br = nameof(pt_br); /// <summary> /// 葡萄牙语 - 葡萄牙 /// </summary> public const string pt_pt = nameof(pt_pt); /// <summary> /// 匈牙利语 /// </summary> public const string hu = nameof(hu); /// <summary> /// 匈牙利语 - 匈牙利 /// </summary> public const string hu_hu = nameof(hu_hu); /// <summary> /// 冰岛语 /// </summary> public const string @is = "is"; /// <summary> /// 冰岛语 - 冰岛 /// </summary> public const string is_is = nameof(is_is); /// <summary> /// 德国语 /// </summary> public const string de = nameof(de); /// <summary> /// 德国语 - 奥地利 /// </summary> public const string de_at = nameof(de_at); /// <summary> /// 德语 - 德国 /// </summary> public const string de_de = nameof(de_de); /// <summary> /// 德语 - 列支敦士登 /// </summary> public const string de_li = nameof(de_li); /// <summary> /// 德语 - 卢森堡 /// </summary> public const string de_lu = nameof(de_lu); /// <summary> /// 德语 - 瑞士 /// </summary> public const string de_ch = nameof(de_ch); /// <summary> /// 芬兰语 /// </summary> public const string fi = nameof(fi); /// <summary> /// 芬兰语 - 芬兰 /// </summary> public const string fi_fi = nameof(fi_fi); /// <summary> /// 法语 /// </summary> public const string fr = nameof(fr); /// <summary> /// 法语 - 比利时 /// </summary> public const string fr_be = nameof(fr_be); /// <summary> /// 法语 - 加拿大 /// </summary> public const string fr_ca = nameof(fr_ca); /// <summary> /// 法语 - 法国 /// </summary> public const string fr_fr = nameof(fr_fr); /// <summary> /// 法语 - 卢森堡 /// </summary> public const string fr_lu = nameof(fr_lu); /// <summary> /// 法语 - 摩纳哥 /// </summary> public const string fr_mc = nameof(fr_mc); /// <summary> /// 法语 - 瑞士 /// </summary> public const string fr_ch = nameof(fr_ch); /// <summary> /// 希腊语 /// </summary> public const string el = nameof(el); /// <summary> /// 印尼语 /// </summary> public const string id = nameof(id); /// <summary> /// 印尼语 - 印尼 /// </summary> public const string id_id = nameof(id_id); /// <summary> /// 意大利语 /// </summary> public const string it = nameof(it); /// <summary> /// 意大利语 - 意大利 /// </summary> public const string it_it = nameof(it_it); /// <summary> /// 意大利语 - 瑞士 /// </summary> public const string it_ch = nameof(it_ch); /// <summary> /// 日语 /// </summary> public const string ja = nameof(ja); /// <summary> /// 日语 - 日本 /// </summary> public const string ja_jp = nameof(ja_jp); /// <summary> /// 韩语 /// </summary> public const string ko = nameof(ko); /// <summary> /// 韩语 - 韩国 /// </summary> public const string ko_kr = nameof(ko_kr); /// <summary> /// 公用荷兰语 /// </summary> public const string af = nameof(af); /// <summary> /// 公用荷兰语 - 南非 /// </summary> public const string af_za = nameof(af_za); /// <summary> /// 阿拉伯语 /// </summary> public const string ar = nameof(ar); /// <summary> /// 阿拉伯语 - 阿尔及利亚 /// </summary> public const string ar_dz = nameof(ar_dz); /// <summary> /// 阿拉伯语 - 巴林 /// </summary> public const string ar_bh = nameof(ar_bh); /// <summary> /// 阿拉伯语 - 埃及 /// </summary> public const string ar_eg = nameof(ar_eg); /// <summary> /// 阿拉伯语 - 伊拉克 /// </summary> public const string ar_iq = nameof(ar_iq); /// <summary> /// 阿拉伯语 - 约旦 /// </summary> public const string ar_jo = nameof(ar_jo); /// <summary> /// 阿拉伯语 - 科威特 /// </summary> public const string ar_kw = nameof(ar_kw); /// <summary> /// 阿拉伯语 - 黎巴嫩 /// </summary> public const string ar_lb = nameof(ar_lb); /// <summary> /// 阿拉伯语 - 利比亚 /// </summary> public const string ar_ly = nameof(ar_ly); /// <summary> /// 阿拉伯语 - 摩洛哥 /// </summary> public const string ar_ma = nameof(ar_ma); /// <summary> /// 阿拉伯语 - 阿曼 /// </summary> public const string ar_om = nameof(ar_om); /// <summary> /// 阿拉伯语 - 卡塔尔 /// </summary> public const string ar_qa = nameof(ar_qa); /// <summary> /// 阿拉伯语 - 沙特阿拉伯 /// </summary> public const string ar_sa = nameof(ar_sa); /// <summary> /// 阿拉伯语 - 叙利亚共和国 /// </summary> public const string ar_sy = nameof(ar_sy); /// <summary> /// 阿拉伯语 - 北非的共和国 /// </summary> public const string ar_tn = nameof(ar_tn); /// <summary> /// 阿拉伯语 - 阿拉伯联合酋长国 /// </summary> public const string ar_ae = nameof(ar_ae); /// <summary> /// 阿拉伯语 - 也门 /// </summary> public const string ar_ye = nameof(ar_ye); /// <summary> /// 亚美尼亚 /// </summary> public const string ar_hy = nameof(ar_hy); /// <summary> /// 亚美尼亚 - 亚美尼亚 /// </summary> public const string ar_am = nameof(ar_am); /// <summary> /// Azeri /// </summary> public const string az = nameof(az); /// <summary> /// Azeri - (西里尔字母的)阿塞拜疆 /// </summary> public const string az_az_cyrl = nameof(az_az_cyrl); /// <summary> /// Azeri(拉丁文) - 阿塞拜疆 /// </summary> public const string az_az_latn = nameof(az_az_latn); /// <summary> /// 巴斯克 /// </summary> public const string eu = nameof(eu); /// <summary> /// 巴斯克 - 巴斯克 /// </summary> public const string eu_es = nameof(eu_es); /// <summary> /// Belarusian /// </summary> public const string be = nameof(be); /// <summary> /// Belarusian - 白俄罗斯 /// </summary> public const string be_by = nameof(be_by); /// <summary> /// 保加利亚 /// </summary> public const string bg = nameof(bg); /// <summary> /// 保加利亚 - 保加利亚 /// </summary> public const string bg_bg = nameof(bg_bg); /// <summary> /// 嘉泰罗尼亚 /// </summary> public const string ca = nameof(ca); /// <summary> /// 嘉泰罗尼亚 - 嘉泰罗尼亚 /// </summary> public const string ca_es = nameof(ca_es); /// <summary> /// 克罗埃西亚 /// </summary> public const string hr = nameof(hr); /// <summary> /// 克罗埃西亚 - 克罗埃西亚 /// </summary> public const string hr_hr = nameof(hr_hr); /// <summary> /// 捷克 /// </summary> public const string cs = nameof(cs); /// <summary> /// 捷克 - 捷克 /// </summary> public const string cs_cz = nameof(cs_cz); /// <summary> /// 丹麦文 /// </summary> public const string da = nameof(da); /// <summary> /// 丹麦文 -丹麦 /// </summary> public const string da_dk = nameof(da_dk); /// <summary> /// Dhivehi /// </summary> public const string div = nameof(div); /// <summary> /// Dhivehi - 马尔代夫 /// </summary> public const string div_mv = nameof(div_mv); /// <summary> /// 荷兰语 /// </summary> public const string nl = nameof(nl); /// <summary> /// 荷兰语 - 比利时 /// </summary> public const string nl_be = nameof(nl_be); /// <summary> /// 荷兰语 - 荷兰 /// </summary> public const string nl_nl = nameof(nl_nl); /// <summary> /// 爱沙尼亚 /// </summary> public const string et = nameof(et); /// <summary> /// 爱沙尼亚的 - 爱沙尼亚 /// </summary> public const string et_ee = nameof(et_ee); /// <summary> /// Faroese /// </summary> public const string fo = nameof(fo); /// <summary> /// Faroese - 法罗群岛 /// </summary> public const string fo_fo = nameof(fo_fo); /// <summary> /// 波斯语 /// </summary> public const string fa = nameof(fa); /// <summary> /// 波斯语 - 伊朗王国 /// </summary> public const string fa_ir = nameof(fa_ir); /// <summary> /// 加利西亚 /// </summary> public const string gl = nameof(gl); /// <summary> /// 加利西亚 - 加利西亚 /// </summary> public const string gl_es = nameof(gl_es); /// <summary> /// 格鲁吉亚州 /// </summary> public const string ka = nameof(ka); /// <summary> /// 格鲁吉亚州 - 格鲁吉亚州 /// </summary> public const string ka_ge = nameof(ka_ge); /// <summary> /// 希腊语 - 希腊 /// </summary> public const string el_gr = nameof(el_gr); /// <summary> /// Gujarati /// </summary> public const string gu = nameof(gu); /// <summary> /// Gujarati- 印度 /// </summary> public const string gu_in = nameof(gu_in); /// <summary> /// 希伯来 /// </summary> public const string he = nameof(he); /// <summary> /// 希伯来 - 以色列 /// </summary> public const string he_il = nameof(he_il); /// <summary> /// 北印度语 /// </summary> public const string hi = nameof(hi); /// <summary> /// 北印度的 - 印度 /// </summary> public const string hi_in = nameof(hi_in); /// <summary> /// 卡纳达语 /// </summary> public const string kn = nameof(kn); /// <summary> /// 卡纳达语 - 印度 /// </summary> public const string kn_in = nameof(kn_in); /// <summary> /// Kazakh /// </summary> public const string kk = nameof(kk); /// <summary> /// Kazakh- 哈萨克 /// </summary> public const string kk_kz = nameof(kk_kz); /// <summary> /// Konkani /// </summary> public const string kok = nameof(kok); /// <summary> /// Konkani- 印度 /// </summary> public const string kok_in = nameof(kok_in); /// <summary> /// Kyrgyz /// </summary> public const string ky = nameof(ky); /// <summary> /// Kyrgyz- 哈萨克 /// </summary> public const string ky_kz = nameof(ky_kz); /// <summary> /// 拉脱维亚 /// </summary> public const string lv = nameof(lv); /// <summary> /// 拉脱维亚的 - 拉脱维亚 /// </summary> public const string lv_lv = nameof(lv_lv); /// <summary> /// 立陶宛语 /// </summary> public const string lt = nameof(lt); /// <summary> /// 立陶宛语 - 立陶宛 /// </summary> public const string lt_lt = nameof(lt_lt); /// <summary> /// 马其顿语 /// </summary> public const string mk = nameof(mk); /// <summary> /// 马其顿语 - Fyrom /// </summary> public const string mk_mk = nameof(mk_mk); /// <summary> /// 马来语 /// </summary> public const string ms = nameof(ms); /// <summary> /// 马来语 - 汶莱 /// </summary> public const string ms_bn = nameof(ms_bn); /// <summary> /// 马来语 - 马来西亚 /// </summary> public const string ms_my = nameof(ms_my); /// <summary> /// 马拉地语 /// </summary> public const string mr = nameof(mr); /// <summary> /// 马拉地语 - 印度 /// </summary> public const string mr_in = nameof(mr_in); /// <summary> /// Punjab 语 /// </summary> public const string pa = nameof(pa); /// <summary> /// Punjab 语 - 印度 /// </summary> public const string pa_in = nameof(pa_in); /// <summary> /// 罗马尼亚语 /// </summary> public const string ro = nameof(ro); /// <summary> /// 罗马尼亚语 - 罗马尼亚 /// </summary> public const string ro_ro = nameof(ro_ro); /// <summary> /// 梵文 /// </summary> public const string sa = nameof(sa); /// <summary> /// 梵文 - 印度 /// </summary> public const string sa_in = nameof(sa_in); /// <summary> /// 塞尔维亚 - (西里尔字母的)塞尔 /// </summary> public const string sr_sp_yrl = nameof(sr_sp_yrl); /// <summary> /// 塞尔维亚(拉丁文) - 塞尔维亚共 /// </summary> public const string sr_sp_atn = nameof(sr_sp_atn); /// <summary> /// 斯洛伐克 /// </summary> public const string sk = nameof(sk); /// <summary> /// 斯洛伐克 - 斯洛伐克 /// </summary> public const string sk_sk = nameof(sk_sk); /// <summary> /// 斯洛文尼亚 /// </summary> public const string sl = nameof(sl); /// <summary> /// 斯洛文尼亚 - 斯洛文尼亚 /// </summary> public const string sl_si = nameof(sl_si); /// <summary> /// Swahili /// </summary> public const string sw = nameof(sw); /// <summary> /// Swahili - 肯尼亚 /// </summary> public const string sw_ke = nameof(sw_ke); /// <summary> /// Syriac /// </summary> public const string syr = nameof(syr); /// <summary> /// Syriac - 叙利亚共和国 /// </summary> public const string syr_sy = nameof(syr_sy); /// <summary> /// 坦米尔 /// </summary> public const string ta = nameof(ta); /// <summary> /// 坦米尔 - 印度 /// </summary> public const string ta_in = nameof(ta_in); /// <summary> /// Tatar /// </summary> public const string tt = nameof(tt); /// <summary> /// Telugu /// </summary> public const string te = nameof(te); /// <summary> /// Telugu - 印度 /// </summary> public const string te_in = nameof(te_in); /// <summary> /// Urdu /// </summary> public const string ur = nameof(ur); /// <summary> /// Urdu- 巴基斯坦 /// </summary> public const string ur_pk = nameof(ur_pk); /// <summary> /// Uzbek /// </summary> public const string uz = nameof(uz); /// <summary> /// uzbek - (西里尔字母的)乌兹别克 /// </summary> public const string uz_uz_cyrl = nameof(uz_uz_cyrl); /// <summary> /// Uzbek(拉丁文) - 乌兹别克斯坦 /// </summary> public const string uz_uz_latn = nameof(uz_uz_latn); /// <summary> /// 阿尔巴尼亚 /// </summary> public const string sq = nameof(sq); /// <summary> /// 阿尔巴尼亚 - 阿尔巴尼亚 /// </summary> public const string sq_al = nameof(sq_al); } } <file_sep>namespace NXHub.Constants { /// <summary> /// 数字格式化参数 /// 所有的字母参数均可以和数字组合, 数字叫作精度说明符, 一般表示保留多少位, 或者补齐多少位; /// 如: 25.ToString("D4") -> 0025; /// 如: 25.ToString("F2") -> 25.00; /// 如: string.Format("{0:P2}", 0.25) -> 25.00%; /// </summary> public class F_Num { /// <summary> /// 货币, 如: 2.5.ToString("C") -> ¥2.50 /// </summary> public const string C = nameof(C); /// <summary> /// 占位, 如: 25.ToString("D4") -> 0025 /// </summary> public const string D = nameof(D); /// <summary> /// 科学计数法, 如: 2500.ToString("E") -> 2.500000E+003 /// 如果不加数字, 默认 6 位小数 /// </summary> public const string E = nameof(E); /// <summary> /// 科学计数法, 如: 2500.ToString("e") -> 2.5e+003 /// </summary> public const string e = nameof(e); /// <summary> /// 小数点, 如: 25.ToString("F2") -> 25.00 /// </summary> public const string F = nameof(F); /// <summary> /// 加分隔符, 如: 4384.5.ToString("N") -> 4,384.50 /// </summary> public const string N = nameof(N); /// <summary> /// 十六进制, 如: 225.ToString("X") -> 1120 /// </summary> public const string X = nameof(X); /// <summary> /// 百分比, 如: 0.223.ToString("P") -> 22.3% /// </summary> public const string P = nameof(P); /// <summary> /// 自定义占位符, 没有会以 0 补齐 /// 如: 0.025.ToString("00.00%") -> 02.50% /// </summary> public const string C0 = "0"; /// <summary> /// 自定义占位符, 没有不会补齐 /// 如: 0.025.ToString("##.##%") -> 2.5% /// </summary> public const string CS = "#"; /// <summary> /// 自定义百分比 /// 如: 0.025.ToString("00.00%") -> 02.50% /// </summary> public const string CP = "%"; /// <summary> /// 自定义小数点 /// 如: 0.025.ToString("00.00%") -> 02.50% /// </summary> public const string CD = "."; } } <file_sep>namespace NXHub.Constants { public partial class F_Date { /// <summary> /// Format 参数: 短日期 /// 如: 2019/1/2(zh-cn) /// 如: 1/2/2019(en-us) /// </summary> public const string Fd = "d"; /// <summary> /// Format 参数: 长日期 /// 如: 2019年1月2日(zh-cn) /// 如: Wednesday, January 2, 2019(en-us) /// </summary> public const string FD = "D"; /// <summary> /// Format 参数: 长日期, 短时间 /// 如: 2019年1月2日 3:04(zh-cn) /// 如: Wednesday, January 2, 2019 3:04 AM(en-us) /// </summary> public const string Ff = "f"; /// <summary> /// Format 参数: 长日期, 长时间 /// 如: 2019年1月2日 3:04:05(zh-cn) /// 如: Wednesday, January 2, 2019 3:04:05 AM(en-us) /// </summary> public const string FF = "F"; /// <summary> /// Format 参数: 短日期, 短时间 /// 如: 2019/1/2 3:04(zh-cn) /// 如: 1/2/2019 3:04 AM(en-us) /// </summary> public const string Fg = "g"; /// <summary> /// Format 参数: 短日期, 长时间 /// 如: 2019/1/2 3:04:05(zh-cn) /// 如: 1/2/2019 3:04:05 AM(en-us) /// </summary> public const string FG = "G"; /// <summary> /// Format 参数: 月日 /// 如: 1月2日(zh-cn) /// 如: January 2(en-us) /// </summary> public const string Fm = "m"; /// <summary> /// Format 参数: 月日 /// 如: 1月2日(zh-cn) /// 如: January 2 /// </summary> public const string FM = "M"; /// <summary> /// Format 参数: 标准时间 /// 如: Wed, 02 Jan 2019 03:04:05 GMT(zh-cn) /// 如: Wed, 02 Jan 2019 03:04:05 GMT(en-us) /// </summary> public const string Fr = "r"; /// <summary> /// Format 参数: 标准时间 /// 如: Wed, 02 Jan 2019 03:04:05 GMT(zh-cn) /// 如: Wed, 02 Jan 2019 03:04:05 GMT(en-us) /// </summary> public const string FR = "R"; /// <summary> /// Format 参数: 短时间(当地) /// 如: 2019-01-02T03:04:05(zh-cn) /// 如: 2019-01-02T03:04:05(en-us) /// </summary> public const string Fs = "s"; /// <summary> /// Format 参数: 短时间 /// 如: 3:04(zh-cn) /// 如: 3:04 AM(en-us) /// </summary> public const string Ft = "t"; /// <summary> /// Format 参数: 长时间 /// 如: 3:04:05(zh-cn) /// 如: 3:04:05 AM(en-us) /// </summary> public const string FT = "T"; /// <summary> /// Format 参数: 通用短时间 /// 如: 2019-01-02 03:04:05Z(zh-cn) /// 如: 2019-01-02 03:04:05Z(en-us) /// </summary> public const string Fu = "u"; /// <summary> /// Format 参数: 通用长日期长时间 /// 如: 2019年1月1日 19:04:05(zh-cn) /// 如: Tuesday, January 1, 2019 7:04:05 PM(en-us) /// </summary> public const string FU = "U"; /// <summary> /// Format 参数: 年月 /// 如: 2019年1月(zh-cn) /// 如: January 2019(en-us) /// </summary> public const string Fy = "y"; /// <summary> /// Format 参数: 年月 /// 如: 2019年1月(zh-cn) /// 如: January 2019(en-us) /// </summary> public const string FY = "Y"; } } <file_sep>using System.Globalization; using Xunit; namespace NXHub.Constants.Tests { public class NumberFormatTest { [Theory] [InlineData(F_Num.C, C_Lang.zh_cn, 25, "¥25.00")] [InlineData(F_Num.C, C_Lang.en_us, 25, "$25.00")] [InlineData(F_Num.D + "4", C_Lang.zh_cn, 25, "0025")] [InlineData(F_Num.D + "4", C_Lang.en_us, 25, "0025")] [InlineData(F_Num.E, C_Lang.zh_cn, 25, "2.500000E+001")] [InlineData(F_Num.E, C_Lang.en_us, 25, "2.500000E+001")] [InlineData(F_Num.E + "2", C_Lang.zh_cn, 25, "2.50E+001")] [InlineData(F_Num.E + "2", C_Lang.en_us, 25, "2.50E+001")] [InlineData(F_Num.e, C_Lang.zh_cn, 25, "2.500000e+001")] [InlineData(F_Num.e, C_Lang.en_us, 25, "2.500000e+001")] [InlineData(F_Num.e + "2", C_Lang.zh_cn, 25, "2.50e+001")] [InlineData(F_Num.e + "2", C_Lang.en_us, 25, "2.50e+001")] [InlineData(F_Num.F, C_Lang.zh_cn, 25, "25.00")] [InlineData(F_Num.F, C_Lang.en_us, 25, "25.00")] [InlineData(F_Num.F + "1", C_Lang.zh_cn, 25, "25.0")] [InlineData(F_Num.F + "1", C_Lang.en_us, 25, "25.0")] [InlineData(F_Num.N, C_Lang.zh_cn, 2500, "2,500.00")] [InlineData(F_Num.N, C_Lang.en_us, 2500, "2,500.00")] [InlineData(F_Num.P, C_Lang.zh_cn, 25, "2,500.00%")] [InlineData(F_Num.P, C_Lang.en_us, 25, "2,500.00%")] [InlineData(F_Num.P + "1", C_Lang.zh_cn, 25, "2,500.0%")] [InlineData(F_Num.P + "1", C_Lang.en_us, 25, "2,500.0%")] [InlineData(F_Num.X, C_Lang.zh_cn, 16, "10")] [InlineData(F_Num.X, C_Lang.en_us, 16, "10")] [InlineData(F_Num.X, C_Lang.zh_cn, 10, "A")] [InlineData(F_Num.X, C_Lang.en_us, 10, "A")] public void IntNumberTest(string format, string name, int source, string expected) { var culture = CultureInfo.CreateSpecificCulture(name); Assert.Equal(expected, source.ToString(format, culture)); } [Theory] [InlineData(F_Num.C, C_Lang.zh_cn, 2.5, "¥2.50")] [InlineData(F_Num.C, C_Lang.en_us, 2.5, "$2.50")] [InlineData(F_Num.E, C_Lang.zh_cn, 0.25, "2.500000E-001")] [InlineData(F_Num.E, C_Lang.en_us, 0.25, "2.500000E-001")] [InlineData(F_Num.E + "2", C_Lang.zh_cn, 0.25, "2.50E-001")] [InlineData(F_Num.E + "2", C_Lang.en_us, 0.25, "2.50E-001")] [InlineData(F_Num.e, C_Lang.zh_cn, 0.25, "2.500000e-001")] [InlineData(F_Num.e, C_Lang.en_us, 0.25, "2.500000e-001")] [InlineData(F_Num.e + "2", C_Lang.zh_cn, 0.25, "2.50e-001")] [InlineData(F_Num.e + "2", C_Lang.en_us, 0.25, "2.50e-001")] [InlineData(F_Num.F, C_Lang.zh_cn, 2.5, "2.50")] [InlineData(F_Num.F, C_Lang.en_us, 2.5, "2.50")] [InlineData(F_Num.F + "3", C_Lang.zh_cn, 2.5, "2.500")] [InlineData(F_Num.F + "3", C_Lang.en_us, 2.5, "2.500")] [InlineData(F_Num.N, C_Lang.zh_cn, 2500.5, "2,500.50")] [InlineData(F_Num.N, C_Lang.en_us, 2500.5, "2,500.50")] [InlineData(F_Num.P, C_Lang.zh_cn, 0.25, "25.00%")] [InlineData(F_Num.P, C_Lang.en_us, 0.25, "25.00%")] [InlineData(F_Num.P + "1", C_Lang.zh_cn, 0.25, "25.0%")] [InlineData(F_Num.P + "1", C_Lang.en_us, 0.25, "25.0%")] // Custom [InlineData("00.00%", C_Lang.zh_cn, 0.25, "25.00%")] [InlineData("00.00%", C_Lang.en_us, 0.25, "25.00%")] [InlineData("00.00%", C_Lang.zh_cn, 0.255, "25.50%")] [InlineData("00.00%", C_Lang.en_us, 0.255, "25.50%")] [InlineData("00.00%", C_Lang.zh_cn, 0.0255, "02.55%")] [InlineData("00.00%", C_Lang.en_us, 0.0255, "02.55%")] [InlineData("##.##%", C_Lang.zh_cn, 0.0255, "2.55%")] [InlineData("##.##%", C_Lang.en_us, 0.0255, "2.55%")] public void FloatNumberTest(string format, string name, double source, string expected) { var culture = CultureInfo.CreateSpecificCulture(name); Assert.Equal(expected, source.ToString(format, culture)); } } } <file_sep># Constants .NET 常用字符串,如格式化参数字符串等。 <file_sep>using System; using System.Globalization; using Xunit; namespace NXHub.Constants.Tests { public class DateFormatTest { private readonly DateTime _dateTime = new DateTime(2019, 1, 2, 3, 4, 5, 666, DateTimeKind.Local); [Theory] [InlineData(F_Date.Fd, C_Lang.zh_cn, "2019/1/2")] [InlineData(F_Date.Fd, C_Lang.en_us, "1/2/2019")] [InlineData(F_Date.FD, C_Lang.zh_cn, "2019年1月2日")] [InlineData(F_Date.FD, C_Lang.en_us, "Wednesday, January 2, 2019")] [InlineData(F_Date.Ff, C_Lang.zh_cn, "2019年1月2日 3:04")] [InlineData(F_Date.Ff, C_Lang.en_us, "Wednesday, January 2, 2019 3:04 AM")] [InlineData(F_Date.FF, C_Lang.zh_cn, "2019年1月2日 3:04:05")] [InlineData(F_Date.FF, C_Lang.en_us, "Wednesday, January 2, 2019 3:04:05 AM")] [InlineData(F_Date.Fg, C_Lang.zh_cn, "2019/1/2 3:04")] [InlineData(F_Date.Fg, C_Lang.en_us, "1/2/2019 3:04 AM")] [InlineData(F_Date.FG, C_Lang.zh_cn, "2019/1/2 3:04:05")] [InlineData(F_Date.FG, C_Lang.en_us, "1/2/2019 3:04:05 AM")] [InlineData(F_Date.Fm, C_Lang.zh_cn, "1月2日")] [InlineData(F_Date.Fm, C_Lang.en_us, "January 2")] [InlineData(F_Date.FM, C_Lang.zh_cn, "1月2日")] [InlineData(F_Date.FM, C_Lang.en_us, "January 2")] [InlineData(F_Date.Fr, C_Lang.zh_cn, "Wed, 02 Jan 2019 03:04:05 GMT")] [InlineData(F_Date.Fr, C_Lang.en_us, "Wed, 02 Jan 2019 03:04:05 GMT")] [InlineData(F_Date.FR, C_Lang.zh_cn, "Wed, 02 Jan 2019 03:04:05 GMT")] [InlineData(F_Date.FR, C_Lang.en_us, "Wed, 02 Jan 2019 03:04:05 GMT")] [InlineData(F_Date.Fs, C_Lang.zh_cn, "2019-01-02T03:04:05")] [InlineData(F_Date.Fs, C_Lang.en_us, "2019-01-02T03:04:05")] [InlineData(F_Date.Ft, C_Lang.zh_cn, "3:04")] [InlineData(F_Date.Ft, C_Lang.en_us, "3:04 AM")] [InlineData(F_Date.FT, C_Lang.zh_cn, "3:04:05")] [InlineData(F_Date.FT, C_Lang.en_us, "3:04:05 AM")] [InlineData(F_Date.Fu, C_Lang.zh_cn, "2019-01-02 03:04:05Z")] [InlineData(F_Date.Fu, C_Lang.en_us, "2019-01-02 03:04:05Z")] [InlineData(F_Date.FU, C_Lang.zh_cn, "2019年1月1日 19:04:05")] [InlineData(F_Date.FU, C_Lang.en_us, "Tuesday, January 1, 2019 7:04:05 PM")] [InlineData(F_Date.Fy, C_Lang.zh_cn, "2019年1月")] [InlineData(F_Date.Fy, C_Lang.en_us, "January 2019")] [InlineData(F_Date.FY, C_Lang.zh_cn, "2019年1月")] [InlineData(F_Date.FY, C_Lang.en_us, "January 2019")] public void FormatFdTest(string format, string name, string expected) { var culture = CultureInfo.CreateSpecificCulture(name); var v = _dateTime.ToString(format, culture); Assert.NotNull(v); Assert.NotEmpty(v); Assert.Equal(expected, v); } } } <file_sep>using System; using Xunit; namespace NXHub.Constants.Tests { public class GuidFormatTest { [Fact] public void GuidNTest() { var guid = Guid.NewGuid() .ToString(F_Guid.N); Assert.NotNull(guid); Assert.NotEmpty(guid); Assert.Equal(32, guid.Length); Assert.False(guid.StartsWith("{")); Assert.False(guid.EndsWith("}")); Assert.DoesNotContain("-", guid); } [Fact] public void GuidDTest() { var guid = Guid.NewGuid() .ToString(F_Guid.D); Assert.NotNull(guid); Assert.NotEmpty(guid); Assert.Equal(36, guid.Length); Assert.False(guid.StartsWith("{")); Assert.False(guid.EndsWith("}")); Assert.Contains("-", guid); } [Fact] public void GuidBTest() { var guid = Guid.NewGuid() .ToString(F_Guid.B); Assert.NotNull(guid); Assert.NotEmpty(guid); Assert.Equal(38, guid.Length); Assert.StartsWith("{", guid); Assert.EndsWith("}", guid); Assert.Contains("-", guid); } [Fact] public void GuidPTest() { var guid = Guid.NewGuid() .ToString(F_Guid.P); Assert.NotNull(guid); Assert.NotEmpty(guid); Assert.Equal(38, guid.Length); Assert.StartsWith("(", guid); Assert.EndsWith(")", guid); Assert.Contains("-", guid); } [Fact] public void GuidXTest() { var guid = Guid.NewGuid() .ToString(F_Guid.X); Assert.NotNull(guid); Assert.NotEmpty(guid); Assert.Equal(68, guid.Length); Assert.StartsWith("{", guid); Assert.EndsWith("}}", guid); Assert.Contains(",", guid); Assert.Contains("0x", guid); } } }
eeff15aca83b6bf7dbb90262839e243d5e2681e1
[ "Markdown", "C#" ]
10
C#
nxhub/Constants
03e72a0d5f1483b09730ccc066597710d62d240f
79f03444456a1a1a2d1dd1cacf6a5a6399be6e9f
refs/heads/master
<repo_name>shankar75031/native-code-interaction-flutter<file_sep>/android/app/src/main/kotlin/com/example/flutter_with_native_eg/MainActivity.kt package com.example.flutter_with_native_eg import android.content.ContextWrapper import android.content.Intent import android.content.IntentFilter import android.os.BatteryManager import android.os.Build import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel class MainActivity : FlutterActivity() { private val CHANNEL = "course.flutter.dev/battery" override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result -> if(call.method.equals("getBatteryLevel")){ val batteryLevel = getBatteryLevel() if(batteryLevel != -1){ result.success(batteryLevel) }else{ result.error("UNAVILABLE", "Could not fetch battery level", null) } }else{ result.notImplemented() } } } private fun getBatteryLevel(): Int { var batteryLevel = -1 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val batteryManager = getSystemService(BATTERY_SERVICE) as BatteryManager batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) } else { val intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) batteryLevel = ((intent?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1) * 100) / (intent?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: -1) } return batteryLevel } }
b3ae4e36039223d56b61386bc059641f72266f3b
[ "Kotlin" ]
1
Kotlin
shankar75031/native-code-interaction-flutter
8dfcee92ec9dad3d55020fe7c4509a9998d9397f
c02ea7d99c1316e131fdd29837b5cd89aba8ece4
refs/heads/master
<file_sep>pyg = 'ay' original = raw_input('Enter a word:') if len(original) > 0 and original.isalpha(): word = original.lower() first = word[0] print word print word[0] if word[0] in 'aeiou': new_word = word+pyg print new_word else: new_word = word[1:]+first+pyg print new_word else: print 'Not a word'
9e14d9f487e2be6562e77773b50c6a843db5d250
[ "Python" ]
1
Python
tom-davies/pyglatin
68a6311cf1d917515d24285dad984f7136533098
d8648f771794a9cc09de0783553722bd6b2778d6
refs/heads/master
<file_sep>package cn.springlogic.blog.jpa.entity; import cn.springlogic.social.jpa.entity.Tag; import lombok.Data; import java.util.List; /** * * Created by admin on 2017/4/24. */ @Data public class BlogParam { private Article article; //private List<Topic> topics; private List<Tag> tags; } <file_sep>package cn.springlogic.blog.jpa.entity; import cn.springlogic.user.jpa.entity.User; import lombok.Data; import org.hibernate.annotations.CreationTimestamp; import javax.persistence.*; import java.util.Date; /** * Created by admin on 2017/4/18. */ @Data @Entity public class Category { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String name; @Column(name = "create_time") @CreationTimestamp @Temporal(TemporalType.TIMESTAMP) private Date createTime; /** 分类是多的一端 (多个分类对应一个用户)*/ @ManyToOne(fetch=FetchType.LAZY, // 指定属性的抓取策略 FetchType.LAZY:延迟加载 FetchType.EAGER:立即加载 targetEntity=User.class)// 指定关联的持久化类 /** 生成关联的外键列 */ @JoinColumn(name="user_id", // 外键列的列名 referencedColumnName="id") // 指定引用表的主键列 private User user; @ManyToOne(fetch=FetchType.LAZY, // 指定属性的抓取策略 FetchType.LAZY:延迟加载 FetchType.EAGER:立即加载 targetEntity=Category.class)// 指定关联的持久化类 /** 生成关联的外键列 */ @JoinColumn(name="categoryId_id", // 外键列的列名 referencedColumnName="id") // 指定引用表的主键列 private Category categoryId; } <file_sep>package cn.springlogic.blog.jpa.entity.rest; import cn.springlogic.user.jpa.entity.User; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fitcooker.app.serializer.AppDataPreFixSerializer; import org.springframework.data.rest.core.config.Projection; /** * Created by admin on 2017/4/26. */ @Projection(name = "userinfo",types = {User.class}) public interface UserProjection { int getId(); String getNickName(); @JsonSerialize(using = AppDataPreFixSerializer.class) String getAvatar(); String getEmail(); String getStatus(); String getPhone(); String getUsername(); } <file_sep>package cn.springlogic.blog.jpa.entity.rest; import cn.springlogic.blog.jpa.entity.Article; import org.springframework.data.rest.core.config.Projection; /** * Created by admin on 2017/4/26. */ @Projection(types = {Article.class}) public interface ArticleIdProjection { int getId(); } <file_sep>package cn.springlogic.blog.web; import cn.springlogic.blog.jpa.entity.Article; import cn.springlogic.blog.jpa.entity.BlogParam; import cn.springlogic.blog.jpa.repository.ArticleRepository; import cn.springlogic.blog.service.ArticleService; import cn.springlogic.social.jpa.entity.*; import cn.springlogic.social.jpa.entity.Publication; import cn.springlogic.social.jpa.repository.*; import cn.springlogic.social.service.TagService; import cn.springlogic.social.service.TopicService; import cn.springlogic.user.jpa.repository.UserRepository; import com.fitcooker.app.BussinessException; import org.apache.commons.collections.map.HashedMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.rest.webmvc.support.RepositoryEntityLinks; import org.springframework.data.web.PageableDefault; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Created by admin on 2017/4/21. */ @RequestMapping("/api/article") @Controller public class ArticleController { @Autowired private ArticleService articleService; @Autowired private TagService tagService; @Autowired private TopicService topicService; @Autowired private UserRepository userRepository; @Autowired private RepositoryEntityLinks entityLinks; @Autowired private TopicRepository topicRepository; @Autowired private TagRepository tagRepository; @Autowired private FollowRepository followRepository; @Autowired private PublicationRepository publicationRepository; @Autowired private PublicationFavorRepository publicationFavorRepository; @Autowired private PublicationCommentRepository publicationCommentRepository; /** * BlogParam是一个自定义接收饭圈参数的实体 * * @param blogParam * @return */ @Transactional @RequestMapping(value = "/publish", method = RequestMethod.POST, consumes = "application/json") public ResponseEntity<Map<String,Object>> publishArticle(@RequestBody BlogParam blogParam) throws BussinessException { try { ConcurrentHashMap<String,Object>map=new ConcurrentHashMap<>(); ConcurrentHashMap<String,Object>publicationmap=new ConcurrentHashMap<>(); ConcurrentHashMap<String,Object>articlemap=new ConcurrentHashMap<>(); map.put("publication",publicationmap); //拿出组合类里面的 article ,持久化到数据库 Article article = blogParam.getArticle(); articleService.save(article);// 去Article配置了 cascade = CascadeType.PERSIST 成功,如果不配置 会因为 Media是一个瞬态,保存失败. /*拿出组合类里面的 tags .但注意,有可能该 饭圈 没有包含 标签,但是 还是要保存publication这个发布状态.*/ List<Tag> tags = blogParam.getTags(); Publication publication = new Publication(); publication.setArticle(article); publication.setUser(article.getUser()); Tag t=null; if (tags != null) { for (int i = 0; i < tags.size(); i++) { Tag tag = tags.get(i); //判断是否已经创建了该topic,决定是否设置user创建者 Topic tempTopic = topicService.findByname(tag.getTopic().getName()); if (tempTopic != null) { //说明有这个topic了,就设置该topic的创建者userid tag.setTopic(tempTopic); } tag.setPublication(publication); t= tagService.save(tag); publicationmap.put("id",t.getPublication().getId()); articlemap.put("id",t.getPublication().getArticle().getId()); publicationmap.put("article",articlemap); } } else { Publication save = publicationRepository.save(publication); /* Tag tag = new Tag(); tag.setPublication(publication); t=tagService.save(tag); */ publicationmap.put("id",save.getId()); articlemap.put("id",save.getArticle().getId()); publicationmap.put("article",articlemap); } /* ConcurrentHashMap<String,Object>map=new ConcurrentHashMap<>(); ConcurrentHashMap<String,Object>publicationmap=new ConcurrentHashMap<>(); ConcurrentHashMap<String,Object>articlemap=new ConcurrentHashMap<>(); map.put("publication",publicationmap); publicationmap.put("id",t.getPublication().getId()); articlemap.put("id",t.getPublication().getArticle().getId()); publicationmap.put("article",articlemap); */ return ResponseEntity.ok(map); } catch (Exception e) { throw new BussinessException("发布失败"); } } /*************************************************************/ /* 广场 饭圈列表 */ @RequestMapping(value = "/square") public ResponseEntity<Map<String,Object>> del(@PageableDefault(value = 20, sort = {"createTime"}, direction = Sort.Direction.DESC) Pageable pageable, @RequestParam( required = false, name = "topic") String topic, @RequestParam(name = "user_id")int userId) { Page<Publication> byAll = publicationRepository.findByAll(topic, pageable); /** * 处理. */ for (Publication p : byAll.getContent()) { //获取评论总数 p.setPublicationCommentsTotal(p.getPublicationComments().size()); //获取点赞总数 p.setPublicationFavorsTotal(p.getPublicationFavors().size()); //处理所有评论列表 List<PublicationComment> tempComments = publicationCommentRepository.findFirst2BypublicationId(p.getId()); for (PublicationComment c : tempComments) { c.setPublication(null); } //处理点赞列表 List<PublicationFavor> tempFavors = publicationFavorRepository.findBypublicationId(p.getId()); for (PublicationFavor f : tempFavors) { f.setPublication(null); if(f.getUser().getId()==userId){ p.setFavor(f); } } //处理 标签列表 List<Tag> tempTags = tagRepository.findBypublicationId(p.getId()); for (Tag t : tempTags) { t.setPublication(null); Topic temp = t.getTopic(); if (temp!=null) { Topic tempTopic = topicRepository.getOne(temp.getId()); tempTopic.setTags(null); t.setTopic(null); t.setTopic(tempTopic); } } p.setPublicationComments(null); /*设置评论列表*/ p.setPublicationComments(tempComments); p.setPublicationFavors(null); /*设置点赞列表*/ //p.setPublicationFavors(tempFavors); p.setTags(null); p.setTags(tempTags); //设置该publication的作者 当前用户是否关注了 Follow tempfollow = followRepository.findByuserIdAndFollowUserId(userId, p.getUser().getId()); if(tempfollow!=null){ p.setFollow(tempfollow); } } //最外层Map Map<String,Object> map=new HashedMap(); //publications组装 List<Publication> publications; publications=byAll.getContent(); Map<String,List<Publication>> listMap=new HashedMap(); listMap.put("publications",publications); //page :组装 Map<String,Object> pageMap=new HashedMap(); pageMap.put("number",byAll.getNumber()); pageMap.put("size",byAll.getSize()); pageMap.put("totalElements",byAll.getTotalElements()); pageMap.put("totalPages",byAll.getTotalPages()); //_links;组装 Map<String,Map<String,String>>linkMap=new HashedMap(); Map<String,String>selfMap=new HashedMap(); selfMap.put("href",""); linkMap.put("self",selfMap); map.put("_embedded",listMap); map.put("_links",linkMap); map.put("page",pageMap); return ResponseEntity.ok(map); } /** * 读取已经关注用户的饭圈 * @param pageable * @param topic * @param userId * @return */ @RequestMapping("/follow") public ResponseEntity<Map<String,Object>> del2(@PageableDefault(value = 20, sort = {"createTime"}, direction = Sort.Direction.DESC) Pageable pageable, @RequestParam( required = false, name = "topic") String topic, @RequestParam(name = "user_id")int userId) { Page<Publication> byAll = publicationRepository.findByFollow(topic,userId,pageable); /** * 处理. */ for (Publication p : byAll.getContent()) { //获取评论总数 p.setPublicationCommentsTotal(p.getPublicationComments().size()); //获取点赞总数 p.setPublicationFavorsTotal(p.getPublicationFavors().size()); //处理所有评论列表 List<PublicationComment> tempComments = publicationCommentRepository.findFirst2BypublicationId(p.getId()); for (PublicationComment c : tempComments) { c.setPublication(null); PublicationComment tempReply = (PublicationComment) c.getReplyComment(); System.out.println("!!!!replycomment==" + tempReply); /* !!!!replycomment==null !!!!replycomment==PublicationComment@8953(publication=null,id=1,content="上一条评论内容",replyComment=null) !!!!replycomment==PublicationComment@8998(publication=null,id,content="上一条评论内容",replyComment="上一个评论@8953") !!!!replycomment==PublicationComment@9091(publication=null, replyComment="@8998 --@8953") if(tempReply!=null){ tempReply.setReplyComment(null); // 只有最后一条 } */ } //处理点赞列表 List<PublicationFavor> tempFavors = publicationFavorRepository.findBypublicationId(p.getId()); for (PublicationFavor f : tempFavors) { f.setPublication(null); if(f.getUser().getId()==userId){ p.setFavor(f); } } //处理 标签列表 List<Tag> tempTags = tagRepository.findBypublicationId(p.getId()); for (Tag t : tempTags) { t.setPublication(null); Topic temp = t.getTopic(); if (temp!=null) { Topic tempTopic = topicRepository.getOne(temp.getId()); tempTopic.setTags(null); t.setTopic(null); t.setTopic(tempTopic); } System.out.println("!!!!!tag=" + t); } p.setPublicationComments(null); p.setPublicationComments(tempComments); p.setPublicationFavors(null); //p.setPublicationFavors(tempFavors); p.setTags(null); p.setTags(tempTags); //设置该publication的作者 当前用户是否关注了 Follow tempfollow = followRepository.findByuserIdAndFollowUserId(userId, p.getUser().getId()); if(tempfollow!=null){ p.setFollow(tempfollow); } } //最外层Map Map<String,Object> map=new HashedMap(); //publications组装 List<Publication> publications; publications=byAll.getContent(); Map<String,List<Publication>> listMap=new HashedMap(); listMap.put("publications",publications); //page :组装 Map<String,Object> pageMap=new HashedMap(); pageMap.put("number",byAll.getNumber()); pageMap.put("size",byAll.getSize()); pageMap.put("totalElements",byAll.getTotalElements()); pageMap.put("totalPages",byAll.getTotalPages()); //_links;组装 Map<String,Map<String,String>>linkMap=new HashedMap(); Map<String,String>selfMap=new HashedMap(); selfMap.put("href",""); linkMap.put("self",selfMap); map.put("_embedded",listMap); map.put("_links",linkMap); map.put("page",pageMap); return ResponseEntity.ok(map); } @RequestMapping("/user") public ResponseEntity<Map<String,Object>> del3(@PageableDefault(value = 20, sort = {"createTime"}, direction = Sort.Direction.DESC) Pageable pageable, @RequestParam(name = "current_uid")int userId, @RequestParam(name="target_uid")int targetUserId) { Page<Publication> byAll = publicationRepository.findByUserId(targetUserId,pageable); /** * 处理. */ for (Publication p : byAll.getContent()) { //获取评论总数 p.setPublicationCommentsTotal(p.getPublicationComments().size()); //获取点赞总数 p.setPublicationFavorsTotal(p.getPublicationFavors().size()); //处理所有评论列表 List<PublicationComment> tempComments = publicationCommentRepository.findFirst2BypublicationId(p.getId()); for (PublicationComment c : tempComments) { c.setPublication(null); PublicationComment tempReply = (PublicationComment) c.getReplyComment(); System.out.println("!!!!replycomment==" + tempReply); /* !!!!replycomment==null !!!!replycomment==PublicationComment@8953(publication=null,id=1,content="上一条评论内容",replyComment=null) !!!!replycomment==PublicationComment@8998(publication=null,id,content="上一条评论内容",replyComment="上一个评论@8953") !!!!replycomment==PublicationComment@9091(publication=null, replyComment="@8998 --@8953") if(tempReply!=null){ tempReply.setReplyComment(null); // 只有最后一条 } */ } //处理点赞列表 List<PublicationFavor> tempFavors = publicationFavorRepository.findBypublicationId(p.getId()); for (PublicationFavor f : tempFavors) { f.setPublication(null); if(f.getUser().getId()==userId){ p.setFavor(f); } } //处理 标签列表 List<Tag> tempTags = tagRepository.findBypublicationId(p.getId()); for (Tag t : tempTags) { t.setPublication(null); Topic temp = t.getTopic(); if (temp!=null) { Topic tempTopic = topicRepository.getOne(temp.getId()); tempTopic.setTags(null); t.setTopic(null); t.setTopic(tempTopic); } System.out.println("!!!!!tag=" + t); } p.setPublicationComments(null); p.setPublicationComments(tempComments); p.setPublicationFavors(null); //p.setPublicationFavors(tempFavors); p.setTags(null); p.setTags(tempTags); //设置该publication的作者 当前用户是否关注了 Follow tempfollow = followRepository.findByuserIdAndFollowUserId(userId, p.getUser().getId()); if(tempfollow!=null){ p.setFollow(tempfollow); } } //最外层Map Map<String,Object> map=new HashedMap(); //publications组装 List<Publication> publications; publications=byAll.getContent(); Map<String,List<Publication>> listMap=new HashedMap(); listMap.put("publications",publications); //page :组装 Map<String,Object> pageMap=new HashedMap(); pageMap.put("number",byAll.getNumber()); pageMap.put("size",byAll.getSize()); pageMap.put("totalElements",byAll.getTotalElements()); pageMap.put("totalPages",byAll.getTotalPages()); //_links;组装 Map<String,Map<String,String>>linkMap=new HashedMap(); Map<String,String>selfMap=new HashedMap(); selfMap.put("href",""); linkMap.put("self",selfMap); map.put("_embedded",listMap); map.put("_links",linkMap); map.put("page",pageMap); return ResponseEntity.ok(map); } //显示一条饭圈详情 @RequestMapping("/publication") public ResponseEntity<Publication> del4( @RequestParam(name = "current_uid")int userId, @RequestParam(name="target_pid")int publicationId){ Publication p = publicationRepository.findOneById(publicationId); p.setTags(null); //获取评论总数 p.setPublicationCommentsTotal(p.getPublicationComments().size()); //获取点赞总数 p.setPublicationFavorsTotal(p.getPublicationFavors().size()); //处理所有评论列表 List<PublicationComment> tempComments = publicationCommentRepository.findFirst2BypublicationId(p.getId()); for (PublicationComment c : tempComments) { c.setPublication(null); } //处理点赞列表 List<PublicationFavor> tempFavors = publicationFavorRepository.findBypublicationId(p.getId()); for (PublicationFavor f : tempFavors) { f.setPublication(null); if(f.getUser().getId()==userId){ p.setFavor(f); } } //处理 标签列表 List<Tag> tempTags = tagRepository.findBypublicationId(p.getId()); for (Tag t : tempTags) { t.setPublication(null); Topic temp = t.getTopic(); if (temp!=null) { Topic tempTopic = topicRepository.getOne(temp.getId()); tempTopic.setTags(null); t.setTopic(null); t.setTopic(tempTopic); } } p.setPublicationComments(null); // p.setPublicationComments(tempComments); p.setPublicationFavors(null); p.setFollow(null); // p.setPublicationFavors(tempFavors); p.setTags(tempTags); //设置该publication的作者 当前用户是否关注了 Follow tempfollow = followRepository.findByuserIdAndFollowUserId(userId, p.getUser().getId()); if(tempfollow!=null){ p.setFollow(tempfollow); } Map<String,Object> map=new HashedMap(); map.put("",p); return ResponseEntity.ok(p); } @RequestMapping("/favors") public ResponseEntity<Map<String,Object>> del5(@PageableDefault(value = 20, sort = {"createTime"}, direction = Sort.Direction.DESC) Pageable pageable, @RequestParam(name = "current_uid")int userId, @RequestParam(name="target_pid")int targetPublicationId) { //Page<Publication> byAll = publicationRepository.findByUserId(targetUserId,pageable); Page<PublicationFavor> byAll = publicationFavorRepository.findByPublicationIdOrderByCreateTimeDesc(targetPublicationId, pageable); /** * 处理. */ List<PublicationFavor> tempFavor = byAll.getContent(); for (PublicationFavor p:tempFavor) { p.setPublication(null); List<Follow> tempFollow = followRepository.findByUserId(userId); if(tempFollow.size()>0) { for (Follow f:tempFollow) { if(p.getUser().getId()==f.getFollowUser().getId()){ f.setUser(null); p.setFollow(f); } } } } //最外层Map Map<String,Object> map=new HashedMap(); //publications组装 //List<Publication> publications; //publications=byAll.getContent(); Map<String,List<PublicationFavor>> listMap=new HashedMap(); listMap.put("publicationfavors",tempFavor); //page :组装 Map<String,Object> pageMap=new HashedMap(); pageMap.put("number",byAll.getNumber()); pageMap.put("size",byAll.getSize()); pageMap.put("totalElements",byAll.getTotalElements()); pageMap.put("totalPages",byAll.getTotalPages()); //_links;组装 Map<String,Map<String,String>>linkMap=new HashedMap(); Map<String,String>selfMap=new HashedMap(); selfMap.put("href",""); linkMap.put("self",selfMap); map.put("_embedded",listMap); map.put("_links",linkMap); map.put("page",pageMap); return ResponseEntity.ok(map); } } <file_sep>package cn.springlogic.blog.jpa.entity; import cn.springlogic.oss.jpa.entity.File; import cn.springlogic.user.jpa.entity.User; import lombok.Data; import org.hibernate.annotations.CreationTimestamp; import javax.persistence.*; import java.util.Date; /** * Created by admin on 2017/4/18. */ @Data @Entity public class Media { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; /** * 1图片 2音频 3视频 4文件 */ private int type; private String title; private String uri; /** * 用于排序 */ private int rank; @Column(name = "create_time") @CreationTimestamp @Temporal(TemporalType.TIMESTAMP) private Date createTime; @ManyToOne(fetch=FetchType.LAZY, // 指定user属性的抓取策略 FetchType.LAZY:延迟加载 FetchType.EAGER:立即加载 targetEntity=User.class)// 指定关联的持久化类 /** 生成关联的外键列 */ @JoinColumn(name="user_id", // 外键列的列名 referencedColumnName="id") // 指定引用user表的主键列 private User user; /**该File类为 oss包下的File类*/ @ManyToOne(fetch=FetchType.LAZY, // 指定属性的抓取策略 FetchType.LAZY:延迟加载 FetchType.EAGER:立即加载 targetEntity=File.class)// 指定关联的持久化类 /** 生成关联的外键列 */ @JoinColumn(name="oss_file_id", // 外键列的列名 referencedColumnName="id") // 指定引用表的主键列 private File ossFile; } <file_sep>package cn.springlogic.blog.jpa.entity; import cn.springlogic.collection.jpa.entity.Favor; import cn.springlogic.user.jpa.entity.User; import lombok.Data; import org.hibernate.annotations.*; import javax.persistence.*; import javax.persistence.CascadeType; import javax.persistence.Entity; import java.util.*; /** * Created by admin on 2017/4/18. */ @Data @Entity public class Article { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String title; private String summary; private String content; @Column(name = "create_time") @CreationTimestamp @Temporal(TemporalType.TIMESTAMP) private Date createTime; @ManyToOne(fetch=FetchType.EAGER, // 指定user属性的抓取策略 FetchType.LAZY:延迟加载 FetchType.EAGER:立即加载 targetEntity=User.class)// 指定关联的持久化类 /** 生成关联的外键列 */ @JoinColumn(name="user_id", // 外键列的列名 referencedColumnName="id") // 指定引用user表的主键列 private User user; @ManyToMany @JoinTable(name = "article_category", joinColumns = {@JoinColumn(name = "article_id",referencedColumnName = "id")},//JoinColumns定义本方在中间表的主键映射 inverseJoinColumns = {@JoinColumn(name = "category_id",referencedColumnName = "id")})//inverseJoinColumns定义另一在中间表的主键映射 private Set<Category> categories=new HashSet<>(); @ManyToMany//(cascade = {CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REMOVE, CascadeType.REFRESH}) @Cascade(org.hibernate.annotations.CascadeType.PERSIST) @JoinTable(name = "article_media", joinColumns = {@JoinColumn(name = "article_id",referencedColumnName = "id")},//JoinColumns定义本方在中间表的主键映射 inverseJoinColumns = {@JoinColumn(name = "media_id",referencedColumnName = "id")})//inverseJoinColumns定义另一在中间表的主键映射 private List<Media> medias=new ArrayList<>(); } <file_sep>package cn.springlogic.blog.service; import cn.springlogic.blog.jpa.entity.Article; /** * Created by admin on 2017/4/24. */ public interface ArticleService { void save(Article article); } <file_sep>#spring-logic- blog ### JPA实体 - Article 文章实体类 - Category 分类 - Media 媒体资源 - BlogParam (保留,与Social组件关联) <file_sep>package cn.springlogic.blog.jpa.repository; import cn.springlogic.blog.jpa.entity.Article; import cn.springlogic.blog.jpa.entity.rest.ArticleProjection; import cn.springlogic.user.jpa.entity.User; import org.springframework.context.annotation.Configuration; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.data.rest.core.annotation.RestResource; import javax.transaction.Transactional; import java.util.List; /** * Created by admin on 2017/4/18. */ @Configuration @RepositoryRestResource(path="blog:articles",excerptProjection = ArticleProjection.class) public interface ArticleRepository extends JpaRepository<Article,Integer> { //后台用 //public Page<Article> findBycontentContainsAndIdInAndUserIdIn(@Param("content")String content,@Param("id") List<Integer> ids,@Param("userId") List<Integer>userids,Pageable pageable); /** * 条件查询 根据话题名称查找出话题. * @param topic * @param pageable * @return */ @RestResource(path = "all",rel = "all") @Query("Select distinct a from Article a,Tag t where :topic IS NULL OR t.topic.name LIKE CONCAT('%',:topic,'%') and t.publication.article.id=a.id order by a.createTime DESC") public Page<Article> findByAll(@Param("topic")String topic, Pageable pageable); // select a from Article a,Tag t where t.topic.name like %:topic% and t.publication.article.id=a.id order by a.createTime ASC /* 根据 搜索出所有的喜欢该article的用户 @Query("select a from Article a, Topic topic ,Tag t,publication p where a.id=t.publication.article.id and topic.name=?1") @RestResource(path = "a",rel = "a") public List<Article> findArticleByTopicName(@Param("name") String name); */ /* 根据 搜索出所有的喜欢该article的用户 */ /* @Query("select u from User u,Article a where u in elements(a.favors) and a.id=?1") @RestResource(path = "a",rel = "a") public List<User> findLikeUser(@Param("id")Integer id); */ /* delete from Favor l,Article a where a.id=?1 and l in elements(a.favors) and l.user.id=?2 */ /* @Transactional @Modifying // @Query("delete from Favor f,Article a where f.user.id=?1 and f in elements(a.favors) and a.id=?2") // @Query("delete from Favor f inner join Article.favors a where a.user.id=?1") // @Query("delete f from Favor f left join Article a on f in elements(a.favors) where f.user.id=?1 and a.id=?2") //取消点赞 , 根绝用户id删除favor表记录,同时根据favor表id删除article_favor中间表记录 // select f from Article a,Favor f where f.id = a.favors.id //@Query("delete f from Favor f where f in elements(select f from Favor f,Article a where f in elements(a.favors) and f.user.id=?1 and a.id=?2)") //@Query("delete f from Favor f,Article a where f in elements(a.favors) and f.user.id=?1 and a.id=?2") @Query("delete from Favor f1 where f1.id =(select f.id from Favor f,Article a where f in elements(a.favors) and f.user.id=?1 and a.id=?2)") @RestResource(path = "delete",rel = "delete") public void deleteLike(@Param("userid")int userId,@Param("articleid")int articleId); //根据用户id和文章id 查找出 该文章的该用户的favor @Query("select f from Favor f,Article a where f in elements(a.favors) and f.user.id=?1 and a.id=?2") @RestResource(path = "b",rel = "b") public Favor findFavor(@Param("userid")int userId,@Param("articleid")int articleId); @Query("select f.id from Favor f,Article a where f in elements(a.favors) and f.user.id=?1 and a.id=?2") @RestResource(path = "c",rel = "c") public Integer getFavorId(@Param("userid")int userId,@Param("articleid")int articleId); */ }
04dd6c81cccd0bd198b143286d297ce859969ca2
[ "Markdown", "Java" ]
10
Java
caztg/springlogic-blog
1c60c2c6f9736e5787cd0e0a65f91a14e2d9ae7a
440083bb1a757858f28ecc89c47d2a2d72cb92a1
refs/heads/master
<repo_name>cm-art/item-catalog<file_sep>/database_setup.py import os import sys from datetime import datetime from sqlalchemy import Column, ForeignKey, Integer, String, DateTime from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, sessionmaker Base = declarative_base() class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) email = Column(String(320), nullable=False) name = Column(String(80), nullable=False) building = Column(String(3), nullable=False) picture = Column(String(250)) class Drive(Base): __tablename__ = 'drive' serialno = Column(String(40), primary_key=True) manf = Column(String(40), nullable=False) model = Column(String(40), nullable=False) wipe_status = Column(String(10), nullable=False) wipe_start = Column(DateTime) wipe_end = Column(DateTime) user_id = Column(Integer, ForeignKey('user.id')) user = relationship(User) @property def serialize(self): """Return data in serialized format for JSON printing""" return { 'serialno': self.serialno, 'manf': self.manf, 'model': self.model, 'wipe_status': self.wipe_status, 'wipe_start': str(self.wipe_start), 'wipe_end': str(self.wipe_end), 'user_id': self.user_id, } engine = create_engine('sqlite:///drivewipe.db') Base.metadata.create_all(engine) print("Database Setup completed")<file_sep>/wipe.py from functools import wraps from flask import Flask, render_template, request, redirect, jsonify, url_for, flash # noqa from sqlalchemy import create_engine, asc from sqlalchemy.orm import sessionmaker from database_setup import Base, User, Drive from flask import session as login_session import datetime import random import string from oauth2client.client import flow_from_clientsecrets from oauth2client.client import FlowExchangeError import httplib2 import json from flask import make_response import requests app = Flask(__name__) # Application called Wipes, allows users to connect to the DrivewipeDB # and make CRUD changes and also look at the data currently in the DB. CLIENT_ID = json.loads( open('client_secrets.json', 'r').read())['web']['client_id'] APPLICATION_NAME = "Drive Wipe Database Application" # Connect to Database engine = create_engine('sqlite:///drivewipe.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() # Login required def login_required(f): @wraps(f) def login_function(*args, **kwargs): if 'user_id' not in login_session: return redirect(url_for('showLogin')) return f(*args, **kwargs) return login_function # JSON APIs to show Drivewipe Information @app.route('/api/v1/drivewipe.json') def showDriveJSON(): """Returns JSON of all HDD's in Drivewipe DB, order by date of wipe_end""" items = session.query(Drive).order_by(Drive.wipe_end.desc()) return jsonify(Drive=[i.serialize for i in items]) @app.route('/api/v1/drives/<int:u_id>/JSON') def wipeByUser(u_id): """Returns JSON of All drives wiped by user""" userWipe = session.query(Drive).filter_by(user_id = u_id) return jsonify(Drive=[i.serialize for i in userWipe]) @app.route('/api/v1/drives/<serialno>/JSON') def driveSerialno(serialno): """Returns JSON of All drives that matches serialno""" serialNo = session.query(Drive).filter_by(serialno = serialno) return jsonify(Drive=[i.serialize for i in serialNo]) # CRUD for Drives # READ, shows home and also Drives Wiped @app.route('/') @app.route('/drives/') def showDrives(): """ Shows all HDD's that have been wiped """ drives = session.query(Drive).all() items = session.query(Drive).order_by(Drive.wipe_end.desc()) count = items.count() # We're going to return two pages, public_drives is for unauthorized if 'username' not in login_session: return render_template('public_drives.html', drives=drives, items=items, count=count) else: return render_template('drivewipe.html', drives=drives, items=items, count=count) # CREATE, Add in another drive that has been wiped @app.route('/drives/new', methods=['GET', 'POST']) @login_required def newDrive(): """ Allows user to add in new drives to the database """ if request.method == 'POST': print(login_session) if 'user_id' not in login_session and 'email' in login_session: login_session['user_id'] = getUserID(login_session['email']) newDrive = Drive( serialno=request.form['serialno'], manf=request.form['manf'], model=request.form['model'], wipe_status=request.form['wipe_status'], wipe_start=request.form['wipe_start'], wipe_end=request.form['wipe_end'], user_id=login_session['user_id']) session.add(newDrive) session.commit() flash("New Drive added!", 'success') return redirect(url_for('showDrives')) else: return render_template('new_drive.html') # EDIT a Drive @app.route('/drives/<int:serialno>/edit/', methods=['GET', 'POST']) @login_required def editDrive(serialno): """Allows user to edit an existing drive status""" editedDrive = session.query( Drive).filter_by(id=serialno).one() if editedDrive.user_id != login_session['user_id']: return "<script>function myFunction() {alert('You are not authorized!')}</script><body onload='myFunction()'>" # noqa if request.method == 'POST': if request.form['serialno']: editedDrive.serialno = request.form['serialno'] flash( 'Drive Successfully Edited %s' % editedDrive.serialno, 'success') return redirect(url_for('showDrives')) else: return render_template( 'edit_drives.html', drive=editedDrive) # DELETE a category @app.route('/drives/<int:serialno>/delete/', methods=['GET', 'POST']) @login_required def deleteDrive(serialno): """Allows user to delete an existing Drive""" driveToDelete = session.query( Drive).filter_by(id=serialno).one() if driveToDelete.user_id != login_session['user_id']: return "<script>function myFunction() {alert('You are not authorized!')}</script><body onload='myFunction()'>" # noqa if request.method == 'POST': session.delete(driveToDelete) flash('%s Successfully Deleted' % driveToDelete.serialno, 'success') session.commit() return redirect( url_for('showDrive', serialno=serialno)) else: return render_template( 'delete_drive.html', drive=driveToDelete) # Login Handling # Start by creating anti-forgery token. @app.route('/login') def showLogin(): state = ''.join( random.choice( string.ascii_uppercase + string.digits) for x in range(32)) login_session['state'] = state return render_template('login.html', STATE=state) # Google auth call for token. @app.route('/gconnect', methods=['POST']) def gconnect(): # check state token if request.args.get('state') != login_session['state']: response = make_response(json.dumps('Invalid state parameter.'), 401) response.headers['Content-Type'] = 'application/json' return response code = request.data # OAuth flow try: oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='') oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(code) except FlowExchangeError: response = make_response( json.dumps('Failed to upgrade the authorization code.'), 401) response.headers['Content-Type'] = 'application/json' return response # Verify token is valid. access_token = credentials.access_token url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % access_token) h = httplib2.Http() result = json.loads(h.request(url, 'GET')[1]) if result.get('error') is not None: response = make_response(json.dumps(result.get('error')), 500) response.headers['Content-Type'] = 'application/json' return response # Verify the user's token matches them gplus_id = credentials.id_token['sub'] if result['user_id'] != gplus_id: response = make_response( json.dumps("Token's user ID doesn't match given user ID."), 401) response.headers['Content-Type'] = 'application/json' return response # Verify the token is valid for this app if result['issued_to'] != CLIENT_ID: response = make_response( json.dumps("Token's client ID does not match app's."), 401) print("Token's client ID does not match app's.") response.headers['Content-Type'] = 'application/json' return response # Check if the user is already logged in and store token stored_credentials = login_session.get('credentials') stored_gplus_id = login_session.get('gplus_id') if stored_credentials is not None and gplus_id == stored_gplus_id: response = make_response( json.dumps('Current user is already connected.'), 200) response.headers['Content-Type'] = 'application/json' return response login_session['access_token'] = credentials.to_json() login_session['gplus_id'] = gplus_id # Collect user data userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo" params = {'access_token': credentials.access_token, 'alt': 'json'} answer = requests.get(userinfo_url, params=params) data = answer.json() login_session['provider'] = 'google' login_session['username'] = data['name'] login_session['picture'] = data['picture'] login_session['email'] = data['email'] # Check if user exists if not create them. user_id = getUserID(login_session['email']) if not user_id: user_id = createUser(login_session) login_session['user_id'] = user_id output = '' output += '<h1>Hello , ' output += login_session['username'] output += '!, welcome to the drivewipe db!</h1>' output += '<img src="' output += login_session['picture'] output += ' " style = "width: 300px; height: 300px;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;"> ' # noqa flash("you are now logged in as %s" % login_session['username'], 'success') print("done!") return output # Google Logout @app.route('/glogout') def glogout(): # check connection stauts before logging out credentials = login_session.get('credentials') if credentials is None: response = make_response( json.dumps('Current user not connected.'), 401) response.headers['Content-type'] = 'application/json' return response # HTTP request to revoke access token access_token = credentials.access_token url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token h = httplib2.Http() result = h.request(url, 'GET')[0] if result['status'] == '200': # delete the user's data del login_session['credentials'] del login_session['gplus_id'] del login_session['username'] del login_session['email'] del login_session['picture'] response = make_response(json.dumps('Successfully disconnected.'), 200) response.headers['Content-Type'] = 'application/json' return response else: # error if token fails to be revoked! response = make_response( json.dumps('Failed to revoke token for given user.'), 400) response.headers['Content-Type'] = 'application/json' return response # User helper functions def getUserID(email): try: user = session.query(User).filter_by(email=email).one() return user.id except: return None def getUserInfo(user_id): user = session.query(User).filter_by(id=user_id).one() return user def createUser(login_session): newUser = User( name=login_session['username'], email=login_session['email'], picture=login_session['picture']) session.add(newUser) session.commit() user = session.query(User).filter_by(email=login_session['email']).one() return user.id if __name__ == '__main__': app.secret_key = 'super_secret_key' app.debug = True app.run(host='0.0.0.0', port=8000)<file_sep>/db_populate.py from datetime import datetime from sqlalchemy import create_engine from database_setup import Base, User, Drive from sqlalchemy.orm import relationship, sessionmaker engine = create_engine('sqlite:///drivewipe.db') DBSession = sessionmaker(bind=engine) session = DBSession() myFirstUser = User( name="<NAME>", email="<EMAIL>", building="bf2") session.add(myFirstUser) session.commit() myFirstUser = User( name="<NAME>", email="<EMAIL>", building="bf1") session.add(myFirstUser) session.commit() myFirstDrive = Drive( serialno="S2Z5NY0HC12345", model="SM0256G", manf="Apple", wipe_status="Dirty", wipe_start=datetime.now(), wipe_end=datetime.now(), user_id="1") session.add(myFirstDrive) session.commit() myFirstDrive = Drive( serialno="S2Z5NY0HC54321", model="SM0256G", manf="Apple", wipe_status="Dirty", wipe_start=datetime.now(), wipe_end=datetime.now(), user_id="2") session.add(myFirstDrive) session.commit()<file_sep>/README.md # item-catalog Udacity Item Catalog Application
0809ace485bbc604eb8b879ce2060580d4c9ae75
[ "Markdown", "Python" ]
4
Python
cm-art/item-catalog
09695877120f93f9a646de124a1f6ec8ddb29b20
97c29855d8ac175b4f7c208cd8ea5dab22d1283b
refs/heads/master
<file_sep><?php /** * Created by PhpStorm. * User: coffeekizoku * Date: 2017/8/18 * Time: 上午11:18 */ namespace SimpleShop\Brand\Repositories; use SimpleShop\Brand\Models\ShopBrand; use SimpleShop\Repositories\Eloquent\Repository; class BrandRepository extends Repository { /** * Specify Model class name * * @return mixed */ public function model() { return ShopBrand::class; } }<file_sep><?php /** * Created by PhpStorm. * User: coffee * Date: 2017/8/17 * Time: 上午12:58 */ namespace SimpleShop\Brand\Repositories; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use SimpleShop\Repositories\Contracts\RepositoryInterface as Repository; use SimpleShop\Repositories\Criteria\Criteria; class Search extends Criteria { /** * @var array */ private $search; /** * Search constructor. * * @param array $search */ public function __construct(array $search) { $this->search = $search; } /** * @param Model|Builder $model * @param Repository $repository * * @return mixed */ public function apply($model, Repository $repository) { if (isset($this->search['name'])) { $model = $model->where('name', 'like', "%{$this->search['name']}%"); } return $model; } }<file_sep><?php /** * Created by PhpStorm. * User: coffeekizoku * Date: 2017/8/18 * Time: 上午11:13 */ namespace SimpleShop\Brand; use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Illuminate\Database\Eloquent\Model; use SimpleShop\Brand\Contracts\AbstractBrand; use SimpleShop\Brand\Contracts\Brand; use SimpleShop\Brand\Repositories\BrandRepository; use SimpleShop\Brand\Repositories\Order; use SimpleShop\Brand\Repositories\Search; class BrandImpl extends AbstractBrand { /** * 获取品牌列表 * * @param array $search * @param int $limit * @param array $columns * @param array $order * @param int $page * * @return LengthAwarePaginator */ public function getList( array $search = [], int $limit = 20, array $columns = ["*"], array $order = ['id' => 'desc'], int $page = 1 ): LengthAwarePaginator { return $this->repo ->pushCriteria(new Search($search)) ->pushCriteria(new Order($order)) ->paginate($limit, $columns, $page); } /** * @param $id * * @return Model */ public function show($id): Model { return $this->repo->find($id); } /** * @param $id * * @return mixed */ public function destroy($id) { return $this->repo->delete($id); } /** * @param array $data * * @return mixed */ public function create(array $data) { $data['cover'] = json_encode($data['cover']); return $this->repo->create($data); } /** * @param $id * @param array $data * * @return mixed */ public function update($id, array $data) { $data['cover'] = json_encode($data['cover']); return $this->repo->update($id,$data); } }<file_sep><?php namespace SimpleShop\Brand; use Illuminate\Support\ServiceProvider; use SimpleShop\Brand\Contracts\Brand; class SimpleShopBrandServiceProvider extends ServiceProvider { /** * 是否延迟加载 * * @var bool */ public $defer = true; /** * Bootstrap the application services. * * @return void */ public function boot() { // $this->loadMigrationsFrom(dirname(dirname(__FILE__)) . '/migrations'); } /** * Register the application services. * * @return void */ public function register() { $this->app->singleton(Brand::class, BrandImpl::class); } /** * 获取由提供者提供的服务. * * @return array */ public function provides() { return [ Brand::class, ]; } } <file_sep><?php /** * Created by PhpStorm. * User: coffeekizoku * Date: 2017/8/23 * Time: 上午10:22 */ namespace SimpleShop\Brand\Contracts; use SimpleShop\Brand\Repositories\BrandRepository; abstract class AbstractBrand implements Brand { protected $repo; public function __construct(BrandRepository $repository) { $this->repo = $repository; } }<file_sep><?php /** * Created by PhpStorm. * User: coffeekizoku * Date: 2017/8/23 * Time: 上午9:49 */ namespace SimpleShop\Brand\Https\Controllers; use SimpleShop\Commons\Https\Controllers\Controller; use SimpleShop\Brand\Contracts\Brand; use SimpleShop\Brand\Https\Requests\Api\SubmitRequest; use Illuminate\Http\Request; use SimpleShop\Commons\Utils\ReturnJson; class CommodityBrandController extends Controller { private $service; public function __construct(Brand $commodityBrandService) { $this->service = $commodityBrandService; } /** * 列表 * * @param Request $request * @return mixed */ public function index(Request $request) { $this->getRouteParam($request); $data = $this->service->getList($request->all(), $this->routeParam['limit'], $columns = ["*"], [$this->routeParam['sort'] => $this->routeParam['order']], $this->routeParam['page'] ); return ReturnJson::paginate($data); } /** * 保存新品牌的方法 * * @param SubmitRequest $request * * @return \Illuminate\Http\JsonResponse */ public function store(SubmitRequest $request) { $this->service->create($request->all()); return ReturnJson::success(); } /** * 修改品牌的方法 * * @param $id * @param SubmitRequest $request * * @return \Illuminate\Http\JsonResponse */ public function update($id, SubmitRequest $request) { $this->service->update($id, $request->all()); return ReturnJson::success(); } /** * 获取详情 * * @param $id * @return \Illuminate\Http\JsonResponse */ public function detail($id) { $data = $this->service->show($id); return ReturnJson::success($data); } /** * 删除品牌 * * @param $id * * @return \Illuminate\Http\JsonResponse */ public function destroy($id) { $this->service->destroy($id); return ReturnJson::success(); } }<file_sep><?php /** * Created by PhpStorm. * User: coffeekizoku * Date: 2017/8/18 * Time: 上午11:14 */ namespace SimpleShop\Brand\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class ShopBrand extends Model { use SoftDeletes; protected $table = "shop_brands"; /** * 主键 */ protected $primaryKey = "id"; /** * 黑名单列表 * * @var array */ protected $fillable = [ 'sort', 'name', 'description', 'cover' ]; /** * 在数组中想要隐藏的属性。 * * @var array */ protected $hidden = ['deleted_at']; /** * 封面字段的访问器 * * @param $value * * @return mixed */ public function getCoverAttribute($value) { return json_decode($value, true); } }<file_sep># laravel-shop-brand laravel商城的品牌 <file_sep><?php /** * Created by PhpStorm. * User: coffeekizoku * Date: 2017/8/18 * Time: 上午10:27 */ namespace SimpleShop\Brand\Contracts; use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Illuminate\Database\Eloquent\Model; interface Brand { /** * 获取品牌列表 * * @param array $search * @param int $limit * @param array $columns * @param array $order * @param int $page * * @return LengthAwarePaginator */ public function getList( array $search = [], int $limit = 20, array $columns = ["*"], array $order = ['id' => 'desc'], int $page = 1 ) :LengthAwarePaginator; /** * @param $id * * @return Model */ public function show($id) :Model; /** * @param $id * * @return mixed */ public function destroy($id); /** * @param array $data * * @return mixed */ public function create(array $data); /** * @param $id * @param array $data * * @return mixed */ public function update($id, array $data); }<file_sep><?php /** * Created by PhpStorm. * User: coffee * Date: 2017/8/17 * Time: 上午12:59 */ namespace SimpleShop\Brand\Repositories; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use SimpleShop\Repositories\Contracts\RepositoryInterface as Repository; use SimpleShop\Repositories\Criteria\Criteria; class Order extends Criteria { /** * @var array */ private $order; /** * Order constructor. * * @param array $order */ public function __construct(array $order) { $this->order = $order; } /** * @param Model|Builder $model * @param Repository $repository * * @return mixed */ public function apply($model, Repository $repository) { foreach ($this->order as $order => $by) { $model = $model->orderBy($order, $by); } return $model; } }<file_sep><?php /** * Created by PhpStorm. * User: coffeekizoku * Date: 2017/8/23 * Time: 上午10:14 */ namespace SimpleShop\Brand\Https\Requests\Api; use SimpleShop\Commons\Requests\Request; class SubmitRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required|string|between:1,20', ]; } /** * 获取已定义验证规则的错误消息。 * * @return array */ public function messages() { return [ 'name.required' => '品牌名字必须填写', 'name.between' => '品牌名字字数在1-20之间', ]; } }
f6f5955390895411bdf73c63f84490a33336b703
[ "Markdown", "PHP" ]
11
PHP
wangzhoudong/laravel-shop-brand
ab83bd48387a0fc2f700ac783165efd318b225d7
496bbe49368f99ffc75b17fb5a3e2e05d98df3dc
refs/heads/master
<file_sep>import urllib2, json, time, sys, getopt, datetime from dateutil import parser loop_interval_secs = 10 now = datetime.datetime.now().replace(tzinfo=None) last_time = now event_time = now found_events = False print '' print 'Ploggly started' print 'Polling for events every ' + str(loop_interval_secs) + ' seconds.' print '' def call_loggly(): print 'checking for new events...' global last_time, event_time, found_events username = '<loggly_un>' password = '<<PASSWORD>>' url = 'https://<loggly_subdomain>.loggly.com/api/search?q=*&from=NOW-5MINUTES' p = urllib2.HTTPPasswordMgrWithDefaultRealm() p.add_password(None, url, username, password) handler = urllib2.HTTPBasicAuthHandler(p) opener = urllib2.build_opener(handler) urllib2.install_opener(opener) page = urllib2.urlopen(url) json_data = json.load(page) found_events = False for r in json_data["data"]: if r["inputname"] in ('<loggly_input_name>'): if "datetime" in r["json"]: event_time = parser.parse(r["json"]["datetime"]).replace(tzinfo=None) #print str(event_time) + ' > ' + str(last_time) if "host" in r["json"] and event_time > last_time: found_events = True print '' print '----------------------------------------------------------------' print '|' + r["json"]["datetime"] + ' | ' + r["inputname"] + ' | ' + r["ip"] + '|' print 'Message: ' + r["json"]["message"] print 'level: ' + r["json"]["level"] print 'host: ' + r["json"]["host"] print 'datetime: ' + r["json"]["datetime"] print '----------------------------------------------------------------' if found_events == True: last_time = datetime.datetime.now().replace(tzinfo=None) return True # do ur work here, but not for long while True: call_loggly() time.sleep(loop_interval_secs) <file_sep># ploggly Allows you to use the command line interface for monitoring inputs on #loggly. This is still in the very early stages, but it works if you customize the script a bit.
88b285a487253105fd8eec55712a2bc5ccdb50fd
[ "Markdown", "Python" ]
2
Python
fourq/ploggly
a0af017fba37bcf807f8b5392c40f635cb033d12
cd4a8c68aac3822ff1cc766ebb44dc5970dae33f
refs/heads/main
<file_sep>package com.qa.pups.other; public class Puppy { private String name; private String breed; private int age; private int cuteness; public Puppy(String name, String breed, int age, int cuteness) { super(); this.name = name; this.breed = breed; this.age = age; this.cuteness = cuteness; } public Puppy() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBreed() { return breed; } public void setBreed(String breed) { this.breed = breed; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getCuteness() { return cuteness; } public void setCuteness(int cuteness) { this.cuteness = cuteness; } @Override public String toString() { return "Puppy [name=" + name + ", breed=" + breed + ", age=" + age + ", cuteness=" + cuteness + "]"; } } <file_sep>package com.qa.service; import java.util.List; import com.qa.pups.other.Puppy; public interface PuppyService { public void createPuppy(Puppy puppy); public List<Puppy> getAllPuppies(); public Puppy getPuppy(int id); public Puppy replacePuppy(int id, Puppy newPuppy); public String deletePuppy(int id); }
ff6932cb026dce63dfc98874fb35e74cdc07cbae
[ "Java" ]
2
Java
LilyFinn/ClassWork
c0dcfcbe619dca39210a5d08fdf1ecd66c020436
844e7106de082aeffa7588ed30aa075a8aa6ae58
refs/heads/master
<repo_name>DionysiosB/VariousSnippets<file_sep>/uniquePermutations.cpp #include <cstdio> #include <iostream> #include <cstring> #include <algorithm> int main(){ std::string input = "aac"; int length = input.size(); char * array = new char[length]; for(int k = 0; k < length; k++){array[k] = input[k];} std::sort(array, array + length); do{ for(int k = 0; k < length; k++){printf("%c", array[k]);} puts(""); } while(std::next_permutation(array, array + length)); return 0; } <file_sep>/MakingChange.cpp #include <iostream> #include <vector> long numCoins(long amount, std::vector<long> denom){ std::vector<long> numCoins(amount + 1); for(long p = 0; p <= amount; p++){numCoins[p] = p;} for(long p = 1; p <= amount; p++){ for(long c = 0; c < denom.size(); c++){ long currentDen = denom[c]; if(currentDen > p){break;} numCoins[p] = std::min(numCoins[p], 1 + numCoins[p - currentDen]); } } //for(long p = 1; p <= amount; p++){std::cout << p << " ---> " << numCoins[p] << std::endl;}; return numCoins[amount]; } int main(){ const long N(7); std::vector<long> coinValues(N); coinValues[0] = 1; coinValues[1] = 2; coinValues[2] = 5; coinValues[3] = 10; coinValues[4] = 20; coinValues[5] = 50; coinValues[6] = 100; int test; test = 100; std::cout << test << " ---> " << numCoins(test, coinValues) << std::endl; test = 97; std::cout << test << " ---> " << numCoins(test, coinValues) << std::endl; test = 23; std::cout << test << " ---> " << numCoins(test, coinValues) << std::endl; test = 17; std::cout << test << " ---> " << numCoins(test, coinValues) << std::endl; return 0; } <file_sep>/MyInsert.R function(x, where, what){ if(where < 1){return(c(what,x))} if(where > length(x)){return(c(x,what))} return( c(x[1:(where-1)],what,x[where:length(x)]) ) }<file_sep>/WeekDay.R weekDay = function(day,month,year){ k = day y = year %% 100 c = year %/% 100 m = (month - 2); if(m<0){m = m+12} f = ( as.integer(2.6*m -0.2) + k + y + as.integer(y/4) + as.integer(c/4) - 2*c) %% 7 if(f == 0){f = 7}; dayNames = c("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday") return(dayNames[f]) }<file_sep>/NumberOfWaysToScorePoints.cpp #include <iostream> #include <vector> #include <algorithm> int main(){ int s, n; std::cin >> s >> n; std::vector<int> steps; for(int p = 0; p < n; p++){ int x; std::cin >> x; if(x > 0){steps.push_back(x);} } sort(steps.begin(), steps.end()); std::vector<long> dp(s + 1, 0); dp[0] = 1; for(int p = 1; p <= s; p++){ for(int k = 0; k < n && steps[k] <= p; k++){dp[p] += dp[p - steps[k]];} } for(int p = 0; p <= s; p++){std::cout << dp[p] << " ";}; std::cout << std::endl; std::cout << dp[s] << std::endl; return 0; } <file_sep>/DiceThrowWays.cpp #include <iostream> #include <vector> int main(){ int D, S, m; std::cin >> D >> S >> m; std::vector<std::vector<long> > ways(D + 1, std::vector<long>(S + 1)); for(int p = 1; p <= m && p <= S; p++){ways[1][p] = 1;} for(int dice = 2; dice <= D; dice++){ for(int sum = 1; sum <= S; sum++){ for(int res = 1; res <= m && res < sum; res++){ways[dice][sum] += ways[dice - 1][sum - res];} } } for(int dice = 0; dice <= D; dice++){ for(int sum = 0; sum <= S; sum++){std::cout << ways[dice][sum] << "\t";} std::cout << std::endl; } return 0; } <file_sep>/Tree.cpp #include <cstdio> #include <iostream> #include <vector> #include <deque> struct node{ int data; node *left; node *right; }; std::vector<int> rearrange(std::vector<int> v){ if(v.size() <= 1){return v;} sort(v.begin(), v.end()); std::vector<int> res; int m = (v.size() - 1)/ 2; res.push_back(v[m]); std::vector<int> vleft(v.begin(), v.begin() + m); vleft = rearrange(vleft); std::vector<int> vright(v.begin() + m + 1, v.end()); vright = rearrange(vright); res.insert(res.end(), vleft.begin(), vleft.end()); res.insert(res.end(), vright.begin(), vright.end()); return res; } class Tree{ public: Tree(){root = NULL;} ~Tree(); void addData(int x){addData(root, x);} void addData(node * start, int x){ if(start == NULL){ node *p = new node; p->data = x; p->left = p->right = NULL; root = p; } else if(x < start->data){ if(start->left == NULL){node *p = new node; p->data = x; p->left = p->right = NULL; start->left = p;} else{addData(start->left, x);} } else if(x > start->data){ if(start->right == NULL){node *p = new node; p->data = x; p->left = p->right = NULL; start->right = p;} else{addData(start->right, x);} } } void printDFS(){printDFS(root);} void printDFS(node * start){ if(start == NULL){return;} printf("%d _ ", start->data); printDFS(start->left); printDFS(start->right); } void printBFS(){ if(root == NULL){puts("Empty Stack using BFS");} std::deque<node> q; q.push_front(*root); while(!q.empty()){ node current = q.back(); q.pop_back(); printf("%d = ", current.data); if(current.left != NULL){q.push_front(*(current.left));} if(current.right != NULL){q.push_front(*(current.right));} } } int depth(){return depth(root);} int depth(node *start){ if(start == NULL){return 0;} return 1 + std::max(depth(start->left), depth(start->right)); } int minDepth(){return minDepth(root);} int minDepth(node *start){ if(start == NULL){return 0;} return 1 + std::min(minDepth(start->left), minDepth(start->right)); } int maxDepth(){return maxDepth(root);} int maxDepth(node *start){ if(start == NULL){return 0;} return 1 + std::max(maxDepth(start->left), maxDepth(start->right)); } bool isBalanced(){ bool res = (this->maxDepth() - this->minDepth() <= 1) ? true : false; puts(res ? "Balanced Tree" : "Not balanced tree"); return res; } private: node *root; }; int main(){ std::vector<int> v; v.push_back(5); v.push_back(3); v.push_back(1); v.push_back(7); v.push_back(9); v.push_back(4); v.push_back(2); v.push_back(8); v.push_back(0); v.push_back(11); v.push_back(6); v.push_back(10); v.push_back(12); Tree *tree = new Tree(); for(size_t p = 0; p < v.size(); p++){tree->addData(v[p]);} tree->printDFS(); puts(""); tree->printBFS(); puts(""); printf("Depth of tree is: %d\n", tree->depth()); tree->isBalanced(); std::vector<int> test; int A = 15; for(int p = 0; p < A; p++){test.push_back(A - p);} test = rearrange(test); for(int p = 0; p < A; p++){printf("%d ! ", test[p]);}; puts(""); } <file_sep>/MatrixOperation2.R matrixOperationA = function(x){ output = x * (2*(x %% 2 == 1) + (x %% 2 == 0)) return(output) } <file_sep>/CheckPangram.cpp #include <cstdio> #include <iostream> #include <vector> int main(){ const int N = 26; std::string s; getline(std::cin, s); std::vector<bool> check(N, 0); for(size_t p = 0; p < s.size(); p++){check[s[p] - 'a'] = 1;} bool flag(true); for(size_t p = 0; p < N; p++){if(check[p] == 0){flag = 0; break;}} puts(flag ? "YES" : "NO"); bool nostruct(1); for(int p = 0; p < N; p++){ bool hasLetter(0); for(size_t q = 0; q < s.size(); q++){if(s[q] == 'a' + p){hasLetter = 1; break;}} if(!hasLetter){nostruct = 0; break;} } puts(nostruct ? "YES" : "NO"); return 0; } <file_sep>/LongestBitonicSequence.cpp #include <iostream> #include <vector> int main(){ long n; std::cin >> n; std::vector<long> v(n); for(long p = 0; p < n; p++){std::cin >> v[p];} std::vector<long> lis(n, 1); std::vector<long> lds(n, 1); for(int p = 1; p < n; p++){ for(int q = 0; q < p; q++){ if(v[q] < v[p] && lis[p] < lis[q] + 1){lis[p] = lis[q] + 1;} if(v[q] > v[p] && lds[p] < lds[q] + 1){lds[p] = lds[q] + 1;} } } int maxLen(0); for(int p = 1; p < n; p++){ long candidate = lis[p] + lds[p] - 1; maxLen = (maxLen < candidate) ? candidate : maxLen; } std::cout << maxLen << std::endl; return 0; } <file_sep>/stringPowerset.cpp #include <cstdio> #include <vector> #include <iostream> #include <string> std::vector<std::string> binaryCombinations(int n, std::vector<std::string> inputVector){ if(n == 0){return inputVector;} else if(inputVector.size() == 0){ std::vector<std::string> tempVector; tempVector.push_back("0"); tempVector.push_back("1"); std::vector<std::string> outputVector = binaryCombinations(n - 1, tempVector); return outputVector; } else{ std::vector<std::string> newVector; for(int k = 0; k < inputVector.size(); k++){newVector.push_back("0" + inputVector[k]);} for(int k = 0; k < inputVector.size(); k++){newVector.push_back("1" + inputVector[k]);} std::vector<std::string> outputVector = binaryCombinations(n - 1, newVector); return outputVector; } } int main(){ std::vector<std::string> testInput; std::string combinationsInput = "abcde"; std::vector<std::string> binaryVector = binaryCombinations(combinationsInput.size(),testInput); for(int k = 0; k < binaryVector.size(); k++){std::cout << binaryVector[k] << std::endl;} for(int k = 0; k < binaryVector.size(); k++){ std::string currentString = binaryVector[k]; for(int m = 0; m < combinationsInput.size(); m++){if(currentString[m] == '1'){std::cout << combinationsInput[m];}} std::cout << std::endl; } return 0; } <file_sep>/RemoveDuplicates.cpp #include <iostream> int main(){ std::string s; getline(std::cin, s); long x(1); for(int p = 0; p < s.size(); p++){ if(s[p] != s[p - 1]){s[x++] = s[p];} } s = s.substr(0, x); std::cout << s << std::endl; return 0; } <file_sep>/Knapsack-binary.cpp #include <cstdio> #include <iostream> #include <vector> int main(){ //Input //First Line: capacity, and number of items //Subsequent n lines: weight(w) and value (v) of each item long capacity, numItems; std::cin >> capacity >> numItems; std::vector<std::pair<long, long> > itemVec(numItems); for(int p = 0; p < numItems; p++){ long weight, value; std::cin >> weight >> value; itemVec[p] = std::pair<long, long>(weight, value); } std::vector<std::vector<std::pair<long, long> > > matrix(numItems, std::vector<std::pair<long, long> >(capacity + 1, std::pair<long, long>(0, -1))); //Row 0, corresponding to item 0 - no previous item; for(long cap = 1; cap <= capacity; cap++){ matrix[0][cap] = std::pair<long, long>(0, 0); if(itemVec[0].first <= cap){matrix[0][cap] = std::pair<long, long>(itemVec[0].second, 1);} } for(long cap = 1; cap <= capacity; cap++){ for(long i = 1; i < numItems; i++){ long weight = itemVec[i].first; long value = itemVec[i].second; if(i == 0 && weight <= cap){matrix[0][cap] = std::pair<long, long>(value, 1);} else if(i > 0){ matrix[i][cap] = std::pair<long, long>(matrix[i - 1][cap].first, 0); if(weight <= cap && matrix[i - 1][cap - weight].first + value > matrix[i][cap].first){matrix[i][cap] = std::pair<long, long>(matrix[i - 1][cap - weight].first + value, 1);} } } } std::cout << "\nMaximum Value: " << matrix[numItems - 1][capacity].first << std::endl << std::endl; //Rows correspond to items, and columns to capacity; for(long i = 0; i < numItems; i++){ std::cout << i << "**\t"; for(long cap = 0; cap <= capacity; cap++){std::cout << matrix[i][cap].first << "\t";} std::cout << std::endl; } std::cout << std::endl << std::endl; long remCap = capacity; std::vector<long> includedItems; for(long p = numItems - 1; p >= 0; p--){ if(matrix[p][remCap].second > 0){ includedItems.push_back(p); remCap -= itemVec[p].first; } } for(long p = includedItems.size() - 1; p >= 0; p--){std::cout << includedItems[p] << "\t";}; puts(""); return 0; } <file_sep>/FindRuns.R findRuns = function(x , n){ output = c(); for(k in 1:(length(x)-n+1) ){if( all(x[k:(k+n-1)] == 1) ){output = c(output,k);}} return(output) }<file_sep>/CountNumberOfTreesPreorder.cpp #include <iostream> #include <vector> int main(){ int n; std::cin >> n; std::vector<long> count(n + 1, 0); count[0] = 1; for(int p = 1; p <= n; p++){ for(int q = 0; q < p; q++){count[p] += count[q] * count[p - 1 - q];} } for(int p = 0; p <= n; p++){std::cout << count[p] << std::endl;} return 0; } <file_sep>/VectorOperation.R vectorOperation = function(x){ output = (x<0)*(x^2+2*x+3) + (x >= 0 & x < 2)*(x+3) + (x >= 2)*(x^2 + 4*x - 7) return(output) }<file_sep>/MoveAllZerosToEnd.cpp #include <iostream> #include <vector> int main(){ int n; std::cin >> n; std::vector<int> a(n); for(int p = 0; p < n; p++){std::cin >> a[p];} int nextZero(n - 1); while(a[nextZero] == 0){--nextZero;} for(int p = 0; p < n && p < nextZero; p++){ if(a[p] != 0){continue;} int temp = a[nextZero]; a[nextZero] = 0; a[p] = temp; --nextZero; } for(int p = 0; p < n; p++){std::cout << a[p] << " ";}; std::cout << std::endl; return 0; } <file_sep>/MatchingBrackets.cpp #include <cstdio> #include <iostream> #include <vector> int main(){ int t; scanf("%d\n", &t); while(t--){ std::string s; getline(std::cin, s); int correct = 1; std::vector<char> brackets; for(int p = 0; p < s.size(); p++){ if(s[p] == '(' || s[p] == '[' || s[p] == '{' || s[p] == '<'){brackets.push_back(s[p]);} else if(s[p] == ')'){if(brackets.back() == '('){brackets.pop_back();} else{correct = 0; break;}} else if(s[p] == ']'){if(brackets.back() == '['){brackets.pop_back();} else{correct = 0; break;}} else if(s[p] == '}'){if(brackets.back() == '{'){brackets.pop_back();} else{correct = 0; break;}} else if(s[p] == '>'){if(brackets.back() == '<'){brackets.pop_back();} else{correct = 0; break;}} } if(brackets.size() > 0){correct = 0;} std::cout << correct << " "; } std::cout << std::endl; return 0; } <file_sep>/AutocorrelationLag.R autocorrelationLag = function(x,lag){ N = length(x) xbar = mean(x); var = sum( (x - xbar)^2) first = x[1:(N-lag)] - xbar second = x[(1+lag):N] - xbar return( sum(first * second)/var) }<file_sep>/Stack.cpp #include <cstdio> #include <cstdlib> class Stack{ struct node{ int data; node *next; }; public: Stack(){ head = NULL; } ~Stack(){}; void push(int x){ node *p = new node; p->data = x; p->next = head; head = p; printf("Added a new node with value %d\n", x); } int pop(){ if(head == NULL){puts("Empty list!"); return -1;} int res = head->data; printf("Removing element with value %d\n", res); node *rem = head; head = head->next; free(rem); return res; } void print(){ if(head == NULL){puts("Empty Stack!"); return;} node *index = head; while(index != NULL){ printf("%d\t", index->data); index = index->next; } puts(""); } void addToEnd(int x){ if(head == NULL){ node *p = new node; p->data = x; p->next = NULL; head = p; printf("Added a new head with value %d\n", x); return; } node *index = head; while(index->next != NULL){index = index->next;} node *p = new node; p->data = x; p->next = NULL; index->next = p; printf("Added a new node at the tail of the stack with value %d\n", x); return; } void removeElement(int x){ if(head == NULL){puts("Empty stack, cannot remove element!"); return;} if(head->data == x){ node *p = head; head = head->next; free(p); printf("Removed element with value %d, which happened to be the head\n", x); return; } node *p = head; while(p != NULL && p->next != NULL && p->next->data != x){p = p->next;} if(p == NULL || p->next == NULL){printf("Did not find element with value %d in the list, doing nothing\n", x); return;} node *toRemove = p->next; p->next = toRemove->next; free(toRemove); printf("Removed the first element with value %d from the list\n", x); return; } void erase(){ while(head != NULL){this->pop();} puts("Removed all elements from the stack;"); } private: node *head = NULL; }; int main(){ Stack *stack = new Stack(); int n = 11; for(int p = 0; p < n; p++){stack->push(p);} return 0; } <file_sep>/staticVariable.cpp #include <cstdio> #include <vector> #include <iostream> #include <string> class user{ private: int id; static int next_id; public: user(){id = user::next_id++;} void printId(){std::cout << this->id << std::endl;} }; int user::next_id = 0; int main(){ user first, second, third; first.printId(); second.printId(); third.printId(); return 0; } <file_sep>/externalProduct.cpp #include <cstdio> #include <vector> #include <iostream> #include <string> std::vector<std::string> generateCombinations(std::vector<std::string> inputVector){ if(inputVector.size() == 0){ std::vector<std::string> output; output.push_back(""); return output; } else if (inputVector.size() == 1){ std::vector<std::string> output; std::string currentString = inputVector[0]; for(int n = 0; n < currentString.size(); n++){output.push_back(currentString.substr(n,1));} return output; } else if(inputVector.size() > 1){ std::vector<std::string> output; std::string currentString = inputVector.back(); inputVector.pop_back(); std::vector<std::string> previousOutput = generateCombinations(inputVector); for(int k = 0; k < currentString.size(); k++){ for(int m = 0; m < previousOutput.size(); m++){ output.push_back(previousOutput[m] + currentString[k]); } } return output; } std::vector<std::string> dummy; return dummy; } int main(){ std::string A = "abc"; std::string B = "d"; std::string C = "gh"; std::string D = "xyz"; std::vector<std::string> testInput; testInput.push_back(A); testInput.push_back(B); testInput.push_back(C); testInput.push_back(D); std::vector<std::string> testOutput = generateCombinations(testInput); for(int k = 0; k < testOutput.size(); k++){std::cout << testOutput[k] << std::endl;} return 0; } <file_sep>/UberBridge.cpp #include <iostream> int main(){ std::string s; getline(std::cin, s); int k; std::cin >> k; int left(0), right(0); int l(0), maxLen(0), rem(k); for(int r = 0; r < s.size(); r++){ if(s[r] == 'W'){--rem;} while(l <= r && rem < 0){if(s[l] == 'W'){++rem;}; ++l;} if(maxLen < r - l + 1){left = l; right = r; maxLen = right - left + 1;} } std::cout << maxLen << std::endl; for(int p = left; p <= right; p++){if(s[p] == 'W'){std::cout << (p + 1) << " ";}} return 0; } <file_sep>/ReplaceSpaces.cpp #include <iostream> int main(){ std::string s; getline(std::cin, s); std::string r(""); for(size_t p = 0; p < s.size(); p++){ if(s[p] != ' '){r += s[p];} else{r += "%20";} } std::cout << r << std::endl; return 0; } <file_sep>/LongestIncreasingSubsequence.cpp #include <iostream> #include <vector> int lis(std::vector<long> v){ std::vector<long> length(v.size(), 1); long res(0); for(long p = 1; p < v.size(); p++){ for(long q = 0; q < p; q++){ if(v[q] >= v[p]){continue;} length[p] = std::max(length[p], length[q] + 1); } res = std::max(res, length[p]); } return res; } int main(){ long n(100); std::vector<long> array(n); for(int p = 0; p < n; p++){array[p] = p;}; std::cout << lis(array) << std::endl; for(int p = 0; p < n; p++){array[p] = n - p;}; std::cout << lis(array) << std::endl; for(int p = 0; p < n; p++){array[p] = p % 5;}; std::cout << lis(array) << std::endl; return 0; } <file_sep>/maxSubarray.cpp #include <iostream> #include <cstdio> #include <vector> int maxSum(std::vector<int> const & input){ int maxSoFar(input[0]), maxEndingHere(input[0]); size_t tempStart(0),candidateBegin(0),candidateEnd(0); for(size_t i = 1; i < input.size(); i++){ if(maxEndingHere < 0){maxEndingHere = input[i]; tempStart = i;} else{maxEndingHere += input[i];} if(maxEndingHere >= maxSoFar){maxSoFar = maxEndingHere; candidateBegin = tempStart; candidateEnd = i;} } std::cout << candidateBegin << " " << candidateEnd << std::endl; return maxSoFar ; } int main(){ std::vector<int> test({1,2,3,-10,7,8,9,-11}); std::cout << maxSum(test) << std::endl; return 0; } <file_sep>/MyFib.R function(N){ if(N < 1){return(NULL)} output = rep(0,N) phi = (1 + sqrt(5))/2 for(k in 1:N){output[k] = (phi^k - (1 - phi)^k) / sqrt(5) } return(output) }<file_sep>/Factorial.cpp #include <cstdio> #include <iostream> int64_t factorial(int x){ if(x <= 1){return 1;} return x * factorial(x - 1); } int main(){ for(int p = 0; p < 15; p++){ printf("%lld\n", factorial(p)); } return 0; } <file_sep>/matchStrings.cpp #include <cstdio> #include <iostream> int matchStrings(std::string glob, std::string test) { int cp(0),mp(0); int first(0), second(0); while (glob[first] != '*' && second < test.size()) { if ((glob[first] != test[second]) && (glob[first] != '?')){return 0;} ++first; ++second; } while(second < test.size()) { if (glob[first] == '*') { if (first == glob.size() - 1){return 1;} mp = first; cp = second + 1; } else if ((glob[first] == test[second]) || (glob[first] == '?')){++first; ++second;} else{first = mp; second = cp++;} } while (glob[first] == '*') {++first;} if(first == glob.size()){return 1;} else{return 0;} } int main(){ std::string test(""), glob(""); getline(std::cin, test); getline(std::cin, glob); printf("%d\n", matchStrings(glob,test)); return 0; } <file_sep>/GoldRowGame.cpp #include <iostream> #include <vector> #include <algorithm> int main(){ int n; std::cin >> n; std::vector<int> v(n, 0); std::ios_base::sync_with_stdio(false); for(int p = 0; p < n; p++){std::cin >> v[p];} std::vector<std::vector<int> > dp(n, std::vector<int>(n, 0)); for(int p = 0; p < n; p++){dp[p][p] = v[p];} for(int p = 0; p < n - 1; p++){dp[p][p + 1] = std::max(v[p], v[p + 1]);} for(int len = 3; len <= n; len++){ for(int s = 0; s + len <= n; s++){ int f = s + len - 1; dp[s][f] = std::max(v[s] + std::min(dp[s + 2][f], dp[s + 1][f - 1]), std::min(dp[s + 1][f - 1], dp[s][f - 2]) + v[f]); } } for(int p = 0; p < n; p++){ for(int q = 0; q < n; q++){std::cout << dp[p][q] << "\t";}; std::cout << std::endl; } std::cout << dp[0][n - 1] << std::endl; return 0; } <file_sep>/HistogramMaxArea.cpp #include <iostream> #include <vector> long getHistMaxArea(std::vector<long> h){ long maxArea; size_t n = h.size(); std::vector<long> stack; size_t k(0); while(k < n){ if(stack.empty() || h[stack.back()] <= h[k]){stack.push_back(k++);} else{ long top = stack.back(); stack.pop_back(); long area = h[top] * (stack.empty() ? k : (k - stack.back() - 1)); if(area > maxArea){maxArea = area;} } } while(!stack.empty()){ long top = stack.back(); stack.pop_back(); long area = h[top] * (stack.empty() ? n : (n - stack.back() - 1)); if(area > maxArea){maxArea = area;} } return maxArea; } int main(){ int n; std::cin >> n; std::vector<long> hist(n, 0); for(int p = 0; p < n; p++){std::cin >> hist[p];} long area = getHistMaxArea(hist); std::cout << area << std::endl; return 0; } <file_sep>/OddCounter.R oddCounter = function(x){ output = 0; for( k in x){if( k %% 2 == 1){output = output + 1;}} return(output); } <file_sep>/CoinChange-MinNumberOfCoins.cpp #include <cstdio> #include <iostream> #include <vector> int main(){ //Input: //First line: amount to be exchanged, and number of available denominations //Subesquent lines: the available denominations long change, numCoins; std::cin >> change >> numCoins; std::vector<long> denom(numCoins, 0); for(long p = 0; p < numCoins; p++){long value; std::cin >> value; denom[p] = value;} std::vector<std::pair<long, long> > optimal(1 + change, std::pair<long, long>(0,0)); for(long rest = 1; rest <= change; rest++){ for(long d = 0; d < numCoins; d++){ long currentValue = denom[d]; if(rest < currentValue){continue;} if(optimal[rest].first == 0 || 1 + optimal[rest - currentValue].first < optimal[rest].first){ optimal[rest].first = 1 + optimal[rest - currentValue].first; optimal[rest].second = currentValue; } } } std::cout << "\nMinimum number of coins: " << optimal[change].first << std::endl; std::cout << "\n\nUsed Coins:\n"; long rem = change; while(rem > 0){ std::cout << optimal[rem].second << "\t"; rem -= optimal[rem].second; } std::cout << std::endl; return 0; } <file_sep>/Fibonacci.R fibonacci = function(n){ output = c(); if(n<1){return;} if(n >= 1){output = c(1)} if(n >= 2){output = c(output,1);summary(output)} if(n >= 3){for(k in seq(3,n) ){output = c(output, output[k-1]+output[k-2]);}}; output; } <file_sep>/TextJustification.cpp #include <iostream> #include <vector> int main(){ long M, n; std::cin >> M >> n; std::vector<long> words(n); for(long p = 0; p < n; p++){std::cin >> words[p];} std::vector<std::vector<long> > spaces(n, std::vector<long>(n, 0)); for(int p = 0; p < n; p++){ spaces[p][p] = M - words[p]; for(int q = p + 1; q < n; q++){spaces[p][q] = spaces[p][q - 1] - words[q] - 1;} } std::vector<std::vector<long> > penalty(n, std::vector<long>(n, 0)); for(int p = 0; p < n; p++){ for(int q = p; q < n - 1; q++){ penalty[p][q] = (spaces[p][q] < 0) ? (-1) : (spaces[p][q] * spaces[p][q]); } } std::vector<long> score(n, -1); std::vector<long> prev(n, 0); for(int p = 1; p < n; p++){ for(int q = 1; q <= p; q++){ if(penalty[q][p] < 0){continue;} long candidate = score[q - 1] + penalty[q][p]; if(score[p] < 0 || candidate < score[p]){score[p] = candidate; prev[p] = q;} } } std::vector<std::pair<long, long> > lines; long ind(n - 1); while(ind >= 0){ lines.push_back(std::make_pair(prev[ind], ind)); ind = prev[ind] - 1; } for(long p = lines.size() - 1; p >= 0; p--){std::cout << lines[p].first << " " << lines[p].second << std::endl;} return 0; } <file_sep>/MaximumContiguousSequence.cpp #include <iostream> #include <vector> int maxValue(std::vector<int> v){ int res(0); int ending(0); for(int p = 0; p < v.size(); p++){ ending = std::max(ending + v[p], v[p]); res = std::max(res, ending); } return res; } int main(){ int n = 23; std::vector<int> x(n); for(int p = 0; p < n; p++){x[p] = (3 * p + 5) % n - 10;} for(int p = 0; p < n; p++){std::cout << x[p] << " ";}; std::cout << std::endl; std::cout << maxValue(x) << std::endl; return 0; } <file_sep>/stringPermutations.cpp #include <cstdio> #include <iostream> #include <string> void printPerms(std::string input, std::string remainder){ if(input.size() == 0){std::cout << remainder << std::endl;} else{ for(int k = 0; k < input.size(); k++){ std::string newRemainder = remainder + input[k]; std::string newInput = input.substr(0,k) + input.substr(k + 1); printPerms(newInput,newRemainder); } } } int main(){ std::string testString = "abcd"; printPerms(testString, ""); return 0; } <file_sep>/BinaryMatrixMaxArea.cpp #include <iostream> #include <vector> long getHistMaxArea(std::vector<long> h){ long maxArea; size_t n = h.size(); std::vector<long> stack; size_t k(0); while(k < n){ if(stack.empty() || h[stack.back()] <= h[k]){stack.push_back(k++);} else{ long top = stack.back(); stack.pop_back(); long area = h[top] * (stack.empty() ? k : (k - stack.back() - 1)); if(area > maxArea){maxArea = area;} } } while(!stack.empty()){ long top = stack.back(); stack.pop_back(); long area = h[top] * (stack.empty() ? n : (n - stack.back() - 1)); if(area > maxArea){maxArea = area;} } return maxArea; } long getMaxRectangleArea(std::vector<std::vector<int> > box){ std::vector<long> hist(box[0].size(), 0); long maxBoxArea(0); for(int row = 0; row < box.size(); row++){ for(int col = 0; col < box[row].size(); col++){ if(box[row][col]){++hist[col];} else{hist[col] = 0;} } long subArea = getHistMaxArea(hist); if(subArea > maxBoxArea){maxBoxArea = subArea;} } return maxBoxArea; } int main(){ int R, C; std::cin >> R >> C; std::vector<std::vector<int> > matrix(R, std::vector<int>(C, 0)); for(int row = 0; row < R; row++){for(int col = 0; col < C; col++){std::cin >> matrix[row][col];}} std::cout << getMaxRectangleArea(matrix) << std::endl; return 0; } /* Example input 4 6 1 0 0 1 1 1 1 0 1 1 0 1 0 1 1 1 1 1 0 0 1 1 1 1 */ <file_sep>/Eratosthenes.R primeFinder = function(n){ if(n<2){stop("Input should be more >=2");} sieve = rep(T , n);sieve[1]=F; for(k in 2:sqrt(n) ) { if(!sieve[k]) {next;} a = 2*k; while( a <= n ){sieve[a] = F; a = a+k} } primes = 1:n;primes = primes[sieve];primes; } <file_sep>/Knapsack-unbounded.cpp #include <cstdio> #include <iostream> #include <vector> //Input: First line - Capacity and number of items // Then the items follow, in the form of (weight, value); int main(){ long capacity, numItems; std::cin >> capacity >> numItems; std::vector<std::pair<long, long> > items(numItems); for(int p = 0; p < numItems; p++){ long weight, value; std::cin >> weight >> value; items[p] = std::pair<long, long>(weight, value); } std::vector<std::pair<long, long> > optimal(capacity + 1, std::pair<long, long>(0,-1)); for(long cap = 1; cap <= capacity; cap++){ optimal[cap].first = optimal[cap - 1].first; for(long index = 0; index < items.size(); index++){ long currentWeight = items[index].first; long currentValue = items[index].second; if(currentWeight > cap){continue;} else if(optimal[cap - currentWeight].first + currentValue > optimal[cap].first){ optimal[cap].first = optimal[cap - currentWeight].first + currentValue; optimal[cap].second = index; } } } std::vector<long> chosen; long cap = capacity; while(cap > 0){ if(optimal[cap].second < 0){--cap;} else{ long index = optimal[cap].second; chosen.push_back(index); cap -= items[index].first; } } std::cout << "Index\tWeight\tValue\n"; for(int p = chosen.size() - 1; p >= 0; p--){ long index = chosen[p]; std::cout << index <<"\t"<< items[index].first <<"\t"<< items[index].second << "\n"; } std::cout << "\nOptimal Value: " << optimal[capacity].first << std::endl; std::cout << "Optimal Value for different Capacities:\n" << std::endl; std::cout << "Cap\tValue\n"; for(int p = 0; p < optimal.size(); p++){std::cout << p <<"\t"<< optimal[p].first << "\n";} return 0; } <file_sep>/PassByValueOrRef.cpp #include <cstdio> #include <iostream> void swapRef(int &x, int &y){ int temp = x; x = y; y = temp; return; } void swapValue(int x, int y){ int temp = x; x = y; y = temp; return; } int main(){ int a(1), b(2); swapValue(a, b); std::cout << a << "\t" << b << std::endl; swapRef(a, b); std::cout << a << "\t" << b << std::endl; return 0; } <file_sep>/SweetHarvest.cpp #include <cstdio> #include <iostream> #include <sstream> #include <vector> int main(){ int t; scanf("%d\n", &t); while(t--){ std::string s; getline(std::cin, s); std::istringstream iss(s); long x; std::vector<long> candies; while(iss >> x){candies.push_back(x);} size_t n = candies.size(); std::vector<long> sums(n); sums[0] = candies[0]; sums[1] = 0; sums[2] = candies[0] + candies[2]; for(int p = 3; p < n; p++){sums[p] = candies[p] + ((sums[p - 3] > sums[p - 2]) ? sums[p - 3] : sums[p - 2]);} long ans = (sums[n - 2] > sums[n - 1]) ? sums[n - 2] : sums[n - 1]; std::cout << ans << " "; } std::cout << std::endl; return 0; } <file_sep>/OptimalCutting.cpp #include <iostream> #include <vector> int main(){ int n; std::cin >> n; std::vector<int> price(n + 1); for(int p = 1; p <= n; p++){std::cin >> price[p];} std::vector<int> optimal(n + 1); for(int p = 1; p <= n; p++){ int currentMax(0); for(int q = 0; q <= p / 2; q++){ int current = price[q] + price[p - q]; if(current > currentMax){currentMax = current;} } optimal[p] = currentMax; } for(int p = 0; p <= n; p++){std::cout << price[p] << "\t";} std::cout << std::endl; for(int p = 0; p <= n; p++){std::cout << optimal[p] << "\t";} std::cout << std::endl; std::cout << optimal[n] << std::endl; return 0; } //Given a rod that can be cut into individual pieces of integer length, //find how to cut it in order to achieve maximum profit //http://tech-queries.blogspot.com/2014/04/max-price-by-selling-pieces-of-rod.html <file_sep>/binaryCombinations.cpp #include <cstdio> #include <vector> #include <iostream> #include <string> std::vector<std::string> binaryCombinations(int n, std::vector<std::string> inputVector){ if(n == 0){return inputVector;} else if(inputVector.size() == 0){ std::vector<std::string> tempVector; tempVector.push_back("0"); tempVector.push_back("1"); std::vector<std::string> outputVector = binaryCombinations(n - 1, tempVector); return outputVector; } else{ std::vector<std::string> newVector; for(int k = 0; k < inputVector.size(); k++){newVector.push_back("0" + inputVector[k]);} for(int k = 0; k < inputVector.size(); k++){newVector.push_back("1" + inputVector[k]);} std::vector<std::string> outputVector = binaryCombinations(n - 1, newVector); return outputVector; } } int main(){ std::vector<std::string> testInput; std::vector<std::string> testString = binaryCombinations(3,testInput); for(int k = 0; k < testString.size(); k++){std::cout << testString[k] << std::endl;} return 0; } <file_sep>/MovingAverage.R movingAverage = function(x,a){ N = length(x) output = rep(0,N-a+1) for(k in 1:a ){output = output +x[k:(N-a+k)]} return(output/a) }<file_sep>/MatrixOperation.R matrixOperationB = function(n,k){ A = matrix(0 , nrow = n, ncol =n) A = A + k*(row(A) == col(A)) + (abs(row(A)-col(A)) == 1); return(A) }
ee3d23a02e976a673aecebf8dfd209aa4f42239c
[ "R", "C++" ]
46
C++
DionysiosB/VariousSnippets
3964cbdea02e842838be9bff8333b778be7ddf8d
ebebdcf7a203353b472434ddfa1db050f187af5f
refs/heads/master
<repo_name>crownz/category-tree<file_sep>/src/app/dialogs/new-node/new-node.component.ts import { Component, OnInit } from '@angular/core'; import {MdDialogRef} from "@angular/material"; @Component({ selector: 'app-new-node', templateUrl: './new-node.component.html', styleUrls: ['new-node.component.less'] }) export class NewNodeDialog implements OnInit { nodeName: string = ''; constructor(public dialogRef: MdDialogRef<NewNodeDialog>) { } ngOnInit() { } } <file_sep>/src/app/services/tree-category.service.ts import { Node } from '../models/node.model'; import {Injectable} from "@angular/core"; @Injectable() export abstract class TreeCategoryService { abstract build(tree: Node): Array<Node>; } <file_sep>/src/app/services/tree-category-recursive.service.ts import { Node } from '../models/node.model'; import {TreeCategoryService} from "./tree-category.service"; export class TreeCategoryRecursiveService extends TreeCategoryService { /** * Creates array of tree nodes in recursive way * in order which nodes will be printed out * when visualizing. * Stack overflow might occur if tree depth is too big. * @param tree * @returns {Array<Node>} */ build(tree: Node): Array<Node> { let result: Array<Node> = []; result.push(tree); if (tree.children && tree.children.length > 0) { tree.children.forEach(child => result.push(...this.build(child))); } return result; } } /** * Exporting factory. */ export default () => new TreeCategoryRecursiveService(); <file_sep>/src/app/dialogs/new-node/new-node.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { NewNodeDialog } from './new-node.component'; describe('NewNodeComponent', () => { let component: NewNodeDialog; let fixture: ComponentFixture<NewNodeDialog>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ NewNodeDialog ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(NewNodeDialog); component = fixture.componentInstance; fixture.detectChanges(); }); }); <file_sep>/src/app/components/tree-container/tree-container.component.ts import { Component, OnInit } from '@angular/core'; import { Node } from '../../models/node.model'; import {TreeCategoryRecursiveService} from "../../services/tree-category-recursive.service"; import {TreeCreationUtils} from "../../utils/tree-creation.utils"; import {TreeCategoryIterativeService} from "../../services/tree-category-iterative.service"; import {NewNodeDialog} from "../../dialogs/new-node/new-node.component"; import {MdDialog} from "@angular/material"; import {TreeCategoryService} from "../../services/tree-category.service"; const TYPE_RECURSIVE: string = "Recursive"; const TYPE_ITERATIVE: string = "Iterative"; const ROOT_LEVEL: number = 0; @Component({ selector: 'tree-container', templateUrl: './tree-container.component.html', styleUrls: ['tree-container.component.less'] }) export class TreeContainerComponent implements OnInit { /** * Root node of currently displayed tree. */ rootNode: Node; /** * Array used to store tree nodes in * display order. */ nodesArray: Array<Node>; /** * Current tree service used for * nodes array generation. */ currentTreeService: TreeCategoryService; /** * List of all instance of available tree services. * At the moment it is assumed that two services * will be injected. */ allTreeServices; /** * Type of currently used service for * nodes array building. */ serviceType; constructor(private treeServices: TreeCategoryService, public dialog: MdDialog) { this.serviceType = TYPE_RECURSIVE; this.allTreeServices = treeServices; this.currentTreeService = treeServices[1]; } ngOnInit() { } /** * Opens dialog for new node creation. * If no node is passed in, it is assumed that * new tree is being created. * @param node */ addNewNode(node?: Node): void { let dialogRef = this.dialog.open(NewNodeDialog); dialogRef.afterClosed().subscribe(result => { if (result && node) { let newNode: Node = {value: result, children: [], level: node.level + 1}; node.children.push(newNode); this.nodesArray = this.currentTreeService.build(this.rootNode); } else if (result && !node) { let newNode: Node = {value: result, children: [], level: ROOT_LEVEL}; this.rootNode = newNode; this.nodesArray = [this.rootNode]; } }); } /** * Generates new tree. */ generateStartingTree(): void { this.rootNode = TreeCreationUtils.createSampleTree(); this.nodesArray = this.currentTreeService.build(this.rootNode); } /** * Toggles tree service type between * iterative and recursive. */ toggleBuilder() { if (this.currentTreeService instanceof TreeCategoryRecursiveService) { this.serviceType = TYPE_ITERATIVE; this.currentTreeService = this.allTreeServices[0]; } else if (this.currentTreeService instanceof TreeCategoryIterativeService) { this.serviceType = TYPE_RECURSIVE; this.currentTreeService = this.allTreeServices[1]; } } } <file_sep>/src/app/services/tree-category-iterative.service.ts import { Node } from '../models/node.model'; import {TreeCategoryService} from "./tree-category.service"; export class TreeCategoryIterativeService extends TreeCategoryService { /** * Creates array of tree nodes in iterative way * in order which nodes will be printed out * when visualizing. * @param tree * @returns {Array<Node>} */ build(tree: Node): Array<Node> { let result: Array<Node> = []; let toIterate: Array<Node> = []; toIterate.push(tree); while(toIterate.length > 0) { let current = toIterate.shift(); result.push(current); if (current.children && current.children.length > 0) { toIterate = this.mergeToBeginning(toIterate, current.children); } } return result; } /** * Merges arrays by pushing second * array to the beginning of first one. * @param array1 * @param array2 * @returns {Array} */ private mergeToBeginning(array1: Array<Node>, array2: Array<Node>): Array<Node> { let result: Array<Node> = []; result.push(...array2, ...array1); return result; } } /** * Exporting factory. */ export default () => new TreeCategoryIterativeService(); <file_sep>/src/app/components/tree-container/tree-container.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Node } from '../../models/node.model'; import { TreeContainerComponent } from './tree-container.component'; import {MaterialModule, MdDialog} from "@angular/material"; import {TreeCategoryService} from "../../services/tree-category.service"; import {TreeCreationUtils} from "../../utils/tree-creation.utils"; import {Observable} from "rxjs"; import {TreeCategoryRecursiveService} from "../../services/tree-category-recursive.service"; import {TreeCategoryIterativeService} from "../../services/tree-category-iterative.service"; const TYPE_RECURSIVE: string = "Recursive"; const TYPE_ITERATIVE: string = "Iterative"; class TreeCategoryServiceMock { build() {} } class MdDialogMock { open() {} } class DialogRefMock { afterClosed() { } } describe('TreeContainerComponent', () => { let component: TreeContainerComponent; let fixture: ComponentFixture<TreeContainerComponent>; let treeService: TreeCategoryService; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ TreeContainerComponent ], imports: [MaterialModule.forRoot()], providers: [ { provide: TreeCategoryService, useValue: new TreeCategoryServiceMock(), multi: true }, { provide: TreeCategoryService, useValue: new TreeCategoryServiceMock(), multi: true }, { provide: MdDialog, useValue: new MdDialogMock() } ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TreeContainerComponent); component = fixture.componentInstance; treeService = TestBed.get(TreeCategoryService); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('generateStartingTree should successfully generate nodes array', () => { //given const root: Node = { value: 'node1', children: [], level: 0 }; const resultArray = []; //when spyOn(TreeCreationUtils, "createSampleTree").and.returnValue(root); spyOn(component.currentTreeService, "build").and.returnValue(resultArray); component.generateStartingTree(); //then expect(component.rootNode).toBe(root); expect(component.nodesArray).toBe(resultArray); }); it('addNewNode should successfully add new node', async(() => { //given let dialogRef: DialogRefMock = new DialogRefMock(); const result = 'node'; const root: Node = { value: 'node1', children: [], level: 0 }; const resultArray = []; //when spyOn(TestBed.get(MdDialog), "open").and.returnValue(dialogRef); spyOn(dialogRef, "afterClosed").and.returnValue(Observable.of(result)); spyOn(component.currentTreeService, "build").and.returnValue(resultArray); component.addNewNode(root); //then expect(root.children.length).toBe(1); expect(root.children[0].level).toEqual(root.level + 1); expect(component.nodesArray).toBe(resultArray); })); it('addNewNode should successfully create new root node', async(() => { //given let dialogRef: DialogRefMock = new DialogRefMock(); const result = 'node'; //when spyOn(TestBed.get(MdDialog), "open").and.returnValue(dialogRef); spyOn(dialogRef, "afterClosed").and.returnValue(Observable.of(result)); component.addNewNode(); //then expect(component.rootNode.children.length).toEqual(0); expect(component.rootNode.level).toEqual(0); expect(component.rootNode.value).toEqual(result); expect(component.nodesArray.length).toEqual(1); expect(component.nodesArray[0]).toBe(component.rootNode); })); it('addNewNode should do nothing without result value', async(() => { //given let dialogRef: DialogRefMock = new DialogRefMock(); const root: Node = { value: 'node1', children: [], level: 0 }; //when spyOn(TestBed.get(MdDialog), "open").and.returnValue(dialogRef); spyOn(dialogRef, "afterClosed").and.returnValue(Observable.of(undefined)); component.rootNode = root; component.addNewNode(); //then expect(component.rootNode).toBe(root); })); it('toggleBuilder should switch to iterative service', () => { //given component.currentTreeService = new TreeCategoryRecursiveService(); //when component.toggleBuilder(); //then expect(component.serviceType).toEqual(TYPE_ITERATIVE); expect(component.currentTreeService).toBe(component.allTreeServices[0]); }); it('toggleBuilder should switch to recursive service', () => { //given component.currentTreeService = new TreeCategoryIterativeService(); //when component.toggleBuilder(); //then expect(component.serviceType).toEqual(TYPE_RECURSIVE); expect(component.currentTreeService).toBe(component.allTreeServices[1]); }); }); <file_sep>/src/app/services/tree-category.service.spec.ts import {Node} from '../models/node.model'; import {TreeCategoryIterativeService} from "./tree-category-iterative.service"; import {TreeCategoryService} from "./tree-category.service"; import {TreeCategoryRecursiveService} from "./tree-category-recursive.service"; describe('TreeCategoryIterativeService', () => { let testedInstances: Array<TreeCategoryService>; beforeEach(() => { testedInstances = [ new TreeCategoryIterativeService(), new TreeCategoryRecursiveService() ]; }); it('build should successfully build when root has no children', () => { testedInstances.forEach(service => { //given const root: Node = { value: 'node1', children: [], level: 0 }; //when const result = service.build(root); //then expect(result.length).toEqual(1); expect(result[0]).toBe(root); }); }); it('build should successfully build when root has children', () => { testedInstances.forEach(service => { //given const innerNode: Node = { value: 'node4', children: [], level: 2 }; const root: Node = { value: 'node1', children: [ { value: 'node2', children: [innerNode], level: 1 }, { value: 'node3', children: [], level: 1 } ], level: 0 }; const expectedResult = [root, root.children[0], root.children[0].children[0], root.children[1]]; //when const result = service.build(root); //then expect(result.length).toEqual(4); expect(result[0]).toBe(root); expect(result).toEqual(expectedResult); }); }); }); <file_sep>/src/app/components/tree-node/tree-node.component.ts import {Component, OnInit, Input} from '@angular/core'; import { Node } from '../../models/node.model'; @Component({ selector: 'tree-node', templateUrl: './tree-node.component.html', styleUrls: ['tree-node.component.less'] }) export class TreeNodeComponent implements OnInit { @Input() node: Node; constructor() { } ngOnInit() { } } <file_sep>/src/app/utils/tree-creation.utils.ts import {Node} from '../models/node.model'; export class TreeCreationUtils { /** * Creates sample tree using hardcoded values. * @returns {{value: string, children: (Node|Node)[], indentation: number}} */ static createSampleTree(): Node { let node6: Node = {value: 'node6', children: [], level: 3}; let node7: Node = {value: 'node7', children: [], level: 3}; let node2: Node = {value: 'node2', children: [], level: 2}; let node3: Node = {value: 'node3', children: [], level: 2}; let node4: Node = {value: 'node4', children: [node6, node7], level: 2}; let node5: Node = {value: 'node5', children: [], level: 2}; let node0: Node = {value: 'node0', children: [node2], level: 1}; let node1: Node = {value: 'node1', children: [node3, node4, node5], level: 1}; let rootNode = {value: 'Root', children: [node0, node1], level: 0}; return rootNode; } } <file_sep>/src/app/models/node.model.ts export interface Node { value: String; children: Array<Node>; level: number; } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { TreeContainerComponent } from './components/tree-container/tree-container.component'; import { TreeNodeComponent } from './components/tree-node/tree-node.component'; import recursiveServiceFactory from "./services/tree-category-recursive.service"; import iterativeServiceFactory from "./services/tree-category-iterative.service"; import {TreeCategoryService} from "./services/tree-category.service"; import {MaterialModule} from "@angular/material"; import { NewNodeDialog } from './dialogs/new-node/new-node.component'; @NgModule({ declarations: [ AppComponent, TreeContainerComponent, TreeNodeComponent, NewNodeDialog ], imports: [ BrowserModule, FormsModule, HttpModule, MaterialModule ], providers: [ { provide: TreeCategoryService, useFactory: iterativeServiceFactory, multi: true }, { provide: TreeCategoryService, useFactory: recursiveServiceFactory, multi: true } ], entryComponents: [ NewNodeDialog ], bootstrap: [AppComponent] }) export class AppModule { }
36fcdf47e746b17e7802ce7bb6ec3464d26e8ba6
[ "TypeScript" ]
12
TypeScript
crownz/category-tree
23f189a31c3101279f97bfc83eab28a5394c948f
6e1286f95ca2670b4b90815e386df3af4a57ce77
refs/heads/master
<repo_name>bagobor/DeepSpace_OculusVR<file_sep>/Assets/game_code/Enemy.cs using UnityEngine; using System.Collections; public class Enemy { Vector3 pos; float vel; GameObject gameobj; public Enemy(Vector3 _pos, GameObject _gameobj) { pos = _pos; gameobj = _gameobj; gameobj.transform.position = pos; vel = Util.rand_range(0.15f,0.5f); } public void update() { pos.z -= vel; gameobj.transform.position = pos; } public Vector3 get_position() { return pos; } public bool should_remove() { return pos.z < -40; } public void do_remove() { GameObject.Destroy(gameobj); gameobj = null; } } <file_sep>/Assets/game_code/GameControl.cs using UnityEngine; using System.Collections; using System; public class GameControl : MonoBehaviour { public static float X_MAX = 25; public static float X_MIN = -25; public static float Y_MAX = 25; public static float Y_MIN = -25; static float VX_MAX = 1; static float VY_MAX = 1; float vx = 0; float vy = 0; float rotation_z = 0; float rotation_x = 0; float gun_cooldown = 0; int gun_ct; GameObject crosshair_gui; GameObject left_gun_anchor; GameObject right_gun_anchor; GameObject player_anchor; void Start () { crosshair_gui = Util.FindInHierarchy(this.gameObject,"crosshair"); player_anchor = Util.FindInHierarchy(this.gameObject,"OVRCameraController"); left_gun_anchor = Util.FindInHierarchy(this.gameObject,"MissileAnchor_L"); right_gun_anchor = Util.FindInHierarchy(this.gameObject,"MissileAnchor_R"); } void Update () { Screen.showCursor = false; Vector3 position = this.gameObject.transform.position; Quaternion rotation_q = this.gameObject.transform.rotation; Vector3 rotation = rotation_q.eulerAngles; if (Input.GetKey(KeyCode.A)) { if (vx > 0) vx = 0; vx = Math.Max(-VX_MAX,vx - 0.01f); } else if (Input.GetKey(KeyCode.D)) { if (vx < 0) vx = 0; vx = Math.Min(VX_MAX,vx + 0.01f); } else { vx *= 0.95f; } if (Input.GetKey(KeyCode.S)) { if (vy > 0) vy = 0; vy = Math.Max(-VY_MAX,vy - 0.01f); } else if (Input.GetKey(KeyCode.W)) { if (vy < 0) vy = 0; vy = Math.Min(VY_MAX,vy + 0.01f); } else { vy *= 0.95f; } position.x = Mathf.Clamp(position.x+vx,X_MIN,X_MAX); position.y = Mathf.Clamp(position.y+vy,Y_MIN,Y_MAX); float target_rotation_z = 20.0f * -1 * vx; rotation_z = rotation_z + (target_rotation_z - rotation_z)/10.0f; float target_rotation_x = 20.0f * -1 * vy; rotation_x = rotation_x + (target_rotation_x - rotation_x)/10.0f; rotation.z = rotation_z; rotation.x = rotation_x; rotation_q.eulerAngles = rotation; this.gameObject.transform.rotation = rotation_q; this.gameObject.transform.position = position; float mousex = Input.mousePosition.x > Screen.width ? Screen.width : Input.mousePosition.x; float mousey = Input.mousePosition.y > Screen.height ? Screen.height : Input.mousePosition.y; Vector3 crosshair_position = crosshair_gui.transform.localPosition; float screen_scale = 0.13f; crosshair_position.x = (mousex - Screen.width/2.0f) / (Screen.width/2.0f) * screen_scale; crosshair_position.y = (mousey - Screen.height/2.0f) / (Screen.height/2.0f) * screen_scale * 0.86f + 0.08f; crosshair_gui.transform.localPosition = crosshair_position; if (gun_cooldown > 0) { gun_cooldown-=1; } if (Input.GetKey(KeyCode.Space) || Input.GetMouseButton(0)) { if (gun_cooldown <= 0) { gun_ct++; if (gun_ct%4 == 0) { gun_cooldown = 20; } else { gun_cooldown = 6; } Vector3 cursor_position = crosshair_gui.transform.position; if (Math.Abs(position.x) < X_MAX) cursor_position.x += vx; if (Math.Abs(position.y) < Y_MAX) cursor_position.y += vy; Vector3 player_position = player_anchor.transform.position; Vector3 npc_dir = (new Vector3( cursor_position.x-player_position.x, cursor_position.y-player_position.y, cursor_position.z-player_position.z)).normalized; npc_dir.x *= 20; npc_dir.y *= 20; npc_dir.z *= 20; Vector3 convergence_pos = new Vector3(npc_dir.x + player_position.x, npc_dir.y+player_position.y, npc_dir.z+player_position.z); Vector3 lanchor_position = left_gun_anchor.transform.position; if (Math.Abs(position.x) < X_MAX) lanchor_position.x += vx; if (Math.Abs(position.y) < Y_MAX)lanchor_position.y += vy; Vector3 lbullet_vel = (new Vector3(convergence_pos.x-lanchor_position.x, convergence_pos.y-lanchor_position.y, convergence_pos.z-lanchor_position.z)).normalized; lbullet_vel.x *= 0.75f; lbullet_vel.y *= 0.75f; lbullet_vel.z *= 0.75f; if (Math.Abs(position.x) < X_MAX) lbullet_vel.x += vx; if (Math.Abs(position.y) < Y_MAX)lbullet_vel.y += vy; BulletManager.instance.AddBullet( lanchor_position, lbullet_vel ); Vector3 ranchor_position = right_gun_anchor.transform.position; if (Math.Abs(position.x) < X_MAX) ranchor_position.x += vx; if (Math.Abs(position.y) < Y_MAX)ranchor_position.y += vy; Vector3 rbullet_vel = (new Vector3(convergence_pos.x-ranchor_position.x, convergence_pos.y-ranchor_position.y, convergence_pos.z-ranchor_position.z)).normalized; rbullet_vel.x *= 0.75f; rbullet_vel.y *= 0.75f; rbullet_vel.z *= 0.75f; if (Math.Abs(position.x) < X_MAX) rbullet_vel.x += vx; if (Math.Abs(position.y) < Y_MAX) rbullet_vel.y += vy; BulletManager.instance.AddBullet( ranchor_position, rbullet_vel ); } } } } <file_sep>/Assets/ZSpriteEngine/ZResourceManager.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; // spotco -- todo -- kill all the asset downloading code public interface IResourceManager { Object Load(string path); Object Load(string path, System.Type systemTypeInstance); Object LoadAssetAtPath(string path, System.Type systemTypeInstance); } public class ZResourceManager : SingletonMonoBehaviour<ZResourceManager>, IResourceManager { public const string ASSET_REPO_URL = ""; private List<AssetBundle> loadedBundles = new List<AssetBundle>(); private List<ZAssetBundle> allBundles = new List<ZAssetBundle>(); public List<ZAssetBundle> AllBundles {get {return allBundles;}} IEnumerator Start() { yield return true; } protected override void Awake() { base.Awake(); } public static Object SafeLoad(string path) { if (ZResourceManager.DoesInstanceExist()) { return Instance.Load (path); } else { return Resources.Load (path); } } public static Object SafeLoadAssetAtPath(string path, System.Type systemTypeInstance) { if (ZResourceManager.DoesInstanceExist()) { return Instance.LoadAssetAtPath(path, systemTypeInstance); } else { return Resources.LoadAssetAtPath(path, systemTypeInstance); } } public Object Load(string path) { return Load (path, null); } public Object Load(string path, System.Type type) { Object resource; resource = LoadFromResources(path, type); if (resource == null) { resource = LoadFromAssetBundles(path); } else { } return resource; } public Object LoadAssetAtPath(string path, System.Type type) { Object resource; resource = LoadAssetAtPathFromResources(path, type); if (resource == null) { resource = LoadFromAssetBundles(path); } else { } return resource; } private Object LoadFromResources(string path, System.Type type) { Object result; try { if (type != null) { result = Resources.Load(path, type); } else { result = Resources.Load(path); } } catch (System.Exception) { result = null; } return result; } private Object LoadAssetAtPathFromResources(string path, System.Type type) { Object result; try { result = Resources.LoadAssetAtPath(path, type); } catch (System.Exception) { result = null; } return result; } private Object LoadFromAssetBundles(string path) { string assetName = System.IO.Path.GetFileName(path); foreach (AssetBundle bundle in loadedBundles) { try { if( bundle != null ) { Object asset = bundle.Load(assetName); if (asset != null) { Debug.Log("Loaded from asset bundle: " + path); return asset; } } } catch (System.Exception e) { Debug.LogError("LoadFromAssetBundles: " + e); } } return null; } private ZResourceManager() { InitBundles(); } private void InitBundles() { // Audio Bundle allBundles.Add( new ZAssetBundle( 1, // version "sounds", // bundle name OnSoundsLoaded, // on load callback GetAudioFilesToExclude(), // files to exclude from the build delegate() {return Resources.FindObjectsOfTypeAll(typeof(AudioClip));} // Objects for bundle ) ); } private string[] GetAudioFilesToExclude() { string[] rtv = {""}; return rtv; } public void OnSoundsLoaded() { //spotco -- log here } public void OnFireHeroLoaded() { } } public class ZAssetBundle { private int _version; private System.Action _onLoadCallback; private string _name; private string[] _files; private System.Func<Object[]> _getObjectsForBundle; public ZAssetBundle(int version, string name, System.Action onLoadCallback, string[] files, System.Func<Object[]> getObjectsForBundle) { _version = version; _onLoadCallback = onLoadCallback; _name = name; _files = files; _getObjectsForBundle = getObjectsForBundle; } public int Version { get { return _version; } } public string Name { get { return _name; } } public System.Action OnLoadCallback { get { return _onLoadCallback; } } public string[] Files { get { return _files; } } public Object[] ObjectsForBundle { get { return _getObjectsForBundle(); } } public string Url { get { string platform = "editor"; #if UNITY_IPHONE platform = "ios"; #endif #if UNITY_ANDROID platform = "android"; #endif return ZResourceManager.ASSET_REPO_URL + platform + "/" + _name; } } public string PathToSave { get { string platform = "editor"; #if UNITY_IPHONE platform = "ios"; #endif #if UNITY_ANDROID platform = "android"; #endif // http://assets-dev-hero.hero-dev-01.zc1.zynga.com/ios/sounds return "Assets/bundles/" + platform + "/" + _name; } } } <file_sep>/Assets/game_code/BulletManager.cs using UnityEngine; using System.Collections.Generic; public class BulletManager : MonoBehaviour { public static BulletManager instance; public List<Bullet> bullets = new List<Bullet>(); void Start () { instance = this; } void Update () { for (int i = bullets.Count-1; i >= 0; i--) { Bullet b = bullets[i]; b.update(); if (b.should_remove()) { bullets.RemoveAt(i); b.do_remove(); } } } public void AddBullet(Vector3 pos, Vector3 vel) { GameObject bullet_object = (GameObject)Instantiate(Resources.Load("Bullet")); bullet_object.transform.parent = this.gameObject.transform; bullets.Add(new Bullet(pos,vel,bullet_object)); } } <file_sep>/Assets/game_code/GameGUI.cs using UnityEngine; using System.Collections; public class GameGUI : MonoBehaviour { public static GameGUI instance; TextMesh text_hp; TextMesh text_score; GameObject health_bar_image; tk2dSprite health_bar_sprite; public int score = 0; void Start () { instance = this; text_hp = Util.FindInHierarchy(this.gameObject,"HP").GetComponent<TextMesh>(); text_score = Util.FindInHierarchy(this.gameObject,"ScoreText").GetComponent<TextMesh>(); health_bar_image = Util.FindInHierarchy(this.gameObject,"HealthBarImage"); health_bar_sprite = health_bar_image.GetComponent<tk2dSprite>(); } void Update () { /*Vector3 hbi_sc = health_bar_image.transform.localScale; hbi_sc.x = 0.25f; health_bar_image.transform.localScale = hbi_sc; text_hp.color = Color.red; text_score.color = Color.red; health_bar_sprite.color = Color.red;*/ text_score.text = "Score: "+score; } } <file_sep>/Assets/ZSpriteEngine/ZSpriteManager.cs //#define LOG_DEBUG_STATS using UnityEngine; using System; using System.Runtime.CompilerServices; using System.Collections.Generic; public class ZSprite { public int id = -1; public int bucket = 0; // This will not be validated for performance reasons so make sure it is a valid bucket index public Color32 color = new Color32(255, 255, 255, 255); public ZSpriteMaterial material = null; public Vector2[] uvs = new Vector2[4]; public Vector3[] vertices = new Vector3[4]; public Color32[] colors = new Color32[4]; } public class ZSpriteMaterial { public int id; public int refCount; public Material material; } public class ZSpriteManager : MonoBehaviour { public static ZSpriteManager DefaultSpriteManager; public int NumBuckets = 1 << 16; public int MaxSpritesPerBucket = 32; public int NumReservedSprites = 512; public int MaxSpritesPerBatch = 128; public Camera Camera; public bool UseAsDefault = false; private int mNumBuckets = 0; private int mMaxSpritesPerBucket = 0; private int mNumAllocatedSprites = 0; private int mNumUsedSprites = 0; private ZSprite[] mSprites; private int mNumAllocatedMaterials = 0; private int mNumUsedMaterials = 0; private ZSpriteMaterial[] mMaterials = new ZSpriteMaterial[0]; private int[] mBuckets; private int[] mBucketCounts; private int[] mBatchSprites; private int[] mBatchCounts; private int mNumBatches; private Mesh[] mMeshes; private Vector3[][] mVertices; private Vector2[][] mUVs; private Color32[][] mColors; private int[][] mTriangles; private Vector3 mZeroVector = Vector3.zero; private Quaternion mIdentityQuaternion = Quaternion.identity; public int NumAllocatedSprites { get { return mNumAllocatedSprites; } } public int NumUsedSprites { get { return mNumUsedSprites; } } void OnEnable() { if (UseAsDefault) { DefaultSpriteManager = this; } if (mBuckets == null) { SetupBuckets(NumBuckets, MaxSpritesPerBucket); } if (mSprites == null) { ReserveSpriteMemory(NumReservedSprites); } } public void SetupBuckets(int numBuckets, int maxSpritesPerBucket) { if (mBuckets == null || numBuckets != mNumBuckets || maxSpritesPerBucket != mMaxSpritesPerBucket) { mNumBuckets = numBuckets; mMaxSpritesPerBucket = maxSpritesPerBucket; mBuckets = new int[mNumBuckets * mMaxSpritesPerBucket]; mBucketCounts = new int[mNumBuckets]; } } public void ReserveSpriteMemory(int numSprites) { int prevNumAllocatedSprites = mNumAllocatedSprites; if (mSprites == null) { mSprites = new ZSprite[numSprites]; mBatchSprites = new int[numSprites]; mBatchCounts = new int [numSprites]; mVertices = new Vector3[numSprites][]; mUVs = new Vector2[numSprites][]; mColors = new Color32[numSprites][]; mTriangles = new int[numSprites][]; mMeshes = new Mesh[numSprites]; mNumAllocatedSprites = numSprites; } else if (prevNumAllocatedSprites < numSprites) { Array.Resize(ref mSprites, numSprites); Array.Resize(ref mVertices, numSprites); Array.Resize(ref mUVs, numSprites); Array.Resize(ref mColors, numSprites); Array.Resize(ref mTriangles, numSprites); Array.Resize(ref mMeshes, numSprites); mBatchSprites = new int[numSprites]; mBatchCounts = new int[numSprites]; mNumAllocatedSprites = numSprites; } for (int i = prevNumAllocatedSprites; i < mNumAllocatedSprites; i++) { mSprites[i] = new ZSprite(); mSprites[i].id = i; if (i > MaxSpritesPerBatch) { continue; } int numSpritesInBatch = i; mVertices[numSpritesInBatch] = new Vector3[numSpritesInBatch * 4]; mUVs[numSpritesInBatch] = new Vector2[numSpritesInBatch * 4]; mColors[numSpritesInBatch] = new Color32[numSpritesInBatch * 4]; mTriangles[numSpritesInBatch] = new int[numSpritesInBatch * 6]; for (int n = 0; n < i; n++) { int iOffset = n * 6; int vOffset = n * 4; mTriangles[numSpritesInBatch][iOffset] = vOffset; mTriangles[numSpritesInBatch][iOffset + 1] = vOffset + 3; mTriangles[numSpritesInBatch][iOffset + 2] = vOffset + 1; mTriangles[numSpritesInBatch][iOffset + 3] = vOffset + 2; mTriangles[numSpritesInBatch][iOffset + 4] = vOffset + 3; mTriangles[numSpritesInBatch][iOffset + 5] = vOffset; } mMeshes[numSpritesInBatch] = new Mesh(); mMeshes[numSpritesInBatch].MarkDynamic(); mMeshes[numSpritesInBatch].vertices = mVertices[numSpritesInBatch]; mMeshes[numSpritesInBatch].uv = mUVs[numSpritesInBatch]; mMeshes[numSpritesInBatch].colors32 = mColors[numSpritesInBatch]; mMeshes[numSpritesInBatch].triangles = mTriangles[numSpritesInBatch]; } } public ZSprite CreateSprite() { if (mNumAllocatedSprites == mNumUsedSprites) { ReserveSpriteMemory(mNumAllocatedSprites * 2); } ZSprite sprite = mSprites[mNumUsedSprites++]; return sprite; } public void RemoveSprite(ZSprite sprite) { if (sprite == null || sprite.id < 0 || sprite.id >= mNumUsedSprites || mSprites[sprite.id] != sprite) { return; } // Swap the last sprite with the removed one mNumUsedSprites--; mSprites[sprite.id] = mSprites[mNumUsedSprites]; mSprites[sprite.id].id = sprite.id; mSprites[mNumUsedSprites] = sprite; ReleaseMaterial(sprite.material); sprite.id = mNumUsedSprites; sprite.material = null; } public ZSpriteMaterial AddMaterial(Material material) { ZSpriteMaterial materialRef = Array.Find(mMaterials, m => m.material == material); if (materialRef == null) { if (mNumUsedMaterials == mNumAllocatedMaterials) { if (mNumAllocatedMaterials == 0) { mNumAllocatedMaterials = 1; } else { mNumAllocatedMaterials *= 2; } Array.Resize(ref mMaterials, mNumAllocatedMaterials); for (int i = mNumUsedMaterials; i < mNumAllocatedMaterials; i++) { mMaterials[i] = new ZSpriteMaterial(); mMaterials[i].id = i; } } materialRef = mMaterials[mNumUsedMaterials++]; materialRef.material = material; } return RetainMaterial(materialRef); } public ZSpriteMaterial RetainMaterial(ZSpriteMaterial materialRef) { if (materialRef != null) { materialRef.refCount++; } return materialRef; } public void ReleaseMaterial(ZSpriteMaterial materialRef) { if (materialRef == null || materialRef.id < 0 || materialRef.id >= mNumUsedMaterials || mMaterials[materialRef.id] != materialRef) { return; } materialRef.refCount--; if (materialRef.refCount <= 0) { // Swap the last material ref with the removed one mNumUsedMaterials--; mMaterials[materialRef.id] = mMaterials[mNumUsedMaterials]; mMaterials[materialRef.id].id = materialRef.id; mMaterials[mNumUsedMaterials] = materialRef; materialRef.id = mNumUsedMaterials; materialRef.refCount = 0; materialRef.material = null; } } public void OnDisable() { // Release all materials while (mNumUsedMaterials > 0) { mNumUsedMaterials--; mMaterials[mNumUsedMaterials].refCount = 0; mMaterials[mNumUsedMaterials].material = null; } // Release all sprites while (mNumUsedSprites > 0) { mNumUsedSprites--; mSprites[mNumUsedSprites].material = null; } } void LateUpdate() { CreateBatches(); } void CreateBatches() { // Put the sprites in buckets instead of true sorting // Hopefully, we can even speed this up later by not rebuilding the buckets every frame // Have to figure out how to be flexible though without actually making a lot of function calls // Maybe the stats will show that we don't actually update the bucket very much? for (int i = 0; i < mNumUsedSprites; i++) { ZSprite sprite = mSprites[i]; int bucketIndex = sprite.bucket; int bucketCount = mBucketCounts[bucketIndex]; if (bucketCount < mMaxSpritesPerBucket) { mBuckets[bucketIndex * mMaxSpritesPerBucket + bucketCount] = i; mBucketCounts[bucketIndex]++; } } #if LOG_DEBUG_STATS int maxInBucket = 0; string debugStats = "ZSpriteManager::OnRenderObject " + Time.time; #endif int numSprites = 0; for (int i = 0; i < mNumBuckets; i++) { #if LOG_DEBUG_STATS if (mBucketCounts[i] > maxInBucket) { maxInBucket = mBucketCounts[i]; } #endif int bucketBegin = i * mMaxSpritesPerBucket; int bucketEnd = bucketBegin + mBucketCounts[i]; mBucketCounts[i] = 0; for (int bucketIndex = bucketBegin; bucketIndex < bucketEnd; bucketIndex++) { int spriteIndex = mBuckets[bucketIndex]; mBatchSprites[numSprites++] = spriteIndex; } } mNumBatches = 0; int material = -1; int numSpritesInBatch = 0; for (int i = 0; i < numSprites; i++) { ZSprite sprite = mSprites[mBatchSprites[i]]; if (sprite.material.id == material && numSpritesInBatch < MaxSpritesPerBatch) { numSpritesInBatch++; } else { if (numSpritesInBatch > 0) { mBatchCounts[mNumBatches] = numSpritesInBatch; mNumBatches++; #if LOG_DEBUG_STATS debugStats += String.Format(" {0}:{1}", material, numSpritesInBatch); #endif } material = sprite.material.id; numSpritesInBatch = 1; } } if (numSpritesInBatch > 0) { mBatchCounts[mNumBatches] = numSpritesInBatch; mNumBatches++; #if LOG_DEBUG_STATS debugStats += String.Format(" {0}:{1}", id, numSpritesInBatch); #endif } #if LOG_DEBUG_STATS Debug.Log(String.Format("{0}\nNumBatches = {1} MaxInBucket = {2}", debugStats, numBatches, maxInBucket)); #endif } void OnRenderObject() { Camera camera = Camera == null ? UnityEngine.Camera.main : Camera; /* #if UNITY_EDITOR if (UnityEngine.Camera.current != camera && Array.IndexOf(UnityEditor.SceneView.GetAllSceneCameras(), UnityEngine.Camera.current) == -1) { return; } #else */ if (UnityEngine.Camera.current != camera) { return; } //#endif //CreateBatches(); int spriteIndex = 0; for (int i = 0; i < mNumBatches; i++) { int numSpritesInBatch = mBatchCounts[i]; Vector3[] vertices = mVertices[numSpritesInBatch]; Vector2[] uvs = mUVs[numSpritesInBatch]; Color32[] colors = mColors[numSpritesInBatch]; Material material = mSprites[mBatchSprites[spriteIndex]].material.material; int numElements = numSpritesInBatch * 4; for (int vOffset = 0; vOffset < numElements; vOffset += 4) { ZSprite batchedSprite = mSprites[mBatchSprites[spriteIndex++]]; vertices[vOffset] = batchedSprite.vertices[0]; vertices[vOffset + 1] = batchedSprite.vertices[1]; vertices[vOffset + 2] = batchedSprite.vertices[2]; vertices[vOffset + 3] = batchedSprite.vertices[3]; uvs[vOffset] = batchedSprite.uvs[0]; uvs[vOffset + 1] = batchedSprite.uvs[1]; uvs[vOffset + 2] = batchedSprite.uvs[2]; uvs[vOffset + 3] = batchedSprite.uvs[3]; colors[vOffset] = batchedSprite.color; colors[vOffset + 1] = batchedSprite.color; colors[vOffset + 2] = batchedSprite.color; colors[vOffset + 3] = batchedSprite.color; } Mesh mesh = mMeshes[numSpritesInBatch]; mesh.vertices = vertices; mesh.uv = uvs; mesh.colors32 = colors; material.SetPass(0); Graphics.DrawMeshNow(mesh, mZeroVector, mIdentityQuaternion); } } } <file_sep>/Assets/game_code/Util.cs using System; using UnityEngine; public class Util{ public static System.Random rand = new System.Random(); public static float rand_range(float min, float max) { float r = (float)rand.NextDouble(); return (max-min)*r + min; } public static float vec_dist(Vector3 a, Vector3 b) { return (float)Math.Abs(Math.Sqrt(Math.Pow(a.x-b.x,2)+Math.Pow(a.y-b.y,2)+Math.Pow(a.z-b.z,2))); } public static GameObject FindInHierarchy(GameObject root, string name) { if (root == null || root.name == name) { return root; } Transform child = root.transform.Find(name); if (child != null) { return child.gameObject; } int numChildren = root.transform.childCount; for (int i = 0; i < numChildren; i++) { GameObject go = FindInHierarchy(root.transform.GetChild(i).gameObject, name); if (go != null) { return go; } } return null; } } <file_sep>/Assets/game_code/EnemyManager.cs using UnityEngine; using System.Collections.Generic; using System; public class EnemyManager : MonoBehaviour { public static EnemyManager instance; List<Enemy> enemies = new List<Enemy>(); int ct = 0; void Start () { instance = this; } void Update () { ct++; if (ct%25==0) { generate_enemy(); } for (int i = enemies.Count-1; i >= 0; i--) { Enemy b = enemies[i]; b.update(); List<Bullet> bullets = BulletManager.instance.bullets; bool hit = false; Vector3 enemy_pos = b.get_position(); for (int j = bullets.Count-1; j >= 0; j--) { Vector3 bullet_pos = bullets[j].get_position(); if (Util.vec_dist(enemy_pos,bullet_pos) < 1.5f) { hit = true; GameGUI.instance.score++; EffectManager.instance.add_effect(new Effect("Explosion",enemy_pos,100)); } } if (hit || b.should_remove()) { enemies.RemoveAt(i); b.do_remove(); } } } void generate_enemy() { Vector3 pos = new Vector3( Util.rand_range(GameControl.X_MIN,GameControl.X_MAX), Util.rand_range(GameControl.Y_MIN,GameControl.Y_MAX), 75 ); GameObject enemy_object = (GameObject)Instantiate(Resources.Load("A10_red")); enemy_object.transform.parent = this.gameObject.transform; enemies.Add(new Enemy(pos,enemy_object)); } } <file_sep>/Assets/game_code/Bullet.cs using System; using UnityEngine; public class Bullet { Vector3 vel; GameObject obj; int ct; public Bullet (Vector3 pos, Vector3 _vel, GameObject _obj) { vel = _vel; obj = _obj; obj.transform.position = pos; ct = 100; } public void update() { Vector3 pos = obj.transform.position; pos.x += vel.x; pos.y += vel.y; pos.z += vel.z; obj.transform.position = pos; ct--; } public bool should_remove() { return ct <= 0; } public void do_remove() { GameObject.Destroy(obj); obj = null; } public Vector3 get_position() { return obj.transform.position; } } <file_sep>/Assets/TK2DROOT/tk2d/Code/Sprites/tk2dSprite.cs using UnityEngine; using System; using System.Collections; [AddComponentMenu("2D Toolkit/Sprite/tk2dSprite")] [RequireComponent(typeof(MeshRenderer))] [RequireComponent(typeof(MeshFilter))] [ExecuteInEditMode] /// <summary> /// Sprite implementation which maintains its own Unity Mesh. Leverages dynamic batching. /// </summary> public class tk2dSprite : tk2dBaseSprite { private const float MIN_Y_VALUE = 0.0f; private const float MAX_Y_VALUE = 160.0f; private const float MIN_Z_VALUE = -200.0f; private const float MAX_Z_VALUE = 50.0f; private const float MIN_X_VALUE = 0.0f; private const float MAX_X_VALUE = 60.0f; private const float LERP_Z_DENOM = 1.0f / (MIN_Z_VALUE - MAX_Z_VALUE); private const float LERP_X_DENOM = 0.0f / (MIN_X_VALUE - MAX_X_VALUE); Mesh mesh; Vector3[] meshVertices; Vector3[] meshNormals = null; Vector4[] meshTangents = null; Color[] meshColors; private Transform mTransform; public ZSpriteManager mZSpriteManager = null; public ZSprite mZSprite = null; public Vector3 mZPreviousPosition; new void Awake() { base.Awake(); mTransform = transform; } void OnEnable() { if (Application.isPlaying && tk2dSystem.useZSpriteManager) { if (mZSpriteManager == null) { mZSpriteManager = ZSpriteManager.DefaultSpriteManager; } } if (mZSpriteManager == null) { // Create mesh, independently to everything else mesh = new Mesh(); mesh.hideFlags = HideFlags.DontSave; GetComponent<MeshFilter>().mesh = mesh; } // This will not be set when instantiating in code // In that case, Build will need to be called if (Collection) { // reset spriteId if outside bounds // this is when the sprite collection data is corrupt if (_spriteId < 0 || _spriteId >= Collection.Count) _spriteId = 0; Build(); } } void OnDisable() { if (mZSprite != null) { mZSpriteManager.RemoveSprite(mZSprite); mZSprite = null; } } protected void OnDestroy() { if (mesh) { #if UNITY_EDITOR DestroyImmediate(mesh); #else Destroy(mesh); #endif } if (meshColliderMesh) { #if UNITY_EDITOR DestroyImmediate(meshColliderMesh); #else Destroy(meshColliderMesh); #endif } } public override void Build() { if (mZSpriteManager == null) { var sprite = collectionInst.spriteDefinitions[spriteId]; meshVertices = new Vector3[sprite.positions.Length]; meshColors = new Color[sprite.positions.Length]; meshNormals = new Vector3[0]; meshTangents = new Vector4[0]; if (sprite.normals != null && sprite.normals.Length > 0) { meshNormals = new Vector3[sprite.normals.Length]; } if (sprite.tangents != null && sprite.tangents.Length > 0) { meshTangents = new Vector4[sprite.tangents.Length]; } SetPositions(meshVertices, meshNormals, meshTangents); SetColors(meshColors); if (mesh == null) { mesh = new Mesh(); mesh.hideFlags = HideFlags.DontSave; GetComponent<MeshFilter>().mesh = mesh; } mesh.Clear(); mesh.vertices = meshVertices; mesh.normals = meshNormals; mesh.tangents = meshTangents; mesh.colors = meshColors; mesh.uv = sprite.uvs; mesh.triangles = sprite.indices; UpdateMaterial(); CreateCollider(); } else { if (mZSprite == null) { mZSprite = mZSpriteManager.CreateSprite(); } renderer.enabled = false; SetZSpritePosition(); UpdateMaterial(); CreateCollider(); } } /// <summary> /// Adds a tk2dSprite as a component to the gameObject passed in, setting up necessary parameters and building geometry. /// Convenience alias of tk2dBaseSprite.AddComponent<tk2dSprite>(...). /// </summary> public static tk2dSprite AddComponent(GameObject go, tk2dSpriteCollectionData spriteCollection, int spriteId) { return tk2dBaseSprite.AddComponent<tk2dSprite>(go, spriteCollection, spriteId); } /// <summary> /// Create a sprite (and gameObject) displaying the region of the texture specified. /// Use <see cref="tk2dSpriteCollectionData.CreateFromTexture"/> if you need to create a sprite collection /// with multiple sprites. /// Convenience alias of tk2dBaseSprite.CreateFromTexture<tk2dSprite>(...) /// </summary> public static GameObject CreateFromTexture(Texture2D texture, tk2dRuntime.SpriteCollectionSize size, Rect region, Vector2 anchor) { return tk2dBaseSprite.CreateFromTexture<tk2dSprite>(texture, size, region, anchor); } protected override void UpdateGeometry() { UpdateGeometryImpl(); } protected override void UpdateColors() { UpdateColorsImpl(); } protected override void UpdateVertices() { UpdateVerticesImpl(); } protected void UpdateColorsImpl() { #if UNITY_EDITOR // This can happen with prefabs in the inspector if ((mesh == null || meshColors == null || meshColors.Length == 0) && (mZSprite == null)) return; #endif if (mZSprite == null) { SetColors(meshColors); mesh.colors = meshColors; } else { Color32 c = _color; if (collectionInst.premultipliedAlpha) { c.r *= c.a; c.g *= c.a; c.b *= c.a; } mZSprite.color = c; } } protected void UpdateVerticesImpl() { #if UNITY_EDITOR // This can happen with prefabs in the inspector if ((mesh == null || meshVertices == null || meshVertices.Length == 0) && mZSprite == null) return; #endif if (mZSprite == null) { var sprite = collectionInst.spriteDefinitions[spriteId]; // Clear out normals and tangents when switching from a sprite with them to one without if (sprite.normals.Length != meshNormals.Length) { meshNormals = (sprite.normals != null && sprite.normals.Length > 0)?(new Vector3[sprite.normals.Length]):(new Vector3[0]); } if (sprite.tangents.Length != meshTangents.Length) { meshTangents = (sprite.tangents != null && sprite.tangents.Length > 0)?(new Vector4[sprite.tangents.Length]):(new Vector4[0]); } SetPositions(meshVertices, meshNormals, meshTangents); mesh.vertices = meshVertices; mesh.normals = meshNormals; mesh.tangents = meshTangents; mesh.uv = sprite.uvs; mesh.bounds = GetBounds(); } else { SetZSpritePosition(); } } protected void UpdateGeometryImpl() { #if UNITY_EDITOR // This can happen with prefabs in the inspector if (mesh == null && mZSprite == null) return; #else if (mesh == null && mZSprite == null) Build(); #endif if (mZSprite == null) { var sprite = collectionInst.spriteDefinitions[spriteId]; if (meshVertices == null || meshVertices.Length != sprite.positions.Length) { meshVertices = new Vector3[sprite.positions.Length]; meshNormals = (sprite.normals != null && sprite.normals.Length > 0)?(new Vector3[sprite.normals.Length]):(new Vector3[0]); meshTangents = (sprite.tangents != null && sprite.tangents.Length > 0)?(new Vector4[sprite.tangents.Length]):(new Vector4[0]); meshColors = new Color[sprite.positions.Length]; } SetPositions(meshVertices, meshNormals, meshTangents); SetColors(meshColors); mesh.Clear(); mesh.vertices = meshVertices; mesh.normals = meshNormals; mesh.tangents = meshTangents; mesh.colors = meshColors; mesh.uv = sprite.uvs; mesh.bounds = GetBounds(); mesh.triangles = sprite.indices; } else { SetZSpritePosition(); } } void SetZSpritePosition() { var sprite = collectionInst.spriteDefinitions[spriteId]; Vector3 p = transform.position; Matrix4x4 m = transform.localToWorldMatrix; Color32 c = _color; if (collectionInst.premultipliedAlpha) { c.r *= c.a; c.g *= c.a; c.b *= c.a; } float depth = (p.z - MAX_Z_VALUE) * LERP_Z_DENOM; if (depth < 0) { depth = 0; } else if (depth > 1.0f) { depth = 1.0f; } mZSprite.vertices[0].x = sprite.positions[0].x * _scale.x; mZSprite.vertices[0].y = sprite.positions[0].y * _scale.y; mZSprite.vertices[1].x = sprite.positions[1].x * _scale.x; mZSprite.vertices[1].y = sprite.positions[1].y * _scale.y; mZSprite.vertices[2].x = sprite.positions[2].x * _scale.x; mZSprite.vertices[2].y = sprite.positions[2].y * _scale.y; mZSprite.vertices[3].x = sprite.positions[3].x * _scale.x; mZSprite.vertices[3].y = sprite.positions[3].y * _scale.y; mZSprite.vertices[0] = m.MultiplyPoint3x4(mZSprite.vertices[0]); mZSprite.vertices[1] = m.MultiplyPoint3x4(mZSprite.vertices[1]); mZSprite.vertices[2] = m.MultiplyPoint3x4(mZSprite.vertices[2]); mZSprite.vertices[3] = m.MultiplyPoint3x4(mZSprite.vertices[3]); mZSprite.vertices[0].z = p.z; mZSprite.vertices[1].z = p.z; mZSprite.vertices[2].z = p.z; mZSprite.vertices[3].z = p.z; mZSprite.bucket = (UInt16)(depth * (mZSpriteManager.NumBuckets - 1)); mZPreviousPosition = p; } void LateUpdate() { if (mZSprite != null) { Vector3 p = mTransform.position; if (p.x != mZPreviousPosition.x || p.y != mZPreviousPosition.y || p.z != mZPreviousPosition.z) { SetZSpritePosition(); } } } protected override void UpdateMaterial() { if (mZSprite == null) { if (renderer.sharedMaterial != collectionInst.spriteDefinitions[spriteId].materialInst) renderer.material = collectionInst.spriteDefinitions[spriteId].materialInst; } else { tk2dSpriteDefinition sprite = collectionInst.spriteDefinitions[spriteId]; Material material = sprite.materialInst; if (mZSprite.material == null) { mZSprite.material = mZSpriteManager.AddMaterial(material); } else if (mZSprite.material.material != material) { mZSpriteManager.ReleaseMaterial(mZSprite.material); mZSprite.material = mZSpriteManager.AddMaterial(material); } mZSprite.uvs[0] = sprite.uvs[0]; mZSprite.uvs[1] = sprite.uvs[1]; mZSprite.uvs[2] = sprite.uvs[2]; mZSprite.uvs[3] = sprite.uvs[3]; mZSprite.color = color; } } protected override int GetCurrentVertexCount() { #if UNITY_EDITOR if (meshVertices == null) return 0; #else if (meshVertices == null && mZSprite == null) Build(); #endif // Really nasty bug here found by <NAME>. return mZSprite == null ? meshVertices.Length : mZSprite.vertices.Length; } public override void ForceBuild() { base.ForceBuild(); GetComponent<MeshFilter>().mesh = mesh; } } <file_sep>/Assets/game_code/Effect.cs using UnityEngine; using System.Collections; public class Effect { GameObject obj; int ct; public Effect(string resc, Vector3 pos, int _ct) { obj = (GameObject)EffectManager.Instantiate(Resources.Load(resc)); obj.transform.position = pos; ct = _ct; obj.transform.parent = EffectManager.instance.gameObject.transform; } public void update() { ct--; } public bool should_remove() { return ct <= 0; } public void do_remove() { GameObject.Destroy(obj); obj = null; } } <file_sep>/Assets/TK2DROOT/tk2d/Editor/Sprites/SpriteAnimationEditor/tk2dSpriteAnimationPreview.cs using UnityEngine; using UnityEditor; using System.Collections; public class tk2dSpriteAnimationPreview { public enum GridTypes { LightChecked, MediumChecked, DarkChecked, BlackChecked, LightSolid, MediumSolid, DarkSolid, BlackSolid } public GridTypes GridType { get { return (GridTypes)tk2dPreferences.inst.animBackground; } set { if (tk2dPreferences.inst.animBackground != (int)value) { tk2dPreferences.inst.animBackground = (int)value; DestroyGridTexture(); } } } tk2dSpriteThumbnailCache spriteThumbnailRenderer = new tk2dSpriteThumbnailCache(); private void Init() { if (gridTexture == null) { gridTexture = new Texture2D(16, 16); Color c0 = Color.white; Color c1 = new Color(0.8f, 0.8f, 0.8f, 1.0f); switch (GridType) { case GridTypes.LightChecked: c0 = new Color32(255, 255, 255, 255); c1 = new Color32(204, 204, 204, 255); break; case GridTypes.MediumChecked: c0 = new Color32(153, 153, 153, 255); c1 = new Color32(102, 102, 102, 255); break; case GridTypes.DarkChecked: c0 = new Color32( 51, 51, 51, 255); c1 = new Color32(102, 102, 102, 255); break; case GridTypes.BlackChecked: c0 = new Color32( 0, 0, 0, 255); c1 = new Color32( 51, 51, 51, 255); break; case GridTypes.LightSolid: c0 = new Color32(255, 255, 255, 255); c1 = c0; break; case GridTypes.MediumSolid: c0 = new Color32(153, 153, 153, 255); c1 = c0; break; case GridTypes.DarkSolid: c0 = new Color32( 51, 51, 51, 255); c1 = c0; break; case GridTypes.BlackSolid: c0 = new Color32( 0, 0, 0, 255); c1 = c0; break; } for (int y = 0; y < gridTexture.height; ++y) { for (int x = 0; x < gridTexture.width; ++x) { bool xx = (x < gridTexture.width / 2); bool yy = (y < gridTexture.height / 2); gridTexture.SetPixel(x, y, (xx == yy)?c0:c1); } } gridTexture.Apply(); gridTexture.filterMode = FilterMode.Point; gridTexture.hideFlags = HideFlags.HideAndDontSave; } } void DestroyGridTexture() { if (gridTexture != null) { Object.DestroyImmediate(gridTexture); gridTexture = null; } } public void Destroy() { spriteThumbnailRenderer.Destroy(); DestroyGridTexture(); } void Repaint() { HandleUtility.Repaint(); } public int Frame { get; set; } Vector2 translate = Vector2.zero; float scale = 1.0f; bool dragging = false; public void ResetTransform() { scale = 1.0f; translate.Set(0, 0); Repaint(); } // Background Texture2D gridTexture = null; public void Draw(Rect r, tk2dSpriteDefinition sprite) { Init(); Event ev = Event.current; switch (ev.type) { case EventType.MouseDown: if (r.Contains(ev.mousePosition)) { dragging = true; ev.Use(); } break; case EventType.MouseDrag: if (dragging && r.Contains(ev.mousePosition)) { translate += ev.delta; ev.Use(); Repaint(); } break; case EventType.MouseUp: dragging = false; break; case EventType.ScrollWheel: if (r.Contains(ev.mousePosition)) { scale = Mathf.Clamp(scale + ev.delta.y * 0.1f, 0.1f, 10.0f); ev.Use(); Repaint(); } break; } // Draw grid float scl = 16.0f; GUI.DrawTextureWithTexCoords(r, gridTexture, new Rect(-translate.x / scl, translate.y / scl, r.width / scl, r.height / scl), false); // Draw sprite if (sprite != null) { spriteThumbnailRenderer.DrawSpriteTextureCentered(r, sprite, translate, scale, Color.white); } } } <file_sep>/Assets/game_code/EffectManager.cs using UnityEngine; using System.Collections.Generic; public class EffectManager : MonoBehaviour { public static EffectManager instance; public List<Effect> effects = new List<Effect>(); void Start () { instance = this; } void Update () { for (int i = effects.Count-1; i >= 0; i--) { Effect b = effects[i]; b.update(); if (b.should_remove()) { effects.RemoveAt(i); b.do_remove(); } } } public void add_effect(Effect e) { effects.Add(e); } }
67c9476328ffe3cb97bd26895ff20d82db7142bd
[ "C#" ]
13
C#
bagobor/DeepSpace_OculusVR
f9535991d6cd592cf4b43fbe20bc2f152189f16e
3d4dcc873a80b930019960f117662ce95913442b
refs/heads/master
<file_sep>// Business logic function Places(placeName, time, landmarks, notes) { this.placeName = placeName; this.time = time; this.landmarks = landmarks; this.notes = notes; } Places.prototype.nameYear = function() { return this.placeName + " - " + this.time; } // UI logic $(function() { $("form#places").submit(function(e) { e.preventDefault(); var inputName = $("input#name").val(); var inputTime = $("input#time").val(); var inputLandmarks = $("input#landmarks").val(); var inputNotes = $("input#notes").val(); var newPlaces = new Places(inputName, inputTime, inputLandmarks, inputNotes); $("input#name, input#time, input#landmarks, input#notes").val(""); $(".name-output").append("<li><span class='nameYearOutput'>" + newPlaces.nameYear() + "</span></li>"); console.log(newPlaces); $(".nameYearOutput").last().click(function() { $("#infodiv").show(); $("#infodiv h2").text(newPlaces.placeName); $("#info").append("<li>" + newPlaces.time + "</li>") $("#info").append("<li>" + newPlaces.landmarks + "</li>") $("#info").append("<li>" + newPlaces.notes + "</li>") }); }); });
7597ed18fce6c4887bee5de3a5e576ef4599b7bf
[ "JavaScript" ]
1
JavaScript
saschultz/Places-Webpage
c9ff82c691cd6fcac4057dc4030940d4fc1d7d8a
aa715334cd90b8b69520d4588b31c898d795bcc2
refs/heads/master
<repo_name>trollguy22/skriptimine<file_sep>/praks5/yl11 #!/bin/bash # 10 plussi trykkimine for i in {1..10} do for i in {1..10} do echo -n "+" done echo done echo # skripti lopp <file_sep>/praks7/kujund2 #!/bin/bash # #kolmnurk # ülemine pool for((r=1; r<4; r++)) do # veerud - tärnid # tärnide arv algab 1-st # Igal veerul tärnide arv ei tohi ületada rea numbri for((t=1; t<$(($r+1)); t++)) do echo -n "* " done echo # reavahetus done #alumine pool for((r=4; r>0; r--)) do for((t=1; t<$(($r+1)); t++)) do echo -n "* " done echo done <file_sep>/praks9/naide1 #!/bin/bash for (( i = 1; i <= 5; i++ )) #väline# do for (( j = 1 ; j <= 5; j++ )) #sisemine# do echo -n "$i " done echo "" #uus rida# done <file_sep>/praks9/yl2 #!/bin/bash for (( i = 1; i <= 5; i++ )) #5 rida# do for (( j = 1 ; j <= 3; j++ )) #3 tärni reas do echo -n "* " done echo "" done <file_sep>/praks3/yl1 #!/bin/bash # # keskkonna ja oma muutujate kasutamine # # kasutame kaskkonna muutuja nimega $USER # ja tervitame kasutajat echo "Tere, $USER!" # kuupäeva väärtuse loomine # defineerime vastava väärtusega muutuja kuupaev=`date +'%d. %B'` # valjastame kuupaev koos selgitava teksiga echo "Täna on $kuupaev" # kella väärtuse loomine # defineerime vastava väärtusega muutuja kell=`date +%H:%M` # väljastame kell koos seletusega echo "Kell on $kell" echo "==================" kalender=`cal` echo "$kalender" echo "==================" <file_sep>/praks8/yl1 #!/bin/bash # ip järgi arvuti kontrollimine echo -n "sisesta vahemiku algus: " read algus echo -n "sisesta vahemiku lõpp: " read lopp echo -n > ping_tulemus for((nr=$algus; nr<=$lopp; nr++)) do # paneme ip kokku ip=172.23.13.$nr # teata,e antud ip pingu ping -c 1 $ip > /dev/null # väljund kustutatud # kontroll if [ $? -eq 0 ]; then # kui $? on 0 - kõik korras echo "$ip - ok" >> ping_tulemus # muidu else echo "$ip -not" >> ping_tulemus fi done <file_sep>/praks4/yl1 #!/bin/bash # # arvu kontoll - positiivne või negatiivne # # kontrollime, kas on sisestatud 1 parameeter # kui ei ole, siis trükime välja kasutusjuhend if [ $# -ne 1 ]; then echo "Kasutusjuhend: " echo "$0 arv" echo "Näiteks: $0 5" # kui on kõik korras ja parameetrite arv on 1 else arv=$1 # nüüd kontrollib, kas arv on positiivne # sel juhul arv peab olema suurem kui 0 if [ $arv -gt 0 ]; then # jah, arv on suurem kui 0 - positiivne echo "$arv on positiivne" # kui arv on väiksem kui kui 0 - negatiivne elif [ $arv -lt 0 ]; then echo "$arv on negatiivne" # kui esimene või teine tingimus ei sobi - neutraalne else echo "$arv on neutraalne" # if lause tuleb korralikult lõpetada fi # väline if lause tuleb ka korralikult lõpetada fi <file_sep>/praks7/kujund1 #!/bin/bash # # tärniruut # # tekitame read for((r=1; r<5; r++)) do # kontrollime kui r on 1 või (-o) on 4 if [ $r -eq 1 -o $r -eq 4 ]; then # teeme tärnid for((v=1; v<6; v++)) do echo -n "* " done # vahepealsed else #tärn echo -n "* " # täpid for((v=2; v<5; v++)) do echo -n " " done echo -n "* " fi #reavahetus echo done
c22d5322ec5f4280295de12c19e57c0acbccc387
[ "Shell" ]
8
Shell
trollguy22/skriptimine
3fd1f32094ef941e5c399b11fe85168e7f995958
8c3923566d04530388d6845906e3e96ba3dbd5da
refs/heads/master
<repo_name>heramerom/sample-swagger<file_sep>/template.go package main var templateModel = "// +build sample_swagger\n" + "\n" + "package sample_swagger\n" + "\n" + "type Info struct {\n" + " Description string `json:\"description\"`\n" + " Version string `json:\"version\"`\n" + " Title string `json:\"title\"`\n" + " TermsOfService string `json:\"termsOfService\"`\n" + " Contact struct {\n" + " Email string `json:\"email\"`\n" + " } `json:\"contact\"`\n" + " License struct {\n" + " Name string `json:\"name\"`\n" + " URL string `json:\"url\"`\n" + " } `json:\"license\"`\n" + "}\n" + "\n" + "type Router struct {\n" + " Tags []string `json:\"tags\"`\n" + " Summary string `json:\"summary\"`\n" + " Description string `json:\"description\"`\n" + " OperationID string `json:\"operationId\"`\n" + " Consumes []string `json:\"consumes\"`\n" + " Produces []string `json:\"produces\"`\n" + " Parameters []Parameter `json:\"parameters\"`\n" + " Responses map[string]Response `json:\"responses\"`\n" + "}\n" + "\n" + "type Schema struct {\n" + " Ref string `json:\"$ref,omitempty\"`\n" + "}\n" + "\n" + "type Parameter struct {\n" + " In string `json:\"in\"`\n" + " Name string `json:\"name\"`\n" + " Type string `json:\"type\"`\n" + " Description string `json:\"description\"`\n" + " Required bool `json:\"required\"`\n" + " Schema *Schema `json:\"schema,omitempty\"`\n" + "}\n" + "\n" + "type Response struct {\n" + " Description string `json:\"description\"`\n" + " Schema struct {\n" + " Type string `json:\"type\"`\n" + " Items struct {\n" + " Ref string `json:\"$ref\"`\n" + " } `json:\"items\"`\n" + " Ref string `json:\"$ref\"`\n" + " } `json:\"schema\"`\n" + "}\n" + "\n" + "type Property struct {\n" + " Type string `json:\"type,omitempty\"`\n" + " Format string `json:\"format,omitempty\"`\n" + " Description string `json:\"description,omitempty\"`\n" + " Ref string `json:\"$ref,omitempty\"`\n" + " Items *Definition `json:\"items,omitempty\"`\n" + " Properties *Definition `json:\"properties,omitempty\"`\n" + "\n" + " AdditionalProperties *AdditionalProperties `json:\"additionalProperties,omitempty\"`\n" + "}\n" + "\n" + "type AdditionalProperties struct {\n" + " Type string `json:\"type\"`\n" + " Ref string `json:\"$ref\"`\n" + "}\n" + "\n" + "type NestedProperty struct {\n" + " Id string `json:\"id,omitempty\"`\n" + " Name string `json:\"name,omitempty\"`\n" + "}\n" + "\n" + "type Definition struct {\n" + " Type string `json:\"type,omitempty\"`\n" + " Format string `json:\"format,omitempty\"`\n" + " Items *Definition `json:\"items,omitempty\"`\n" + " Properties map[string]*Definition `json:\"properties,omitempty\"`\n" + " AdditionalProperties *Definition `json:\"additionalProperties,omitempty\"`\n" + " Ref string `json:\"$ref,omitempty\"`\n" + "}\n" + "\n" + "type Swagger struct {\n" + " Swagger string `json:\"swagger\"`\n" + " Info *Info `json:\"info\"`\n" + " Host string `json:\"host\"`\n" + " BasePath string `json:\"basePath\"`\n" + " Schemes []string `json:\"schemes\"`\n" + " Paths map[string]Method `json:\"paths\"`\n" + " Definitions map[string]*Definition `json:\"definitions\"`\n" + "}\n" + "\n" + "type Method map[string]Router\n" + "\n" + "func MapType(typ string) string {\n" + " switch typ {\n" + " case \"int\", \"int8\", \"int16\", \"int32\", \"int64\", \"uint\", \"uint8\", \"uint16\", \"uint32\", \"uint64\":\n" + " return \"integer\"\n" + " case \"string\", \"str\", \"s\":\n" + " return \"string\"\n" + " case \"bool\", \"boolean\", \"b\":\n" + " return \"boolean\"\n" + " case \"object\", \"obj\", \"o\":\n" + " return \"object\"\n" + " case \"float32\", \"float64\":\n" + " return \"number\"\n" + " case \"array\", \"slice\":\n" + " return \"array\"\n" + " case \"map\":\n" + " return \"map\"\n" + " }\n" + " return \"{}\" // any\n" + "}" var templateParser = "// +build sample_swagger\n" + "\n" + "package sample_swagger\n" + "\n" + "import (\n" + " \"encoding/json\"\n" + " \"fmt\"\n" + " \"reflect\"\n" + " \"strings\"\n" + ")\n" + "\n" + "const (\n" + " typeString = \"string\"\n" + " typeInt = \"integer\"\n" + " typeBool = \"boolean\"\n" + " typeNumber = \"number\"\n" + " typeObject = \"object\"\n" + " typeArray = \"array\"\n" + " typeMap = \"map\"\n" + ")\n" + "\n" + "var buildInTypes = map[string]string{\n" + " \"time.Time\": \"string\",\n" + " \"*time.Time\": \"string\",\n" + "}\n" + "\n" + "var definitions = make(map[string]model)\n" + "\n" + "func parse() string {\n" + " var swagger Swagger\n" + " err := json.Unmarshal([]byte(generatorJson), &swagger)\n" + " if err != nil {\n" + " fmt.Printf(\"unmarshal error: %s\", err.Error())\n" + " return \"\"\n" + " }\n" + "\n" + " for _, v := range generatorModels {\n" + " rt := reflect.TypeOf(v)\n" + " rv := reflect.ValueOf(v)\n" + " parseDefines(&rv, rt)\n" + " }\n" + "\n" + " for _, v := range definitions {\n" + " if swagger.Definitions == nil {\n" + " swagger.Definitions = make(map[string]*Definition)\n" + " }\n" + " name, definition := v.toDefinition(false)\n" + " if definition != nil && name != \"\" {\n" + " swagger.Definitions[name] = definition\n" + " }\n" + " }\n" + " if swagger.Swagger == \"\" {\n" + " swagger.Swagger = \"2.0\"\n" + " }\n" + " bs, err := json.Marshal(swagger)\n" + " if err != nil {\n" + " fmt.Printf(\"marshal error: %s\", err.Error())\n" + " return \"\"\n" + " }\n" + " return string(bs)\n" + "}\n" + "\n" + "type model struct {\n" + " Name string\n" + " Type string\n" + " Object *model `json:\"object\"`\n" + " Fields []*model `json:\",omitempty\"` // properties\n" + "\n" + " Anonymous bool\n" + "}\n" + "\n" + "func (m *model) expandFields() []*model {\n" + " var fds []*model\n" + " for _, f := range m.Fields {\n" + " if f.Anonymous && f.Object != nil {\n" + " pm, ok := definitions[f.Object.Name]\n" + " if ok {\n" + " fds = append(fds, pm.expandFields()...)\n" + " }\n" + " } else {\n" + " fds = append(fds, f)\n" + " }\n" + " }\n" + " return fds\n" + "}\n" + "\n" + "func (m *model) toDefinition(ref bool) (name string, definition *Definition) {\n" + "\n" + " if m == nil {\n" + " return\n" + " }\n" + " if !ref && isBaseDefinitions(m.Type) {\n" + " return m.Type, nil\n" + " }\n" + "\n" + " var d Definition\n" + " name = m.Name\n" + " d.Type = m.Type\n" + "\n" + " switch m.Type {\n" + " case typeObject:\n" + " if ref {\n" + " if m.Object != nil {\n" + " if isBaseDefinitions(m.Object.Type) {\n" + " return m.Name, &Definition{Type: m.Object.Type}\n" + " }\n" + " if !isNestedObject(m.Object.Name) {\n" + " return m.Name, &Definition{Type: typeObject, Ref: \"#/definitions/\" + m.Object.Name}\n" + " }\n" + " } else {\n" + " if isBaseDefinitions(m.Type) {\n" + " return m.Name, &Definition{Type: m.Type}\n" + " }\n" + " if !isNestedObject(m.Name) {\n" + " return m.Name, &Definition{Type: typeObject, Ref: \"#/definitions/\" + m.Name}\n" + " }\n" + " }\n" + " }\n" + " if !ref && isNestedObject(name) {\n" + " return m.Name, nil\n" + " }\n" + "\n" + " if m.Object != nil {\n" + " _, d := m.Object.toDefinition(true)\n" + " return m.Name, d\n" + " } else {\n" + " if len(m.Fields) > 0 {\n" + " ps := make(map[string]*Definition, len(m.Fields))\n" + " fds := m.expandFields()\n" + " for _, v := range fds {\n" + " _, ps[v.Name] = v.toDefinition(true)\n" + " }\n" + " d.Properties = ps\n" + " }\n" + " }\n" + " case typeArray:\n" + " if m.Object != nil {\n" + " _, d := m.Object.toDefinition(true)\n" + " return m.Name, &Definition{Type: typeArray, Items: d}\n" + " }\n" + " case typeMap:\n" + " if m.Object != nil {\n" + " _, d := m.Object.toDefinition(true)\n" + " return m.Name, &Definition{Type: typeObject, AdditionalProperties: d}\n" + " }\n" + " }\n" + " definition = &d\n" + " return\n" + "}\n" + "\n" + "func isBaseDefinitions(typ string) bool {\n" + " switch typ {\n" + " case typeObject, typeArray, typeMap:\n" + " return false\n" + " }\n" + " return true\n" + "}\n" + "\n" + "func isNestedObject(name string) bool {\n" + " return strings.Contains(name, \"struct {\")\n" + "}\n" + "\n" + "func parseField(value reflect.Value, typ reflect.Type, fd reflect.StructField) *model {\n" + " // unexport field\n" + " if fd.Name[0] > 'Z' || fd.Name[0] < 'A' {\n" + " return nil\n" + " }\n" + " var f model\n" + " f.Name = strings.Split(fd.Tag.Get(\"json\"), \",\")[0]\n" + " // ignore field\n" + " if f.Name == \"-\" {\n" + " return nil\n" + " }\n" + " f.Anonymous = fd.Anonymous\n" + " if f.Name == \"\" {\n" + " f.Name = fd.Name\n" + " }\n" + " switch typ.Kind() {\n" + " case reflect.String:\n" + " f.Type = typeString\n" + " case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,\n" + " reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n" + " f.Type = typeInt\n" + " case reflect.Float32, reflect.Float64:\n" + " f.Type = typeNumber\n" + " case reflect.Bool:\n" + " f.Type = typeBool\n" + " case reflect.Struct:\n" + " if buildIn, ok := buildInTypes[typ.String()]; ok {\n" + " f.Type = buildIn\n" + " break\n" + " }\n" + " f.Type = typeObject\n" + " m := parseDefines(&value, typ)\n" + " f.Object = &m\n" + " case reflect.Ptr:\n" + " v, t := indirectType(fd.Type)\n" + " return parseField(v, t, fd)\n" + " case reflect.Array, reflect.Slice:\n" + " f.Type = typeArray\n" + " v, t := indirectType(fd.Type.Elem())\n" + " m := parseDefines(&v, t)\n" + " f.Object = &m\n" + " case reflect.Map:\n" + " f.Type = typeMap\n" + " v, t := indirectType(fd.Type.Elem())\n" + " vm := parseDefines(&v, t)\n" + " f.Object = &vm\n" + " }\n" + " return &f\n" + "}\n" + "\n" + "func nameOfType(t reflect.Type) string {\n" + " return t.String()\n" + "}\n" + "\n" + "func indirectType(t reflect.Type) (reflect.Value, reflect.Type) {\n" + " switch t.Kind() {\n" + " case reflect.Ptr:\n" + " return reflect.Indirect(reflect.New(t.Elem())), t.Elem()\n" + " }\n" + " return reflect.Indirect(reflect.New(t)), t\n" + "}\n" + "\n" + "func parseDefines(v *reflect.Value, t reflect.Type) model {\n" + " if v == nil {\n" + " return model{}\n" + " }\n" + "\n" + " switch t.Kind() {\n" + " case reflect.Ptr:\n" + " if v.IsNil() {\n" + " v, t := indirectType(t)\n" + " return parseDefines(&v, t)\n" + " }\n" + " }\n" + "\n" + " if t.Kind() == reflect.Ptr {\n" + " obj := reflect.Indirect(*v).Interface()\n" + " v := reflect.ValueOf(obj)\n" + " t := reflect.TypeOf(obj)\n" + " return parseDefines(&v, t)\n" + " }\n" + "\n" + " key := nameOfType(t)\n" + " if v, ok := definitions[key]; ok {\n" + " if v.Type == typeObject && !strings.Contains(v.Name, \"struct { \") {\n" + " return model{Name: v.Name, Type: v.Type}\n" + " }\n" + " return v\n" + " }\n" + " // block dead loop\n" + " definitions[key] = sampleModel(key, t)\n" + "\n" + " var m model\n" + " switch t.Kind() {\n" + " case reflect.String:\n" + " m.Name = typeString\n" + " m.Type = typeString\n" + " return m\n" + " case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,\n" + " reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n" + " m.Name = typeInt\n" + " m.Type = typeInt\n" + " return m\n" + " case reflect.Float32, reflect.Float64:\n" + " m.Name = typeNumber\n" + " m.Type = typeNumber\n" + " case reflect.Bool:\n" + " m.Name = typeBool\n" + " m.Type = typeBool\n" + " case reflect.Struct:\n" + " m.Name = key\n" + " m.Type = typeObject\n" + " var fields []*model\n" + " for i := 0; i < v.NumField(); i++ {\n" + " v := v.Field(i)\n" + " f := parseField(v, t.Field(i).Type, t.Field(i))\n" + " if f == nil {\n" + " continue\n" + " }\n" + " fields = append(fields, f)\n" + " }\n" + " m.Fields = fields\n" + " case reflect.Array, reflect.Slice:\n" + " m.Type = typeArray\n" + " fmt.Println(\"name->\", t.Elem().Name())\n" + " v, t := indirectType(t.Elem())\n" + " mm := parseDefines(&v, t)\n" + " m.Object = &mm\n" + " case reflect.Map:\n" + " m.Type = typeMap\n" + " v, t := indirectType(t.Elem())\n" + " fmt.Println(\"typ:\", t)\n" + " mm := parseDefines(&v, t)\n" + " m.Object = &mm\n" + " }\n" + " definitions[key] = m\n" + " if m.Type == typeObject && !isNestedObject(m.Name) {\n" + " return model{Name: m.Name, Type: m.Type}\n" + " }\n" + " return m\n" + "}\n" + "\n" + "func sampleModel(key string, t reflect.Type) model {\n" + " switch t.Kind() {\n" + " case reflect.String:\n" + " return model{Name: key, Type: typeString}\n" + " case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,\n" + " reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n" + " return model{Name: key, Type: typeInt}\n" + " case reflect.Float32, reflect.Float64:\n" + " return model{Name: key, Type: typeNumber}\n" + " case reflect.Bool:\n" + " return model{Name: key, Type: typeBool}\n" + " default:\n" + " return model{Name: key, Type: typeObject}\n" + " }\n" + " return model{}\n" + "}\n" + "" var templateServer = "// +build sample_swagger\n" + "\n" + "package sample_swagger\n" + "\n" + "import (\n" + " \"html/template\"\n" + " \"net/http\"\n" + ")\n" + "\n" + "var serverJson string\n" + "\n" + "var htmlTemp = `\n" + "<!-- HTML for static distribution bundle build -->\n" + "<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + "<head>\n" + " <meta charset=\"UTF-8\">\n" + " <title>Swagger UI</title>\n" + " <link rel=\"stylesheet\" type=\"text/css\"\n" + " href=\"https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.18.2/swagger-ui.css\">\n" + " <link rel=\"icon\" type=\"image/png\" href=\"data:image/png;base64,iVBORw0KGgoAAAANSU<KEY>zen<KEY>QvbYCWKo6go2uvi1zzlU0RFAq+tzNDRVa5fR4FQNrW7<KEY>" + "\" sizes=\"32x32\"/>\n" + " <link rel=\"icon\" type=\"image/png\" href=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9h<KEY>jHMF2tgOn3LeeiYy0LHfDZ6l3LRNJ0G0/mK5JSQi7bZDFDrY0DQf<KEY>n" + "\" sizes=\"16x16\"/>\n" + " <style>\n" + " html {\n" + " box-sizing: border-box;\n" + " overflow: -moz-scrollbars-vertical;\n" + " overflow-y: scroll;\n" + " }\n" + "\n" + " *,\n" + " *:before,\n" + " *:after {\n" + " box-sizing: inherit;\n" + " }\n" + "\n" + " body {\n" + " margin: 0;\n" + " background: #fafafa;\n" + " }\n" + " </style>\n" + "</head>\n" + "\n" + "<body>\n" + "<div id=\"swagger-ui\"></div>\n" + "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.18.2/swagger-ui-bundle.js\"></script>\n" + "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.18.2/swagger-ui-standalone-preset.js\"></script>\n" + "<script>\n" + "\n" + " var spec = {{.Spec}};\n" + "\n" + " spec = JSON.parse(spec);\n" + "\n" + " window.onload = function () {\n" + " const ui = SwaggerUIBundle({\n" + " spec: spec,\n" + " dom_id: '#swagger-ui',\n" + " deepLinking: true,\n" + " presets: [\n" + " SwaggerUIBundle.presets.apis,\n" + " SwaggerUIStandalonePreset.slice(1) // here\n" + " ],\n" + " layout: \"StandaloneLayout\"\n" + " });\n" + " window.ui = ui;\n" + " }\n" + "</script>\n" + "</body>\n" + "</html>\n" + "`\n" + "\n" + "func ServerHTTP(w http.ResponseWriter, r *http.Request) {\n" + " if serverJson == \"\" {\n" + " serverJson = parse()\n" + " if serverJson == \"\" {\n" + " serverJson = \"{}\"\n" + " }\n" + " }\n" + " t, err := template.New(\"swagger\").Parse(htmlTemp)\n" + " if err != nil {\n" + " w.Write([]byte(err.Error()))\n" + " return\n" + " }\n" + " err = t.Execute(w, map[string]string{\"Spec\": serverJson})\n" + " if err != nil {\n" + " w.Write([]byte(err.Error()))\n" + " }\n" + "}\n" + "" var templateServer2 = "// +build !sample_swagger\n" + "\n" + "package sample_swagger\n" + "\n" + "import \"net/http\"\n" + "\n" + "func ServerHTTP(w http.ResponseWriter, r *http.Request) {\n" + " w.Write([]byte(`Please use build tag \"sample_swagger\" to open swagger!`))\n" + "}\n" + "" const templateVars = "// +build sample_swagger\n" + "\n" + "package sample_swagger\n" + "\n" + "import (\n" + " {{Imports}}\n" + ")\n" + "\n" + "var generatorJson = {{GeneratorJson}}\n" + "\n" + "var generatorModels = []interface{}{\n" + "{{GeneratorModels}}\n" + "}\n" + "" <file_sep>/example/main.go package main import ( "fmt" "github.com/heramerom/sample-swagger/example/handler" "github.com/heramerom/sample-swagger/example/sample-swagger" "log" "net/http" ) func myHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello there!\n") } func main() { http.HandleFunc("/", myHandler) // 设置访问路由 http.HandleFunc("/v1/class/detail", handler.SayHello) http.HandleFunc("/swagger.html", sample_swagger.ServerHTTP) log.Fatal(http.ListenAndServe(":8089", nil)) } <file_sep>/swagger.go package main import ( "flag" "fmt" "github.com/heramerom/sample-swagger/template" "os" "path" "path/filepath" "reflect" "strings" ) var verbose = flag.Bool("v", false, "verbose") var out = flag.String("o", "sample-swagger", "out put dir") var pkg = flag.String("pkg", "sample_swagger", "pkg name") var ( gopath string ) func debug(msg ...interface{}) { if *verbose { fmt.Println(msg...) } } func debugf(format string, args ...interface{}) { if *verbose { fmt.Printf(format, args...) } } func dumpFile(api *Api) { err := os.MkdirAll(*out, 0644) if err != nil { fmt.Printf("mkdir error: %s", err.Error()) os.Exit(1) } js := api.Json() err = writeFile("model.go", []byte(templateModel)) if err != nil { fmt.Println("write file error:", err.Error()) os.Exit(1) } err = writeFile("parse.go", []byte(templateParser)) if err != nil { fmt.Println("write file error:", err.Error()) os.Exit(1) } err = writeFile("server.go", []byte(templateServer)) if err != nil { fmt.Println("write file error:", err.Error()) os.Exit(1) } err = writeFile("server2.go", []byte(templateServer2)) if err != nil { fmt.Println("write file error:", err.Error()) os.Exit(1) } str := templateVars str = strings.Replace(str, "{{GeneratorJson}}", "`"+js+"`", 1) str = strings.Replace(str, "{{Imports}}", api.DefinitionImports(), 1) str = strings.Replace(str, "{{GeneratorModels}}", api.DefinitionObjects(), 1) err = writeFile("vars.go", []byte(str)) if err != nil { fmt.Println("write file error: ", err.Error()) os.Exit(1) } } func writeFile(name string, data []byte) error { f, err := os.OpenFile(path.Join(*out, name), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644) if err != nil { return err } defer f.Close() _, err = f.WriteAt(data, 0) if err != nil { return err } return f.Sync() } func isDirectory(f string) (bool, error) { fi, err := os.Stat(f) if err != nil { return false, err } switch mode := fi.Mode(); { case mode.IsDir(): return true, nil case mode.IsRegular(): return false, nil } return false, nil } func isSourceFile(f string) bool { if strings.HasSuffix(f, "_test.go") { return false } if strings.HasSuffix(f, ".go") { return true } return false } func parseFile(f string, api *Api) { fileScanner, err := newFileScanner(f) if err != nil { fmt.Printf("open file error: %s, error: %s", f, err.Error()) os.Exit(1) } defer fileScanner.Close() var defaultPkgPath, defaultPkgName string var currentRouter = emptyRouter for fileScanner.Scan() { line := fileScanner.Text() if !strings.Contains(line, "@sw:") { continue } line = strings.TrimLeft(line, " \t") if !strings.HasPrefix(line, "//") { continue } line = strings.Replace(line, "//", "", 1) scanner := newScanner(line, f, fileScanner.line) cmd := scanner.nextString(' ', '\t') cmd = strings.Replace(cmd, "@sw:", "", 1) switch strings.ToLower(cmd) { case "router", "r": if !reflect.DeepEqual(currentRouter, emptyRouter) { api.AddRouters(currentRouter) } currentRouter = parseRouter(scanner) debugf("Found router: %s", currentRouter) case "param", "p": if reflect.DeepEqual(currentRouter, emptyRouter) { continue } currentRouter.params = append(currentRouter.params, parseParam(scanner)) case "response", "resp", "res", "re": if reflect.DeepEqual(currentRouter, emptyRouter) { continue } currentRouter.response = append(currentRouter.response, parseResponse(scanner)) case "model", "m": if defaultPkgPath == "" { defaultPkgName, defaultPkgPath, err = queryPkgName(gopath, f) if err != nil { fmt.Printf("can not get pkg name: %s, err: %s", f, err.Error()) } } def, err := parseModel(scanner, defaultPkgPath, defaultPkgName, fileScanner) if err != nil { debugf("file: %s, line: %s, syntax error: %s", fileScanner.file, fileScanner.line, err.Error()) continue } if reflect.DeepEqual(def, definition{}) { continue } api.AddDefinitions(def) case "swagger": api.swagger.Swagger = scanner.nextString() case "info", "i": parseInfo(api, scanner) case "basepath": api.swagger.BasePath = scanner.nextString() case "host": api.swagger.Host = scanner.nextString() default: debugf("file: %s, line: %s, unsupport command: %s", fileScanner.file, fileScanner.line, cmd) } } if !reflect.DeepEqual(currentRouter, emptyRouter) { api.AddRouters(currentRouter) } } func parseInfo(api *Api, s *Scanner) { if api.swagger.Info == nil { api.swagger.Info = &template.Info{} } next := s.nextString(',') line := s.nextString() switch strings.ToLower(next) { case "description", "desc": api.swagger.Info.Description = line case "version", "v": api.swagger.Info.Version = line case "title": api.swagger.Info.Title = line case "termsOfService": api.swagger.Info.TermsOfService = line case "contact.email": api.swagger.Info.Contact.Email = line case "license.name": api.swagger.Info.License.Name = line case "license.url": api.swagger.Info.License.URL = line } } func Init() { gopath = queryGoPath() } func main() { flag.Parse() args := flag.Args() if len(args) == 0 { fmt.Println("please input path") os.Exit(1) } Init() api := NewApi() for _, pth := range args { b, err := isDirectory(pth) if err != nil { continue } if b { filepath.Walk(pth, func(path string, info os.FileInfo, err error) error { if !isSourceFile(path) { return nil } parseFile(path, api) return nil }) } else { if !isSourceFile(pth) { continue } parseFile(pth, api) } } dumpFile(api) debug("success!!!") } <file_sep>/README.md ### sample-swagger A sample swagger tool for golang web app. #### Install ``` sh go install github.com/heramerom/sample-swagger ``` #### Usage 1. Add tags in source golang code. ```go // tag ruls // @sw:r [http methods], path, url tags, description // @sw:p name, position, type, require, description // @sw:res response code, type, func sayHelloHandler(w http.ResponseWriter, r *http.Request) { } // @sw:m import package path, reference type Response struct { } ``` 2. Generator sample-swagger package ```sh sample-swagger . ``` 3. Add router handler ```go http.HandleFunc("/swagger.html", sample_swagger.ServerHTTP) ``` 4. run web app ```sh go run -tags sample_swagger main.go ``` 5. access the swagger *http://location/swagger.html* <file_sep>/scan.go package main import ( "bufio" "bytes" "fmt" "os" "strings" ) type Scanner struct { reader *bufio.Reader f string l int } const eof = -1 func newScanner(s, f string, l int) *Scanner { return &Scanner{ reader: bufio.NewReader(bytes.NewBufferString(s)), f: f, l: l, } } func (s *Scanner) next() int { ch, err := s.reader.ReadByte() if err != nil { return eof } return int(ch) } func (s *Scanner) isSep(ch int, sep ...byte) bool { for _, b := range sep { if ch == int(b) { return true } } return false } func (s *Scanner) skipWriteSpace() int { ch := s.next() for ; ch == ' ' || ch == '\t'; ch = s.next() { } return ch } func (s *Scanner) nextString(sep ...byte) string { buf := bytes.NewBuffer(nil) var quota byte ch := s.skipWriteSpace() if ch == '"' || ch == '\'' { quota = byte(ch) ch = s.skipWriteSpace() } for { if ch == eof { if quota != 0x00 { fmt.Println("syntax error: quotation not closed", s.f, s.l) os.Exit(1) } break } if byte(ch) == quota { break } if quota != 0x00 { goto Next } if !s.isSep(ch, sep...) { goto Next } break Next: buf.WriteByte(byte(ch)) ch = s.next() } if !s.isSep(ch, sep...) { ch = s.skipWriteSpace() if !s.isSep(ch, sep...) && ch != eof { fmt.Println("syntax error:", s.f, s.l) os.Exit(1) } } return strings.TrimSpace(buf.String()) } type FileScanner struct { *bufio.Scanner line int file string fp *os.File } func newFileScanner(f string) (fc *FileScanner, err error) { fp, err := os.Open(f) if err != nil { return nil, err } return &FileScanner{ line: 1, file: f, fp: fp, Scanner: bufio.NewScanner(fp), }, nil } func (scanner *FileScanner) Close() { if scanner.fp != nil { scanner.fp.Close() } } func (scanner *FileScanner) Scan() bool { return scanner.Scanner.Scan() } func (scanner *FileScanner) Text() string { line := scanner.Scanner.Text() scanner.line++ return line } <file_sep>/template/model.go // +build sample_swagger package template type Info struct { Description string `json:"description"` Version string `json:"version"` Title string `json:"title"` TermsOfService string `json:"termsOfService"` Contact struct { Email string `json:"email"` } `json:"contact"` License struct { Name string `json:"name"` URL string `json:"url"` } `json:"license"` } type Router struct { Tags []string `json:"tags,omitempty"` Summary string `json:"summary,omitempty"` Description string `json:"description,omitempty"` OperationID string `json:"operationId,omitempty"` Consumes []string `json:"consumes,omitempty"` Produces []string `json:"produces,omitempty"` Parameters []Parameter `json:"parameters,omitempty"` Responses map[string]Response `json:"responses,omitempty"` } type Schema struct { Ref string `json:"$ref,omitempty"` } type Parameter struct { In string `json:"in,omitempty"` Name string `json:"name,omitempty"` Type string `json:"type,omitempty"` Description string `json:"description,omitempty"` Required bool `json:"required,omitempty"` Schema *Schema `json:"schema,omitempty"` } type Response struct { Description string `json:"description"` Schema struct { Type string `json:"type"` Items struct { Ref string `json:"$ref"` } `json:"items"` Ref string `json:"$ref"` } `json:"schema"` } type Property struct { Type string `json:"type,omitempty"` Format string `json:"format,omitempty"` Description string `json:"description,omitempty"` Ref string `json:"$ref,omitempty"` Items *Definition `json:"items,omitempty"` Properties *Definition `json:"properties,omitempty"` AdditionalProperties *AdditionalProperties `json:"additionalProperties,omitempty"` } type AdditionalProperties struct { Type string `json:"type"` Ref string `json:"$ref"` } type NestedProperty struct { Id string `json:"id,omitempty"` Name string `json:"name,omitempty"` } type Definition struct { Type string `json:"type,omitempty"` Format string `json:"format,omitempty"` Items *Definition `json:"items,omitempty"` Properties map[string]*Definition `json:"properties,omitempty"` AdditionalProperties *Definition `json:"additionalProperties,omitempty"` Ref string `json:"$ref,omitempty"` } type Swagger struct { Swagger string `json:"swagger"` Info *Info `json:"info"` Host string `json:"host"` BasePath string `json:"basePath"` Schemes []string `json:"schemes"` Paths map[string]Method `json:"paths"` Definitions map[string]*Definition `json:"definitions"` } type Method map[string]Router func MapType(typ string) string { switch typ { case "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64": return "integer" case "string", "str", "s": return "string" case "bool", "boolean", "b": return "boolean" case "object", "obj", "o": return "object" case "float32", "float64": return "number" case "array", "slice": return "array" case "map": return "map" } return "{}" // any } <file_sep>/template/vars.go // +build sample_swagger package template import () var generatorJson = `{"swagger":null,"info":null,"host":"","basePath":"","schemes":null}` var generatorModels = []interface{}{} <file_sep>/template/parse.go // +build sample_swagger package template import ( "encoding/json" "fmt" "reflect" "strings" ) const ( typeString = "string" typeInt = "integer" typeBool = "boolean" typeNumber = "number" typeObject = "object" typeArray = "array" typeMap = "map" ) var buildInTypes = map[string]string{ "time.Time": "string", "*time.Time": "string", } var definitions = make(map[string]model) func parse() string { var swagger Swagger err := json.Unmarshal([]byte(generatorJson), &swagger) if err != nil { fmt.Printf("unmarshal error: %s\n", err.Error()) return "" } for _, v := range generatorModels { rt := reflect.TypeOf(v) rv := reflect.ValueOf(v) parseDefines(&rv, rt) } for _, v := range definitions { if swagger.Definitions == nil { swagger.Definitions = make(map[string]*Definition) } name, definition := v.toDefinition(false) if definition != nil && name != "" { swagger.Definitions[name] = definition } } if swagger.Swagger == "" { swagger.Swagger = "2.0" } bs, err := json.Marshal(swagger) if err != nil { fmt.Printf("marshal error: %s\n", err.Error()) return "" } return string(bs) } type model struct { Name string Type string Object *model `json:"object"` Fields []*model `json:",omitempty"` // properties Anonymous bool } func (m *model) expandFields() []*model { var fds []*model for _, f := range m.Fields { if f.Anonymous && f.Object != nil { pm, ok := definitions[f.Object.Name] if ok { fds = append(fds, pm.expandFields()...) } } else { fds = append(fds, f) } } return fds } func (m *model) toDefinition(ref bool) (name string, definition *Definition) { if m == nil { return } if !ref && isBaseDefinitions(m.Type) { return m.Type, nil } var d Definition name = m.Name d.Type = m.Type switch m.Type { case typeObject: if ref { if m.Object != nil { if isBaseDefinitions(m.Object.Type) { return m.Name, &Definition{Type: m.Object.Type} } if !isNestedObject(m.Object.Name) { return m.Name, &Definition{Type: typeObject, Ref: "#/definitions/" + m.Object.Name} } } else { if isBaseDefinitions(m.Type) { return m.Name, &Definition{Type: m.Type} } if !isNestedObject(m.Name) { return m.Name, &Definition{Type: typeObject, Ref: "#/definitions/" + m.Name} } } } if !ref && isNestedObject(name) { return m.Name, nil } if m.Object != nil { _, d := m.Object.toDefinition(true) return m.Name, d } else { if len(m.Fields) > 0 { ps := make(map[string]*Definition, len(m.Fields)) fds := m.expandFields() for _, v := range fds { _, ps[v.Name] = v.toDefinition(true) } d.Properties = ps } } case typeArray: if m.Object != nil { _, d := m.Object.toDefinition(true) return m.Name, &Definition{Type: typeArray, Items: d} } case typeMap: if m.Object != nil { _, d := m.Object.toDefinition(true) return m.Name, &Definition{Type: typeObject, AdditionalProperties: d} } } definition = &d return } func isBaseDefinitions(typ string) bool { switch typ { case typeObject, typeArray, typeMap: return false } return true } func isNestedObject(name string) bool { return strings.Contains(name, "struct {") } func parseField(value reflect.Value, typ reflect.Type, fd reflect.StructField) *model { // unexport field if fd.Name[0] > 'Z' || fd.Name[0] < 'A' { return nil } var f model f.Name = strings.Split(fd.Tag.Get("json"), ",")[0] // ignore field if f.Name == "-" { return nil } f.Anonymous = fd.Anonymous if f.Name == "" { f.Name = fd.Name } switch typ.Kind() { case reflect.String: f.Type = typeString case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: f.Type = typeInt case reflect.Float32, reflect.Float64: f.Type = typeNumber case reflect.Bool: f.Type = typeBool case reflect.Struct: if buildIn, ok := buildInTypes[typ.String()]; ok { f.Type = buildIn break } f.Type = typeObject m := parseDefines(&value, typ) f.Object = &m case reflect.Ptr: v, t := indirectType(fd.Type) return parseField(v, t, fd) case reflect.Array, reflect.Slice: f.Type = typeArray v, t := indirectType(fd.Type.Elem()) m := parseDefines(&v, t) f.Object = &m case reflect.Map: f.Type = typeMap v, t := indirectType(fd.Type.Elem()) vm := parseDefines(&v, t) f.Object = &vm } return &f } func nameOfType(t reflect.Type) string { return t.String() } func indirectType(t reflect.Type) (reflect.Value, reflect.Type) { switch t.Kind() { case reflect.Ptr: return reflect.Indirect(reflect.New(t.Elem())), t.Elem() } return reflect.Indirect(reflect.New(t)), t } func parseDefines(v *reflect.Value, t reflect.Type) model { if v == nil { return model{} } switch t.Kind() { case reflect.Ptr: if v.IsNil() { v, t := indirectType(t) return parseDefines(&v, t) } } if t.Kind() == reflect.Ptr { obj := reflect.Indirect(*v).Interface() v := reflect.ValueOf(obj) t := reflect.TypeOf(obj) return parseDefines(&v, t) } key := nameOfType(t) if v, ok := definitions[key]; ok { if v.Type == typeObject && !strings.Contains(v.Name, "struct { ") { return model{Name: v.Name, Type: v.Type} } return v } // block dead loop definitions[key] = sampleModel(key, t) var m model switch t.Kind() { case reflect.String: m.Name = typeString m.Type = typeString return m case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: m.Name = typeInt m.Type = typeInt return m case reflect.Float32, reflect.Float64: m.Name = typeNumber m.Type = typeNumber case reflect.Bool: m.Name = typeBool m.Type = typeBool case reflect.Struct: m.Name = key m.Type = typeObject var fields []*model for i := 0; i < v.NumField(); i++ { v := v.Field(i) f := parseField(v, t.Field(i).Type, t.Field(i)) if f == nil { continue } fields = append(fields, f) } m.Fields = fields case reflect.Array, reflect.Slice: m.Type = typeArray fmt.Println("name->", t.Elem().Name()) v, t := indirectType(t.Elem()) mm := parseDefines(&v, t) m.Object = &mm case reflect.Map: m.Type = typeMap v, t := indirectType(t.Elem()) fmt.Println("typ:", t) mm := parseDefines(&v, t) m.Object = &mm } definitions[key] = m if m.Type == typeObject && !isNestedObject(m.Name) { return model{Name: m.Name, Type: m.Type} } return m } func sampleModel(key string, t reflect.Type) model { switch t.Kind() { case reflect.String: return model{Name: key, Type: typeString} case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return model{Name: key, Type: typeInt} case reflect.Float32, reflect.Float64: return model{Name: key, Type: typeNumber} case reflect.Bool: return model{Name: key, Type: typeBool} default: return model{Name: key, Type: typeObject} } return model{} } <file_sep>/example/sample-swagger/server.go // +build sample_swagger package sample_swagger import ( "html/template" "net/http" ) var serverJson string var htmlTemp = ` <!-- HTML for static distribution bundle build --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Swagger UI</title> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.18.2/swagger-ui.css"> <link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAEPElEQVR4Ab1XA8xlWQx+a9u2bcRex17<KEY>vbYCWKo6go2uvi1zzlU0RFAq+tzNDRVa5fR4FQNrW7Mw/70te+5RnsVnQG66DAKUcS58HZTh4su/Y<KEY> " sizes="32x32"/> <link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABhElEQVR4AZVTA0x1cRz9<KEY>7<KEY>fL4qyTTIp5gnzWgA49kypnZLfQxCpPArRArHgSmwEJrjqdiLeOQooruNbA0Bto<KEY> " sizes="16x16"/> <style> html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; } *, *:before, *:after { box-sizing: inherit; } body { margin: 0; background: #fafafa; } </style> </head> <body> <div id="swagger-ui"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.18.2/swagger-ui-bundle.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.18.2/swagger-ui-standalone-preset.js"></script> <script> var spec = {{.Spec}}; spec = JSON.parse(spec); window.onload = function () { const ui = SwaggerUIBundle({ spec: spec, dom_id: '#swagger-ui', deepLinking: true, presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset.slice(1) // here ], layout: "StandaloneLayout" }); window.ui = ui; } </script> </body> </html> ` func ServerHTTP(w http.ResponseWriter, r *http.Request) { if serverJson == "" { serverJson = parse() if serverJson == "" { serverJson = "{}" } } t, err := template.New("swagger").Parse(htmlTemp) if err != nil { w.Write([]byte(err.Error())) return } err = t.Execute(w, map[string]string{"Spec": serverJson}) if err != nil { w.Write([]byte(err.Error())) } } <file_sep>/misc.go package main import ( "bufio" "github.com/kataras/iris/core/errors" "go/build" "os" "path/filepath" "regexp" "strings" ) func queryGoPath() (pth string) { pth = os.Getenv("GOPATH") if pth == "" { pth = build.Default.GOPATH } return } func queryPkgPath(gopath, f string) (defaultPkg string, err error) { absPath, err := filepath.Abs(f) if err != nil { return } absPath = filepath.Dir(absPath) if !strings.Contains(absPath, gopath) { err = errors.New("out gopath") return } defaultPkg = strings.Replace(absPath, gopath+"/src/", "", 1) return } func queryPkgName(gopath, f string) (pkg string, pkgPath string, err error) { pkgPath, err = queryPkgPath(gopath, f) if err != nil { return } fp, err := os.Open(f) if err != nil { return } defer fp.Close() scanner := bufio.NewScanner(fp) reg := regexp.MustCompile(`^( |\t)*package( |\t)+[a-zA-Z0-9._]*( |\t)*$`) for scanner.Scan() { line := scanner.Text() ss := reg.FindAllString(line, -1) if len(ss) > 0 { pkg = strings.Replace(ss[0], "package", "", 1) break } } pkg = strings.Split(pkg, ".")[0] pkg = strings.TrimSpace(pkg) ps := strings.Split(pkgPath, "/") ps = append(ps[:len(ps)-1], pkg) pkgPath = strings.Join(ps, "/") return } <file_sep>/swagger_test.go package main import ( "github.com/influxdata/influxdb/pkg/testing/assert" "testing" ) func TestParseRouter(t *testing.T) { line := "get,post, /v1/class/detail, base, desc" r := parseRouter(line) assert.Equal(t, r.methods[0], "get") assert.Equal(t, r.methods[1], "post") assert.Equal(t, r.path, "/v1/class/detail") assert.Equal(t, r.tag, "base") assert.Equal(t, r.desc, "desc") } <file_sep>/example/doc.go // @sw:i desc, hello world // @sw:i version, 1.0.0 // @sw:i title, swagger example // @sw:i contact.email, <EMAIL> // @sw:basePath /v1 package main <file_sep>/example/model/model.go package model import "time" type Student struct { Name string Age string } // @sw:m github.com/heramerom/sample-swagger/example/model, model.Class, json, "hello" type Class struct { Name string Students []Student Map map[string]int Map2 map[string]Student Map3 map[string]struct { Int int `json:"int"` } } type Base struct { Name string } // @sw:m github.com/heramerom/sample-swagger/example/model, model.Sub, type Sub struct { Base Age int unExportField string BirthDay time.Time `json:"birth_day"` Map map[string]int Map2 map[string]struct { Name string `json:"name"` } `json:"map_2"` Map3 map[string]*Class } // @sw:m github.com/heramerom/sample-swagger/example/model, model.Self, type Self struct { Value string Left *Self Right *Self } // @sw:m github.com/heramerom/sample-swagger/example/model, model.ArrayObject, type ArrayObject struct { Names []string Subs []*Sub } // @sw:m github.com/heramerom/sample-swagger/example/model, model.NestObject, type NestObject struct { Name string `json:"name"` Data struct { Name string `json:"name"` Age int `json:"age"` } `json:"data"` } // @sw:m type DefaultObj struct { Name string Age int } <file_sep>/scan_test.go package main import ( "bufio" "fmt" "os" "strings" "testing" ) func TestSplit(t *testing.T) { a := "get, /v, hello world, this is a test." t.Log(strings.SplitN(a, ",", 3)) t.Log(strings.SplitN(a, ",", -1)) t.Log(strings.SplitN(a, ",", 4)) t.Log(strings.SplitN(a, ",", 1)) t.Log(strings.SplitN(a, ",", 2)) } func TestFile(t *testing.T) { f, err := os.Open("/home/riki/go/src/github.com/heramerom/sample-swagger/cmd/example.txt") if err != nil { panic(err) } sc := bufio.NewScanner(f) for sc.Scan() { t.Log(sc.Text()) } } func TestScanner(t *testing.T) { line := `@sw:p token, "header" , , 'string' , true, "desc", a , d, 'b, c, d'` s := newScanner(line, "", 1) next := s.nextString(' ', '\t') fmt.Println(next) next = s.nextString(',') fmt.Println(next) next = s.nextString(',') fmt.Println(next) next = s.nextString(',') fmt.Println(next) next = s.nextString(',') fmt.Println(next) next = s.nextString(',') fmt.Println(next) next = s.nextString(',') fmt.Println(next) next = s.nextString() fmt.Println(next) } <file_sep>/example/sample-swagger/server2.go // +build !sample_swagger package sample_swagger import "net/http" func ServerHTTP(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`Please use build tag "sample_swagger" to open swagger!`)) } <file_sep>/generator.go package main import ( "encoding/json" models "github.com/heramerom/sample-swagger/template" "strings" ) type Api struct { swagger models.Swagger definitions []definition } func NewApi() *Api { return &Api{} } func (a *Api) AddRouters(routers ...router) { if a.swagger.Paths == nil { a.swagger.Paths = make(map[string]models.Method) } for _, r := range routers { a.swagger.Paths[r.path] = r.toMethod() } } func (a *Api) AddDefinitions(definitions ...definition) { a.definitions = append(a.definitions, definitions...) } func (a *Api) Json() string { bs, _ := json.MarshalIndent(a.swagger, "", " ") return string(bs) } func (a *Api) DefinitionImports() string { ism := make(map[string]struct{}) for _, d := range a.definitions { ism[d.path] = struct{}{} } var is string for path := range ism { paths := strings.Split(path, "/") is += "sw_" + paths[len(paths)-1] + " \"" + path + "\"" + "\n" } return is } func (a *Api) DefinitionObjects() string { var ds string for _, d := range a.definitions { ds += "new(sw_" + d.model + "),\n" } return ds } <file_sep>/example/sample-swagger/vars.go // +build sample_swagger package sample_swagger import ( sw_model "github.com/heramerom/sample-swagger/example/model" ) var generatorJson = `{ "swagger": "", "info": { "description": "hello world", "version": "1.0.0", "title": "swagger example", "termsOfService": "", "contact": { "email": "<EMAIL>" }, "license": { "name": "", "url": "" } }, "host": "", "basePath": "/v1", "schemes": null, "paths": { "/class/body": { "post": { "tags": [ "class" ], "summary": "class-title, router desc", "description": "", "operationId": "", "consumes": null, "produces": null, "parameters": [ { "in": "body", "name": "", "type": "object", "description": "class id", "required": true, "schema": { "$ref": "#/definitions/model.Class" } } ], "responses": { "200": { "description": "", "schema": { "type": "object", "items": { "$ref": "" }, "$ref": "#/definitions/model.Class" } } } } }, "/class/detail": { "get": { "tags": [ "class" ], "summary": "class-detail", "description": "", "operationId": "", "consumes": null, "produces": null, "parameters": [ { "in": "query", "name": "id", "type": "string", "description": "class id", "required": false } ], "responses": { "200": { "description": "", "schema": { "type": "object", "items": { "$ref": "" }, "$ref": "#/definitions/model.Class" } } } }, "post": { "tags": [ "class" ], "summary": "class-detail", "description": "", "operationId": "", "consumes": null, "produces": null, "parameters": [ { "in": "query", "name": "id", "type": "string", "description": "class id", "required": false } ], "responses": { "200": { "description": "", "schema": { "type": "object", "items": { "$ref": "" }, "$ref": "#/definitions/model.Class" } } } } } }, "definitions": null }` var generatorModels = []interface{}{ new(sw_model.Class), new(sw_model.Sub), new(sw_model.Self), new(sw_model.ArrayObject), new(sw_model.NestObject), new(sw_model.DefaultObj), } <file_sep>/example/handler/handler.go package handler import "net/http" // @sw:r get,post, /class/detail, class, class-detail // @sw:p id, query, , , class id // @sw:resp 200, object, model.Class, func SayHello(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello")) } // @sw:r post, /class/body, class, class-title, router desc // @sw:p , body, object, model.Class, true , class id // @sw:resp 200, object, model.Class, func TestBody(w http.ResponseWriter, r *http.Request) { } <file_sep>/parser.go package main import ( "errors" "fmt" models "github.com/heramerom/sample-swagger/template" "strconv" "strings" ) type router struct { path string methods []string tag string desc string params []param response []response } var emptyRouter = router{} func (r *router) toMethod() models.Method { method := make(map[string]models.Router, 1) var router models.Router router.Summary = r.desc router.Tags = strings.Split(r.tag, ",") for _, v := range r.params { router.Parameters = append(router.Parameters, v.toParameters()) } router.Responses = responses(r.response).toResponses() for _, v := range r.methods { method[v] = router } return models.Method(method) } func (r *router) String() string { return fmt.Sprintf("[%s] %s %s", strings.Join(r.methods, ","), r.path, r.desc) } type param struct { name string typ string object string in string require string desc string } func (p *param) toParameters() models.Parameter { require, _ := strconv.ParseBool(p.require) parameter := models.Parameter{ Name: p.name, In: p.in, Type: models.MapType(p.typ), Description: p.desc, Required: require, } if p.object != "" { parameter.Schema = &models.Schema{ Ref: "#/definitions/" + p.object, } } return parameter } type responses []response func (rs responses) toResponses() map[string]models.Response { var r = make(map[string]models.Response) for _, v := range rs { r[v.code] = v.toResponse() } return r } type response struct { code string typ string model string desc string } func (r response) toResponse() models.Response { var resp models.Response resp.Description = r.desc resp.Schema.Type = models.MapType(r.typ) switch resp.Schema.Type { case "object": if r.model != "" { resp.Schema.Type = "object" resp.Schema.Ref = "#/definitions/" + r.model } case "array": if r.model != "" { resp.Schema.Type = "array" resp.Schema.Items.Ref = "#/definitions/" + r.model } case "map": // do nothing } return resp } // @sw:r get,post, path, tag, desc func parseRouter(s *Scanner) router { var r router var next string Loop: for { next = s.nextString(',') switch next { case "get", "post", "option", "put", "delete", "patch": r.methods = append(r.methods, next) default: break Loop } } r.path = next r.tag = s.nextString(',') r.desc = s.nextString() return r } func parseParam(s *Scanner) param { p := param{} p.name = s.nextString(',') p.in = s.nextString(',') p.typ = s.nextString(',') if p.typ == "obj" || p.typ == "object" { p.typ = "object" p.object = s.nextString(',') } p.require = s.nextString(',') p.desc = s.nextString() if p.typ == "" { p.typ = "string" } if p.in == "" { p.in = "query" } if p.require == "" { p.require = "false" } return p } // 100,obj,model,description func parseResponse(s *Scanner) response { var resp response next := s.nextString(',') resp.code = next if next == "" { resp.code = "default" } next = s.nextString(',') resp.typ = strings.ToLower(next) if resp.typ == "" { resp.typ = "string" } switch resp.typ { case "string", "s": resp.typ = "string" resp.desc = s.nextString() case "object", "obj", "o": resp.typ = "object" next = s.nextString(',') resp.model = next resp.desc = s.nextString() case "array", "a": resp.typ = "array" next = s.nextString(',') resp.model = next resp.desc = s.nextString() } return resp } type definition struct { path string model string tag string desc string } // @sw:m import_path,package,desc func parseModel(s *Scanner, pkgPath string, pkg string, scanner *FileScanner) (def definition, err error) { def.path = s.nextString(',') def.model = s.nextString(',') def.desc = s.nextString() if def.path == "" { def.path = pkgPath } if def.model == "" { def.model, err = getNextModel(scanner) def.model = pkg + "." + def.model } return } func getNextModel(scanner *FileScanner) (model string, err error) { for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) if strings.HasPrefix(line, "type") { model = strings.Split(strings.TrimSpace(strings.Replace(line, "type", "", 1)), " ")[0] return } if line != "" { err = errors.New("syntax error: model define") return } } return }
5d3a6e68fac5b5bd06be2ff746f344b28b5a059e
[ "Markdown", "Go" ]
19
Go
heramerom/sample-swagger
3858132f9bdb3de180c788b42e867db4d52a4ce1
9667cde8c9db58d43e46bec7db5e1c74332d1f07
refs/heads/master
<repo_name>UMD-SIVE-Lab/qesmpi<file_sep>/src/utils/include/population_gen.h #ifndef populationGenerator_h_1 #define populationGenerator_h_1 _1 #include<iostream> #include "namedOptParam.h" #include "population.h" #include <map> #include <fstream> #include <vector> #include <sstream> #include "logger/logger.h" using namespace sivelab; namespace sivelab { class populationGenerator { int dimensions ; ///total number of dimensions being handled int total_population_size; ///total number of possible samples// i.e for bruteforce vector< double > min_domain; vector< double > max_domain; vector< int > steps; vector <vector<double> > setValues; population entire_pop; population generate_entire_pop(); int generate_entire_array(double *&); public: logger log; populationGenerator(vector <double> min_domain_ , vector<double> max_domain_ , vector<int> steps_, vector <vector<double > > setvalues_); //check later populationGenerator(population full_pop_); populationGenerator() {}; population generate_fromfile(std::string fileName, std::vector <namedOptParam> &); population generate_all_pop(); int generate_all_array(double []); population generate_random_pop_usingentire(int number); int generate_random_array_usingentire(double [], int number); population generate_random_pop(int number); int generate_random_array(double [], int number); population normalize_bounds(double par[], int popsize); //should make user all the values are withing the required range : double normalize_value(double value, int sample_index); ///this will normalize the value to the value within the given range and step size even for a single value }; } /*populationGenerator popgen(minValues,maxValues,steps,setValues); population temp_all = popgen.generate_all_pop(); std::cout<<"Enter the no of random samples"<<std::endl; int random; std::cin>>random; population temp_random = popgen.generate_random_pop(random); double * temp_all_1; double * temp_random_1; int all_count,random_count,temp_counter=0; all_count = popgen.generate_all_array(temp_all_1); random_count = popgen.generate_random_array(temp_random_1,random); std::cout<<"all population print "<<std::endl; for(int i =0;i<temp_all.size();i++) { for(int j=0; j<temp_all.at(i).size();j++) { std::cout<<temp_all.at(i).at(j)<<":"<<temp_all_1[temp_counter++]<<"\t"; } std::cout<<std::endl; } std::cout<<"random population time "<<std::endl; for(int i=0;i<random_count;i++) std::cout<<temp_random_1[i]<<":"; std::cout<<"second random "<<std::endl; for(int i =0;i<temp_random.size();i++) { for(int j=0; j<temp_random.at(i).size();j++) { std::cout<<temp_random.at(i).at(j)<<":"<<"\t"; } std::cout<<std::endl; } exit(1);*/ #endif <file_sep>/src/CMakeLists.txt cmake_minimum_required (VERSION 2.8) project (optimizationCode) #MPI FIND_PACKAGE(MPI REQUIRED) #BOOST SET(Boost_USE_STATIC_LIBS ON) SET(Boost_USE_MULTITHREADED OFF) FIND_PACKAGE(Boost COMPONENTS mpi serialization timer chrono REQUIRED) #add sub directory message(STATUS "Adding opt_grammar directory...") add_subdirectory(opt_grammar) SET(ANTLR_INCLUDES ${ANTLR_INCLUDES} PARENT_SCOPE) message(STATUS "Adding utils directory...") add_subdirectory(utils) #fitness function shared library location add_definitions( -DFITNESS_FUNCTION_LIBRARY="${CMAKE_BINARY_DIR}/lib/libfitness.so" ) message(STATUS "Adding MPI framework directory...") add_subdirectory(MPI_framework) #message(STATUS "Adding MPI gpuplume directory...") #add_subdirectory(mpi_gpuplume) message(STATUS "Adding MPI LSM directory...") add_subdirectory(mpi_qes_spf) #include_directories include_directories (${Boost_INCLUDE_DIRS}) include_directories (${MPI_CXX_INCLUDE_PATH}) include_directories (${LIBSIVELAB_PATH}) include_directories (${CMAKE_SOURCE_DIR}/include) include_directories (${CMAKE_SOURCE_DIR}/fitness_lib/include) include_directories (${ANTLR_INCLUDES}) include_directories (${QES_INCLUDE_DIRECTORIES}) #link include_directories LINK_DIRECTORIES (${LIBSIVELAB_PATH}/lib) message(STATUS "Linking the executable with necessary libraries") add_executable(quic quic.cpp) #libraries target_link_libraries (quic ${MPI_LIBRARIES}) target_link_libraries (quic ${Boost_LIBRARIES}) target_link_libraries (quic optfileparser) #target_link_libraries (quic mpi_gpuplume) target_link_libraries (quic mpi_simpleLSM) target_link_libraries (quic mpi_framework) target_link_libraries (quic optm-utils) target_link_libraries (quic sive-quicutil) target_link_libraries (quic sive-util) <file_sep>/src/mpi_gpuplume/gpu_plume_job.cpp #include "iostream" #include "cstdlib" #include <fstream> #include <dirent.h> #include "sys/stat.h" #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include "mpi_gpuplume/gpu_plume_job.h" #include "utils/population_gen.h" //#include "utils/concentrationRedux.h" #include <dlfcn.h> using namespace sivelab; using namespace boost; bool gpu_plume_job::eval_population_fitness(population &pop) { char pwd[FILENAME_MAX]; getcwd(pwd, sizeof(pwd)); log.debug("Current working directory", pwd); void *dl_handle; bool (*func)(population & pop, job &); char *error; char *lib = "../fitness_lib/libfitness.so"; dl_handle = dlopen( lib, RTLD_LAZY ); if (!dl_handle) { printf( "!!! %s\n", dlerror() ); return false; } char *method = "fitness_function"; func = (bool (*)(population &, job &))dlsym( dl_handle, method ); error = dlerror(); if (error != NULL) { printf( "!!! %s\n", error ); return false; } cout<<"func pointer"<<func<<endl; (*func)(pop, *this); cout<<"Am I here"<<endl; dlclose( dl_handle ); return true; } // bool gpu_plume_job::eval_population_fitness(population &pop) // { // if (environment_ready) // { // for (auto &sample : pop) // { // if (!eval_sample_fitness(sample)) // { // //log.debug("Fitness calc for ", pop, ": FAILED"); // return false; // } // else // { // //log.debug("Fitness for ", pop, ":", sample.fitness); // } // } // return true; // } // return false; // } //TDOD: resurrect this when needed // bool gpu_plume_job::eval_sample_fitness( sample &s ) // { // if (environment_ready) // { // ////Fitness Values : // ///// If there is no avgParam fitness value is that of the sample // //// if there is an avgParam then the fitness would be the avg fitness across the avgParam . // ///Make sure this happens // //gl_completed_problems++; ///incrementing the number of problems done . ///should be doing at the end but . // ///The value would not update into the database unless problem is completed so should not be a problem // std::string outputDir = workDir.outputDir; // char cmdBuffer1[1024]; // //sprintf(cmdBuffer1, "cd %s; sh rm_urbplumedata.sh", outputDir.c_str()); // //std::cout<<"pausing before the sample starts "<<std::endl; // //system(cmdBuffer1); // ///TODO single values are being handled // // Given the sample information stored in "s", we should be able to // // "instance" a new simulation. This will be done by generating the // // appropriate files in a tmp directory. Some of the files can be // // "copied" from the base project directory. Others will need to be // // loaded, modified, and then written out to the scratch space. // /// boost::timer t; // double retFitness; // if (!cache.inCache( s, retFitness )) // { // std::string concFile; // std::ostringstream sampleString(""); //name of the sample i.e it should be an 2020 where 20 20 is the current sample // std::ostringstream concString(""); ////name of the concetration file should be concOutput_20202 etc // char dirName[128], dirName2[128]; // // using this for a poor man's fitness function!!!! // double totalMean = 0.0; // long totalExceedances = 0; // // need to get the correct .proj file from the base directory... and not assume a .proj file name // // find the name of the .proj file in the base directory path provided... // std::string projFileName = searchForPROJFile(baseproj_inner_path + "/.."); // // std::string projPrefix = projFileName.substr(0, projFileName.length() - 5); // long probInstID = 1; // ///adding this to make the avg param work :D // unsigned int avgParam_Iterations = avgParam.size(); // if (!use_avgParam) // avgParam_Iterations = 1; ///this to make sure the gpuPlume is run atleast once even if the avgParam is not specified // retFitness = 0.0; // for (unsigned int tsIdx = 0; tsIdx < timeStepSet.size(); tsIdx++) // for (unsigned int npIdx = 0; npIdx < numParticleSet.size(); npIdx++) // for (unsigned int avgParam_index = 0; avgParam_index < avgParam_Iterations; avgParam_index++) // { // // use the problemID and the problemInstanceID to // // generate a unique ID for the concentration. This // // will at least allow us to link it back to the correct // // simulation. // long currProbID = 1; // probInstID++; // /*if (useDB) // { // currProbID = optDB_ptr->getCurrentProblemID(); // probInstID = optDB_ptr->insertNewProblemInstance(); // mkdir(("/scratch/data/" + boost::lexical_cast<std::string>(currProbID) + "/" + boost::lexical_cast<std::string>(probInstID)).c_str(), S_IRUSR | S_IWUSR | S_IXUSR); // }*/ // log.debug("Starting work on problem instance ", probInstID, " of Problem #", currProbID); // log.debug("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); // ///For now the database parameters are going to updated only once for a avgParam // ////This avoid more number of parainstances being created; // /////updating after the exaclty before quicPlume execution // /* // Inject the ts, np, and wind info too // std::ostringstream name(""); // double value; // if(use_avgParam) // { // name.str(""); // name <<avgParamName; // value = avgParam.at(avgParam_index); // if (useDB) // optDB_ptr->updateParameterInstance(currProbID, probInstID, name.str(), value); // } // for (unsigned int sampIdx=0; sampIdx<s.size(); sampIdx++) // { // namedOptParam *optData = lookupDataInMapFromSampleIndex(sampIdx); // std::cout << "sample[" << sampIdx << "] = " << s[sampIdx] << ", " << optData->description << std::endl; // name.str(""); // name << optData->description << " " << optData->idx; // value = (int)s[sampIdx]; // if (useDB) // optDB_ptr->updateParameterInstance(currProbID, probInstID, name.str(), value); // } // std::cout<<"Done "<<std::endl; */ // ///TODO uncomment 1111 comment 2222 // ////directory edit begin // ////1111 mkdir("/tmp/workingDir/", S_IRUSR | S_IWUSR | S_IXUSR); // /////1111 sprintf(dirName, "/tmp/workingDir/%s%ld_%ld_%d_%d_%d_%.2f_%.1f", "gpuPlume", currProbID, probInstID, (int)s[0], (int)s[1], numParticleSet[npIdx], timeStepSet[tsIdx], windAngle[w]); // //////1111 mkdir(dirName, S_IRUSR | S_IWUSR | S_IXUSR); // /////2222 // // sprintf(dirName, "/tmp/%s%ld_%ld_%d_%d_%d_%.2f_%.1f", "gpuPlume", currProbID, probInstID, (int)s[0], (int)s[1], numParticleSet[npIdx], timeStepSet[tsIdx], windAngle[w]); // // mkdir(dirName, S_IRUSR | S_IWUSR | S_IXUSR); // ///directory edit stop // ///////222222 // int pause_temp1; // // NOTE: it is here when we know the actual parameters that // // will be used for this particular problem. this // // information can be inserted into the paraminstances // // table of the database to link a problem instance to // // it's parameters. // // create the inner directory // // sprintf(dirName2, "%s/optimizationRun_inner", dirName); // // mkdir(dirName2, S_IRUSR | S_IWUSR | S_IXUSR); // // Concentration file name is based on problem id and problem instance id // //////11111 mkdir("/tmp/workingDir/concFiles/",S_IRUSR | S_IWUSR | S_IXUSR); /////directory // concString.str(""); // /////1111 concString << "/tmp/workingDir/concFiles/concOutput_" << currProbID << "_" << probInstID << ".m"; // // concString << "/tmp/concOutput_" << currProbID << "_" << probInstID << ".m"; ///TODO currWork change the concString so that it will print all the required concentration files // /*if (useDB) // { // //we want the concetration files in the /scratch/data/ // concString << "/scratch/data/" << currProbID << "/" << probInstID << "/concOutput_"; // } // else*/ // { // concString << output_location << "/concOutput_"; // } // sampleString.str(""); // /* for(unsigned int zz=0;zz<s.size();zz++) // { // ///fast changes ///quick fix // std::cerr<<"stopping here "<<std::endl; // namedOptParam* temp = lookupDataInMapFromSampleIndex(zz); // std::string variable_name; // variable_name=temp->description; // std::string s_index=variable_name.substr(variable_name.find("[")+1,variable_name.find("]")-variable_name.find("[")-1); // std::string param=variable_name.substr(variable_name.find("]")+2); // std::cerr<<"the index :"<<s_index<<"the name "<<param; // concString<<param<<s_index; // concString<<"_"<<s.at(zz); // //concString << s.at(zz); // //sampleString<<param<<"_"<<s_index<<"_"; // // sampleString<<s.at(zz); // // sampleString <<remove_me++; // }*/ // sampleString << remove_me++; // //std::cerr << "The nameof the final" << sampleString.str(); // concString << sampleString.str(); // if (use_avgParam) // { // concString << "_" << avgParamName << "_" << avgParam.at(avgParam_index); // } // //std::cout << "the sample" << s << std::endl; // //std::cout << concString.str() << std::endl; // int pause_pause; // //std::cin>>pause_pause; // concString << ".m"; // // std::cout<<"-----------------------------------------------------======================================--------------------------------------------------------------"<<std::endl; // // std::cout<<concString.str()<<std::endl; // // std::cin>>pause_temp1; // // std::cout << "Writing files to " << dirName2 << std::endl; // // // std::string quicFilesPath = baseproj_inner_path + "/"; // // std::string outputDir=workDir.outputDir; // // std::cout<<"quicFilesPath "<<quicFilesPath<<std::endl<<"lenght:"<<quicFilesPath.length()<<std::endl<<quicFilesPath[0]; // // copyFile(quicFilesPath + "../" + projFileName, outputDir + "/../optimizationRun.proj"); // // Not much need for the base gpuPlume input file... since // // defaults are now loaded in util.cpp if nothing else is given. // // std::cout<<"Trying to see if the quicProject works"<<std::endl; ///languageMap // // ///singleValuessivelab::QUICProject quqpData(quicFilesPath); ///reads in the whole set of files // // quqpData.build_map(); ///languageMap // //std::cout<<"Have to compare these two datastructres"<<std::endl; // ////////////////////////////////////////////////////////////////////////////////////////working till here perfectly // //////////////TODO // // quBuildings quBuildingData; // // quBuildingData.readQUICFile(quicFilesPath + "QU_buildings.inp"); // /* ////languageMap // //std::cout<<"comapring values---------------------------------=-=-=-=-=-"<<std::endl ; // //std::cout<<"Project outof project"<<std::endl; // /*std::cout<<quqpData.quBuildingData.x_subdomain_sw<<":"<<quBuildingData.x_subdomain_sw<<std::endl; // std::cout<<quqpData.quBuildingData.y_subdomain_sw<<":"<<quBuildingData.y_subdomain_sw<<std::endl; // std::cout<<quqpData.quBuildingData.x_subdomain_ne<<":"<<quBuildingData.x_subdomain_ne <<std::endl; // std::cout<<quqpData.quBuildingData.y_subdomain_ne<<":"<<quBuildingData.y_subdomain_ne <<std::endl; // std::cout<<quqpData.quBuildingData.zo<<":"<<quBuildingData.zo<<std::endl; // std::cout<<quqpData.quBuildingData.buildings.size()<<":"<<quBuildingData.buildings.size()<<std::endl; // */ // /*std::cout<<"before modifying "<<std::endl; // //std::cout<<"quqpData.quBuildingData.x_subdomain_sw = "<<quqpData.quBuildingData.x_subdomain_sw<<std::endl; // std::cout<<"quqpData.quBuildingData.y_subdomain_sw = "<<quqpData.quBuildingData.y_subdomain_sw<<std::endl; // std::cout<<"quqpData.quBuildingData.x_subdomain_ne = "<<quqpData.quBuildingData.x_subdomain_ne<<std::endl; // std::cout<<"quqpData.quBuildingData.y_subdomain_ne = "<<quqpData.quBuildingData.y_subdomain_ne<<std::endl; // std::cout<<"quqpData.quBuildingData.zo = "<<quqpData.quBuildingData.zo<<std::endl; // std::cout<<"quqpData.quBuildingData.buildings[3].xfo = "<<quqpData.quBuildingData.buildings[3].xfo<<std::endl; // std::cout<<"quqpData.quBuildingData.buildings[3].yfo = "<<quqpData.quBuildingData.buildings[3].yfo<<std::endl; // */ // std::vector<std::string> dataStructureNames; //contains dataStructureNames that are being modified in the sample // ////modifying data in the datastructures .... // augmentDataFromSample(s, quqpData, dataStructureNames); // // augmentBuildingDataFromSample( s, quqpData.quBuildingData); // //quBuildings quBuildingData; // /* // std::cout<<"after modifying "<<std::endl; // std::cout<<"quqpData.quBuildingData.x_subdomain_sw = "<<quqpData.quBuildingData.x_subdomain_sw<<std::endl; // std::cout<<"quqpData.quBuildingData.y_subdomain_sw = "<<quqpData.quBuildingData.y_subdomain_sw<<std::endl; // std::cout<<"quqpData.quBuildingData.x_subdomain_ne = "<<quqpData.quBuildingData.x_subdomain_ne<<std::endl; // std::cout<<"quqpData.quBuildingData.y_subdomain_ne = "<<quqpData.quBuildingData.y_subdomain_ne<<std::endl; // std::cout<<"quqpData.quBuildingData.zo = "<<quqpData.quBuildingData.zo<<std::endl; // std::cout<<"quqpData.quBuildingData.buildings[3].xfo = "<<quqpData.quBuildingData.buildings[3].xfo<<std::endl; // std::cout<<"quqpData.quBuildingData.buildings[3].yfo = "<<quqpData.quBuildingData.buildings[3].yfo<<std::endl; // */ // log.debug( "before modifying dependency"); // log.debug( "---------------------_"); // log.debug( "quqpData.quBuildingData.x_subdomain_sw = " , quqpData.quBuildingData.x_subdomain_sw ); // log.debug( "quqpData.quBuildingData.y_subdomain_sw = " , quqpData.quBuildingData.y_subdomain_sw ); // log.debug( "quqpData.quBuildingData.x_subdomain_ne = " , quqpData.quBuildingData.x_subdomain_ne ); // log.debug( "quqpData.quBuildingData.y_subdomain_ne = " , quqpData.quBuildingData.y_subdomain_ne ); // log.debug( "quqpData.quBuildingData.zo = " , quqpData.quBuildingData.zo); // augmentDataBasedOnDependency(quqpData, dataStructureNames); // log.debug( "after modifying "); // log.debug( "quqpData.quBuildingData.x_subdomain_sw = ", quqpData.quBuildingData.x_subdomain_sw); // log.debug( "quqpData.quBuildingData.y_subdomain_sw = ", quqpData.quBuildingData.y_subdomain_sw); // log.debug( "quqpData.quBuildingData.x_subdomain_ne = ", quqpData.quBuildingData.x_subdomain_ne); // log.debug( "quqpData.quBuildingData.y_subdomain_ne = ", quqpData.quBuildingData.y_subdomain_ne); // log.debug( "quqpData.quBuildingData.zo = ", quqpData.quBuildingData.zo); // //std::cout<<"checking validity"<<std::endl; // //exit(1); // // Write this file to the appropriate place. // // quqpData.quBuildingData.writeQUICFile(outputDir + "/QU_buildings.inp"); // // // // QU_fileoptions.inp... // // // // copyFile(quicFilesPath + "QU_fileoptions.inp", outputDir + "/QU_fileoptions.inp"); // // // // Landuse file // // copyFile(quicFilesPath + "QU_landuse.inp", outputDir + "/QU_landuse.inp"); // // QU_metparams.inp" // // quMetParams quMetParamData; // // // Write this file to the appropriate place. // // quqpData.quMetParamData.writeQUICFile(outputDir + "/QU_metparams.inp"); // quMetParamData.readQUICFile(quicFilesPath + "QU_metparams.inp"); // // QU_simparams.inp // // quSimParams quSimParamData; // // quqpData.quSimParamData.writeQUICFile(outputDir + "/QU_simparams.inp"); // quSimParamData.readQUICFile(quicFilesPath + "QU_simparams.inp"); // // deal with changing wind... // // quSensorParams sensorData; // //quqpData.quMetParamData.quSensorData.direction = windAngle[w]; // ///TODO:removing the wind values for now but fix it // ////currWorkImp make sure we include that in avgParam augment // // quqpData.quMetParamData.quSensorData.direction.setDegrees(windAngle[w],sivelab::MET); // sensorData.readQUICFile(quicFilesPath + "sensor1.inp"); // // quqpData.quMetParamData.quSensorData.writeQUICFile(outputDir + "/sensor1.inp"); // // copyFile(quicFilesPath + projFileName.substr(0, projFileName.length() - 5) + ".info", outputDir + "/optimizationRun.info"); // // copyFile(quicFilesPath + "QP_materials.inp", outputDir + "/QP_materials.inp"); // // copyFile(quicFilesPath + "QP_indoor.inp", outputDir + "/QP_indoor.inp"); // // dataStructureNames.push_back("quSensor"); // // // // augment the emitters, if applicable // // // // qpSource qpSourceData; // // qpSourceData.readQUICFile(quicFilesPath + "QP_source.inp"); // // ... in the 5D test case, this means modifying the overall // int bld1Idx = quqpData.quBuildingData.findIdxByBldNum(1); // assert(bld1Idx != -1); // int bld2Idx = quqpData.quBuildingData.findIdxByBldNum(2); // assert(bld2Idx != -1); // /* // quqpData.qpSourceData.sources[0].points[0].x = quqpData.quBuildingData.buildings[ bld1Idx ].xfo + quqpData.quBuildingData.buildings[ bld1Idx ].length; // quqpData.qpSourceData.sources[0].points[0].z = 0.5; // quqpData.qpSourceData.sources[0].points[1].x = quqpData.quBuildingData.buildings[ bld2Idx ].xfo; // quqpData.qpSourceData.sources[0].points[1].z = 0.5;*/ // // quqpData.qpSourceData.writeQUICFile(outputDir + "/QP_source.inp"); // // copyFile(quicFilesPath + "QP_fileoptions.inp", outputDir + "/QP_fileoptions.inp"); // dataStructureNames.push_back("qpSource"); // // qpParams qpParamData; // // qpParamData.readQUICFile(quicFilesPath + "QP_params.inp"); // // We need to modify the QP Param data to only use 1 particle // // and run for a minimum amount of time while generating the // // turbulence field... // int origNumParticles = quqpData.qpParamData.numParticles; // int origDuration = quqpData.qpParamData.duration; // // quqpData.qpParamData.numParticles = 1; // // quqpData.qpParamData.duration = 0.1; // // quqpData.qpParamData.writeQUICFile(outputDir + "/QP_params.inp"); // dataStructureNames.push_back("qpParams"); // // copyFile(quicFilesPath + "QP_particlesize.inp", outputDir + "/QP_particlesize.inp"); // /* // workDir.validateOutputDir(dataStructureNames, quqpData); // */ // //// outputDir = workDir.outputDir; //// get rid of this now TODO TODO // // std::cout<<"the size of the dataStructeNames should be zero "<<dataStructureNames.size()<<std::endl; // // std::cin>>pause_temp1; // log.debug( "done with changing the buildings params . Only that should change nothing else and before gpuPlume "); // /*if (testing_day) // std::cin >> pause_temp1;*/ // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////point of execution // #ifdef __APPLE__ // std::string quEXE = QUICURB_EXE_PATH + "/quicurb_MACI.exe"; // std::string qpEXE = QUICPLUME_EXE_PATH + "/quicplume_MACI.exe"; // #else // // In 5.72, the executable names have changed... was // // std::string quEXE = QUICURB_EXE_PATH + "/quicurb_LINUX_64.exe"; // // std::string qpEXE = QUICPLUME_EXE_PATH + "/quicplume_LINUX_64.exe"; // // is now // std::string quEXE = QUICURB_EXE_PATH + "/quicurb_LIN64.exe"; // std::string qpEXE = QUICPLUME_EXE_PATH + "/quicplume_LIN64.exe"; // // Old LInux path - "/home/cs/vr/software/QUICv5p51_07-30-2009pcode/executables/ // #endif // // std::cout<<"pausing before quicUrb "<<std::endl; // char cmdBuffer[1024]; // sprintf(cmdBuffer, "cd %s; %s", outputDir.c_str(), quEXE.c_str()); // log.debug("Executing QUICURB to generate new wind field data..."); // log.debug(cmdBuffer); // system(cmdBuffer); // // std::cout<<"pausing "<<std::endl; // //std::cin>>pause_temp1; // // sprintf(cmdBuffer, "cd %s; %s", outputDir.c_str(), qpEXE.c_str()); // // std::cout << "Executing QUICPLUME for 1 iteration to generate turbulence field data..." << std::endl; // // std::cout<<cmdBuffer<<std::endl; // // std::cin>>pause_temp1; // // system(cmdBuffer); // // Now that quicplume has been run to generate the turbulence, // // reset the QPParam data back to the original data and re-write // // it since gpuPlume now uses the QPParam data to run the // // simulation. // //std::cout << "pausing after the quicURB next to execute quicPlume" << std::endl; // //std::cin>>pause_temp1; // if (useNumParticleSet && (numParticleSet.size() > 0)) // quqpData.qpParamData.numParticles = numParticleSet[npIdx]; // else // quqpData.qpParamData.numParticles = origNumParticles; // if (useTimeStepSet && (timeStepSet.size() > 0)) // quqpData.qpParamData.timeStep = timeStepSet[tsIdx]; // // /////////////////////////////////////////////////////////////// // // Update the optimization DB with the correct particle // // number and timestep values // if (avgParam_index == 0) ////Only when the intial run for avgParam_index is run // { // int pause_temp2; // std::cout << "pausing before updateParameter calls" << std::endl; // // std::cin>>pause_temp2; // std::ostringstream name(""); // double value; // ///call update paramIndex // ///update numParticleSet // ////update TimeStepSet; // name.str(""); // name << "Time Step"; // value = quqpData.qpParamData.timeStep; // /*if (useDB) // optDB_ptr->updateParameterInstance(currProbID, probInstID, name.str(), value); // */ // name.str(""); // name << "Number of Particles"; // value = quqpData.qpParamData.numParticles; // /*if (useDB) // { // optDB_ptr->updateParameterInstance(currProbID, probInstID, name.str(), value); // updateParamInstances(currProbID, probInstID, s); // }*/ // std::cout << "pausing after updateParameter calls" << std::endl; // //std::cin>>pause_temp2; // } // // /////////////////////////////////////////////////////////////// // // at this point, the cell type structure should have // // been output, and thus, we could add it to the // // mysql dataset... // // don't do this if we don't need it... // // optDB_ptr->insertCellTypeData(probInstID, currProbID, outputDir + "/QU_celltype.dat"); // std::cerr << "Done with updates completely" << std::endl; // quqpData.qpParamData.duration = origDuration; // // // // need to modify the concentration box based on the emitter bounds // // // /* quqpData.qpParamData.nbx = quqpData.quBuildingData.buildings[ bld2Idx ].xfo - quqpData.quBuildingData.buildings[ bld1Idx ].xfo + quqpData.quBuildingData.buildings[ bld1Idx ].length; // quqpData.qpParamData.nby = 50; // quqpData.qpParamData.nbz = quqpData.quBuildingData.buildings[ bld2Idx ].height; // std::cout << "set conc N to " << quqpData.qpParamData.nbx << " x " << quqpData.qpParamData.nby << " x " << quqpData.qpParamData.nbz << std::endl; // quqpData.qpParamData.xbl = quqpData.quBuildingData.buildings[ bld2Idx ].xfo - quqpData.qpParamData.nbx; // quqpData.qpParamData.xbu = quqpData.quBuildingData.buildings[ bld2Idx ].xfo; // quqpData.qpParamData.ybl = quqpData.quBuildingData.buildings[ bld2Idx ].yfo - quqpData.quBuildingData.buildings[ bld2Idx ].width/2; // quqpData.qpParamData.ybu = quqpData.quBuildingData.buildings[ bld2Idx ].yfo + quqpData.quBuildingData.buildings[ bld2Idx ].width/2; // quqpData.qpParamData.zbl = 0; // quqpData.qpParamData.zbu = quqpData.quBuildingData.buildings[ bld2Idx ].height; // std::cout << "set conc dim to [" << quqpData.qpParamData.xbl << ", " << quqpData.qpParamData.ybl << ", " << quqpData.qpParamData.zbl << "] X ]" // << quqpData.qpParamData.xbu << ", " << quqpData.qpParamData.ybu << ", " << quqpData.qpParamData.zbu << "]" << std::endl; // quqpData.qpSourceData.sources[0].points[0].x = quqpData.quBuildingData.buildings[ bld1Idx ].xfo + quqpData.quBuildingData.buildings[ bld1Idx ].length + 0.5; // quqpData.qpSourceData.sources[0].points[1].x = quqpData.quBuildingData.buildings[ bld2Idx ].xfo - 0.5; // */ // dataStructureNames.push_back("qpParams"); // std::cout << "the size of " << dataStructureNames.size(); // ///This is where we want to augment the data based on et dependency // if (use_avgParam) // { // augmentDataforAvgParam(quqpData, dataStructureNames, avgParam_index); // // read the /tmp/"concFile"... reduce // } // // quqpData.qpParamData.writeQUICFile(outputDir + "/QP_params.inp"); // /* // workDir.validateOutputDir(dataStructureNames, quqpData); // */ // std::cout << "paused for before gpuPlume" << std::endl; // /*if (testing_day) // std::cin >> pause_temp1; // */ // std::ostringstream gpuPlumeCmd(""); // std::cout << "output" << outputDir.c_str() << std::endl; // gpuPlumeCmd << "./gpuPlume --quicproj=" << outputDir.c_str() << "/../optimizationRun.proj" << " --concFile=" << concString.str() << " --concId=" << sampleString.str() << " --ignoreSignal --offscreenRender " << std::endl; // // gpuPlumeCmd << "./gpuPlume " << outputDir.c_str() << "/../optimizationRun.proj" << " --concFile=" << concString.str() << " --concId=optRun_" << currProbID << "_" << probInstID << " --ignoreSignal --offscreenRender" << std::endl; // std::cout << "Executing gpuPlume: " << gpuPlumeCmd.str() << std::endl; // //system(gpuPlumeCmd.str().c_str()); // // processConcentration() // // read the /tmp/"concFile"... reduce the concentration to the // //std::cerr<<"the height is-=================-=-=--=-=-=-=-=-=-=-=-=-=-=-=-3=-3=-3=-3=-3=-3-=3========== "<<quqpData.quBuildingData.buildings[bld2Idx].height<<std::endl; // std::cerr << "before concentration" << std::endl; // /*if (testing_day) // std::cin >> pause_temp1;*/ // /*concentrationRedux cr(concString.str(), quqpData.quBuildingData, quqpData.qpSourceData, 0.5); // std::cout << "EXCEEDANCES: " << cr.exceedances() << ", MEAN: " << cr.mean() << ", STDDEV: " << cr.stddev() << ", MAX: " << cr.max() << ", MIN: " << cr.sum() << std::endl; // totalExceedances += cr.exceedances(); // totalMean += cr.mean(); // // retFitness = 1.0 / (totalExceedances + 1); // // Bugs' recommended fitness function uses the cr.max value at slice 1.5 // // turn it into a fitness by 1/c // // retFitness = 1.0 / cr.max(); // std::cout << "fitness value" << std::endl; // std::cerr << "fitness _function " << std::endl; // std::cerr << fitness_function << std::endl; // // std::cin>>pause_temp1; // if (fitness_function.compare("norm1") == 0) // { // retFitness += cr.norm1(); // } // else if (fitness_function.compare("norm2") == 0) // { // std::cerr << "The fitness is --------------------------------------------------" << cr.norm2() << std::endl; // retFitness += cr.norm2(); // } // else if (fitness_function.compare("norm3") == 0) // retFitness += cr.norm3(); // else if (fitness_function.compare("norm4") == 0) // retFitness += cr.norm4(); // else // retFitness += cr.mean(); // // retFitness = cr.max(); // */ // // csvExport->update( s, windAngle[w], timeStepSet[tsIdx], numParticleSet[npIdx], cr, 1.0/(cr.exceedances() + 1.0), concString.str() ); // #if 0 // // TRAINING DATA // // export out the wind field information to the training data // // // //// trainingModuleExport->appendData(windAngle[w]); ---wind angle is no more // trainingModuleExport->appendData(retFitness); // trainingModuleExport->appendData(cr.max()); // trainingModuleExport->appendData(cr.mean()); // trainingModuleExport->appendCellTypeData(outputDir + "/QU_celltype.dat"); // trainingModuleExport->endData(); // #endif // //int pause_crap; // //std::cout<<"This is to show avgParam_index "<<avgParam_index<<" -- avgParam_Iterations "<<avgParam_Iterations<<std::endl; // // std::cin>>pause_crap; // // update the optimization database // if (avgParam_index == (avgParam_Iterations - 1)) // { // retFitness = retFitness / (double)avgParam_Iterations; // /*if (useDB) // { // //ProblemInstance is being updated . we can update the percentage of compleetion // ////TODO decide as to how often we would like to update . If it not everytime define new varaible to retain percentage. // float percent = (float)gl_completed_problems / (float)gl_total_problems; // //matlab program execution // std::string file_to_run = concString.str(); // int temp_hola; // std::cerr << "pausing before running the file" << std::endl; // std::cin >> temp_hola; // #ifdef USING_MATLAB // matlabeng.matlab_runfile(file_to_run.substr(0, file_to_run.find("."))); // #endif // std::cerr << "After doing the matlab file" << std::endl; // std::cin >> temp_hola; // optDB_ptr->updateProblemInstance(probInstID, retFitness, cr, percent); // } // */ // } // //cr.clearData(); // // ///////////////////////////// // // cleanup files // // ///////////////////////////// // // For now, keep the concentration files, and remove the gpuplume data directories // // cleanupDirectory( dirName ); // // remove the concentration files too since they can be downloaded from the web app! // // cleanupFile(concString.str()); // } // totalMean = totalMean / (double) avgParam_Iterations; // std::cout << "\n\n***********\nEXCEEDANCES: " << totalExceedances << "\n"; // std::cout << "----->>>>>> Fitness: " << retFitness << std::endl; // std::cout << "**************\n\n" << std::endl; // // retFitness = 1.0 / (totalExceedances + 1); // cache.addToCache( s, retFitness ); // int pause_temp; // // std::cerr<<"time"<<std::endl; // // std::cerr<<t.elapsed()<<std::endl; // //std::cin>>pause_temp; // std::cout << "pause" << std::endl; // /*if (testing_day) // std::cin >> pause_temp; // */ // std::cout << "Done with the evaluation returning value" << std::endl; // s.fitness = retFitness; // return true; // } // else // { // //No idea what this is // // csvExport->update( s, retFitness ); // s.fitness = retFitness; // return true; // } // } // else // return false; // } bool gpu_plume_job::readNumParticleSet(const char *line, std::vector<int> &npSet) ////languageMap { // std::cout<<"inside readparticles func:"<<line<<std::endl; std::string settingName = "NumParticleSet"; std::istringstream ist(line); std::string w; ist >> w; std::string equals;///////added ///languageMap ist >> equals; ///////added ///languageMap if (w == settingName) { // read off the first char '[' char c; ist >> c; int numPart; while (c != ']') { cout << "inside while" << endl; ist >> numPart; npSet.push_back(numPart); c = ist.peek(); } return true; } return false; } bool gpu_plume_job::readTimeStepSet(const char *line, std::vector<float> &tsSet) ////languageMap { std::string settingName = "TimeStepSet"; std::istringstream ist(line); std::string w; ist >> w; std::string equals;///////added ///languageMap ist >> equals; ///////added ///languageMap if (w == settingName) { // read off the first char '[' char c; ist >> c; float tstep; while (c != ']') { ist >> tstep; tsSet.push_back(tstep); c = ist.peek(); } return true; } return false; } bool gpu_plume_job::removeCommentLines( char *buf ) { char *comment_ptr = strstr(buf, "//"); if (comment_ptr == 0) return 1; // comment noread1Stringt located, so do not alter the buffer else { // comment delimiter located, remove comments *comment_ptr = '\0'; // check the strlen, if less than 1, return false if (strlen(buf) == 0) return false; else { for (unsigned int i = 0; i < strlen(buf); i++) { if (buf[i] != ' ') return true; } // if we make it here, all the characters in the buffer were // spaces, so return false... return false; } } } bool gpu_plume_job::isNumeric(std::string value) { bool is_a_number = false; try { boost::lexical_cast<double>(value); is_a_number = true; } catch (boost::bad_lexical_cast &) { // if it throws, it's not a number. } return is_a_number; } void gpu_plume_job::readPreferencesFile() { std::ifstream prefFile; prefFile.open("Preferences.txt"); ///std::this was change TODO : make sure this is set righth .//// prefFile.open("Preferences.txt"); std::cout << "trying to open preferences" << std::endl; // currenlty only a couple of lines in here... llok for QUICURB_EXE_PATH and QUICPLUME_EXE_PATH char line[1024]; getcwd(line, 1024); std::cout << line << endl; line[0] = 0; std::string s1; while ( !prefFile.eof() ) { std::cout << "file opened" << std::endl; prefFile.getline(line, 1024); if ( line[ strlen(line)] == '\n' ) { line[ strlen(line)] = '\0'; } std::string s1; cout << strlen(line) << std::endl; if (read1String(line, "QUICURB_EXE_PATH", &s1)) { std::cout << "Found URB PATH: " << s1 << std::endl; QUICURB_EXE_PATH = s1; } if (read1String(line, "QUICPLUME_EXE_PATH", &s1)) { std::cout << "Found PLUME PATH: " << s1 << std::endl; QUICPLUME_EXE_PATH = s1; } } } bool gpu_plume_job::read1String(const char *line, const char *settingName, std::string *s) { std::istringstream ist(line); std::string w; ist >> w; if (w == settingName) { ist >> *s; return true; } return false; } <file_sep>/fitness_lib/compile_dll.sh g++ -c -fPIC -std=c++11 fitness_function.cpp -o fitness.o g++ -shared -o fitness.o libfitness.so <file_sep>/src/utils/directory.cpp #include "utils/directory.h" //extern namedOptParam *lookupDataInRangeMap(unsigned int idx); ///adi: aimed at copying files and loading quqpdata which doesnt change at all :D void directory::intialRun(std::string out, std::string quicPath, sivelab::QUICProject &quqpData, std:: string projFileName1) //loads the quqpdata and creates a working directory for the first time. { //cout , "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$4" , out ); char dirName2[128]; outputDir = out; //this directories path mkdir(outputDir.c_str(), S_IRUSR | S_IWUSR | S_IXUSR); //create the main directory // create the inner directory sprintf(dirName2, "%s/optimizationRun_inner", outputDir.c_str()); mkdir(dirName2, S_IRUSR | S_IWUSR | S_IXUSR); outputDir = dirName2; quqpData.m_quicProjectPath = quicPath; projFileName = projFileName1; ////////////things i want in intialrun : /directory() ///----------------------------------------------------------------------------------------------------------------------------------------------------------- //////optimizationRun.proj log.debug( "should copy optimizationRun.proj copied=" , dir[0]->fileName ); copyFile(quqpData.m_quicProjectPath + "../" + projFileName, outputDir + "/../" + dir[0]->fileName); dir[0]->isValid = true; log.debug( "should copy QU_buildings.inp copied=" , dir[1]->fileName ); dir[1]->isValid = false; quqpData.quBuildingData.writeQUICFile(outputDir + "/" + dir[1]->fileName); log.debug( "should copy QU_fileoptions.inp copied=" , dir[2]->fileName ); copyFile(quqpData.m_quicProjectPath + dir[2]->fileName, outputDir + "/" + dir[2]->fileName); dir[2]->isValid = true; // Landuse file log.debug( "should copy QU_landuse.inp copied=" , dir[3]->fileName ); copyFile(quqpData.m_quicProjectPath + dir[3]->fileName, outputDir + "/" + dir[3]->fileName); dir[3]->isValid = true; log.debug( "should copy QU_metparams.inp copied=" , dir[4]->fileName ); quqpData.quMetParamData.writeQUICFile(outputDir + "/" + dir[4]->fileName); dir[4]->isValid = false; log.debug( "should copy QU_simparams.inp copied=" , dir[5]->fileName ); quqpData.quSimParamData.writeQUICFile(outputDir + "/" + dir[5]->fileName); dir[5]->isValid = false; log.debug( "should copy sensor1.inp copied=" , dir[6]->fileName ); quqpData.quMetParamData.quSensorData.writeQUICFile(outputDir + "/" + dir[6]->fileName); dir[6]->isValid = false; log.debug( "should copy optimizationRun.info copied=" , dir[7]->fileName ); copyFile(quqpData.m_quicProjectPath + projFileName.substr(0, projFileName.length() - 5) + ".info", outputDir + "/" + dir[7]->fileName); dir[7]->isValid = true; log.debug( "should copy QP_materials.inp copied=" , dir[8]->fileName ); copyFile(quqpData.m_quicProjectPath + dir[8]->fileName, outputDir + "/" + dir[8]->fileName); dir[8]->isValid = true; log.debug( "should copy QP_indoor.inp copied=" , dir[9]->fileName ); copyFile(quqpData.m_quicProjectPath + dir[9]->fileName, outputDir + "/" + dir[9]->fileName); dir[9]->isValid = true; log.debug( "should copy QP_source.inp copied=" , dir[10]->fileName ); // quqpData.qpSourceData.readQUICFile(quqpData.m_quicProjectPath + dir[10]->fileName); dir[10]->isValid = false; quqpData.qpSourceData.writeQUICFile(outputDir + "/" + dir[10]->fileName); log.debug( "should copy QP_fileoptions.inp copied=" , dir[11]->fileName ); copyFile(quqpData.m_quicProjectPath + dir[11]->fileName, outputDir + "/" + dir[11]->fileName); dir[11]->isValid = true; log.debug( "should copy QP_params.inp copied=" , dir[12]->fileName ); //quqpData.qpParamData.readQUICFile(quqpData.m_quicProjectPath + dir[12].fileName); // We need to modify the QP Param data to only use 1 particle // and run for a minimum amount of time while generating the // turbulence field... /* int origNumParticles = quqpData.qpParamData.numParticles; int origDuration = quqpData.qpParamData.duration; quqpData.qpParamData.numParticles = 1; quqpData.qpParamData.duration = 0.1; */ ///TODO Is this required quqpData.qpParamData.writeQUICFile(outputDir + "/" + dir[12]->fileName); dir[12]->isValid = false; log.debug( "should copy QP_particlesize.inp copied=" , dir[13]->fileName ); copyFile(quqpData.m_quicProjectPath + dir[13]->fileName, outputDir + "/" + dir[13]->fileName); dir[13]->isValid = true; log.debug( "should copy QP_buildout.inp" , dir[14]->fileName ); quqpData. qpBuildoutData.writeQUICFile(outputDir + "/" + dir[14]->fileName); dir[14]->isValid = false; } /*void directory::createOutputDirectory(float windAngle,std::vector<std::string> &dataStructureNames,sivelab::QUICProject & quqpData,string QUICURB_EXE_PATH,string QUICPLUME_EXE_PATH,bool useNumParticleSet,bool useTimeStepSet,int numParticle,float timeStep){//string outDirPath,sivelab::QUICProject & quqpData){ ///currWork quqpData.quMetParamData.quSensorData.direction = windAngle; dataStructureNames.push_back("quSensor"); // ... in the 5D test case, this means modifying the overall int bld1Idx = quqpData.quBuildingData.findIdxByBldNum(1); assert(bld1Idx != -1); int bld2Idx = quqpData.quBuildingData.findIdxByBldNum(2); assert(bld2Idx != -1); // qpParams qpParamData; // qpParamData.readQUICFile(quicFilesPath + "QP_params.inp"); // We need to modify the QP Param data to only use 1 particle // and run for a minimum amount of time while generating the // turbulence field... int origNumParticles = quqpData.qpParamData.numParticles; int origDuration = quqpData.qpParamData.duration; // quqpData.qpParamData.numParticles = 1; // quqpData.qpParamData.duration = 0.1; dataStructureNames.push_back("qpParams"); for(int crap=0;crap<dataStructureNames.size();crap++) log.debug("the dataStructurenames :",dataStructureNames.at(crap),std::endl; validateOutputDir(dataStructureNames,quqpData); #ifdef __APPLE__ std::string quEXE = QUICURB_EXE_PATH + "/quicurb_MACI.exe"; std::string qpEXE = QUICPLUME_EXE_PATH + "/quicplume_MACI.exe"; #else // In 5.72, the executable names have changed... was // std::string quEXE = QUICURB_EXE_PATH + "/quicurb_LINUX_64.exe"; // std::string qpEXE = QUICPLUME_EXE_PATH + "/quicplume_LINUX_64.exe"; // is now std::string quEXE = QUICURB_EXE_PATH + "/quicurb_LIN64.exe"; std::string qpEXE = QUICPLUME_EXE_PATH + "/quicplume_LIN64.exe"; // Old LInux path - "/home/cs/vr/software/QUICv5p51_07-30-2009pcode/executables/ #endif // sprintf(dirName2, "%s/optimizationRun_inner", outputDir.c_str()); //outDirPath = outDirPath+"/optimizationRun_inner"; cout,"this shoyuld have worked " ,outputDir," #########################################################",endl; char cmdBuffer[1024]; sprintf(cmdBuffer, "cd %s; %s", outputDir.c_str(), quEXE.c_str()); log.debug( "Executing QUICURB to generate new wind field data..." ); system(cmdBuffer); // sprintf(cmdBuffer, "cd %s; %s", outputDir.c_str(), qpEXE.c_str()); // log.debug( "Executing QUICPLUME for 1 iteration to generate turbulence field data..." ); // system(cmdBuffer); // Now that quicplume has been run to generate the turbulence, // reset the QPParam data back to the original data and re-write // it since gpuPlume now uses the QPParam data to run the // simulation. /////////////////////////////////////////////////////////////////////////// getting the previous data /////////////////////////////////////////////////////////////////////////////////////TODO the origNumParticles and duration replacment if (useNumParticleSet) quqpData.qpParamData.numParticles = numParticle; else quqpData.qpParamData.numParticles = origNumParticles; if (useTimeStepSet) quqpData.qpParamData.timeStep = timeStep; // at this point, the cell type structure should have // been output, and thus, we could add it to the // mysql dataset... // don't do this if we don't need it... // optDB_ptr->insertCellTypeData(probInstID, currProbID, outputDir + "/QU_celltype.dat"); quqpData.qpParamData.duration = origDuration; // // need to modify the concentration box based on the emitter bounds // /////////////////////////////////////////////////////////////////////////////////////TODO:validate this quBuildingData etc bld1Idx = quqpData.quBuildingData.findIdxByBldNum(1); assert(bld1Idx != -1); bld2Idx = quqpData.quBuildingData.findIdxByBldNum(2); assert(bld2Idx != -1); quqpData.qpParamData.nbx = quqpData.quBuildingData.buildings[ bld2Idx ].xfo - quqpData.quBuildingData.buildings[ bld1Idx ].xfo + quqpData.quBuildingData.buildings[ bld1Idx ].length; quqpData.qpParamData.nby = 50; quqpData.qpParamData.nbz = quqpData.quBuildingData.buildings[ bld2Idx ].height; log.debug( "set conc N to " , quqpData.qpParamData.nbx , " x " , quqpData.qpParamData.nby , " x " , quqpData.qpParamData.nbz ); quqpData.qpParamData.xbl = quqpData.quBuildingData.buildings[ bld2Idx ].xfo - quqpData.qpParamData.nbx; quqpData.qpParamData.xbu = quqpData.quBuildingData.buildings[ bld2Idx ].xfo; quqpData.qpParamData.ybl = quqpData.quBuildingData.buildings[ bld2Idx ].yfo - quqpData.quBuildingData.buildings[ bld2Idx ].width/2; quqpData.qpParamData.ybu = quqpData.quBuildingData.buildings[ bld2Idx ].yfo + quqpData.quBuildingData.buildings[ bld2Idx ].width/2; quqpData.qpParamData.zbl = 0; quqpData.qpParamData.zbu = quqpData.quBuildingData.buildings[ bld2Idx ].height; log.debug( "set conc dim to [" , quqpData.qpParamData.xbl , ", " , quqpData.qpParamData.ybl , ", " , quqpData.qpParamData.zbl , "] X ]" , quqpData.qpParamData.xbu , ", " , quqpData.qpParamData.ybu , ", " , quqpData.qpParamData.zbu , "]" ); quqpData.qpSourceData.sources[0].points[0].x = quqpData.quBuildingData.buildings[ bld1Idx ].xfo + quqpData.quBuildingData.buildings[ bld1Idx ].length + 0.5; quqpData.qpSourceData.sources[0].points[1].x = quqpData.quBuildingData.buildings[ bld2Idx ].xfo - 0.5; quqpData.qpParamData.writeQUICFile(outputDir + "/QP_params.inp"); } void directory::createOutputDir(const sample& s,string outDirPath,sivelab::QUICProject& quqpData,string projFileName1,string QUICURB_EXE_PATH,string QUICPLUME_EXE_PATH,bool useNumParticleSet,bool useTimeStepSet,int numParticle,float timeStep) { ////TODO: has a few random values like wind number of particles timestep etc ///TODO: refine this . This is a hack to make it work directory temp; sivelab::QUICProject temp_data; temp.intialRun(outDirPath,quqpData.m_quicProjectPath,temp_data,projFileName1); temp.validateDir(s,temp_data,100.0); #ifdef __APPLE__ std::string quEXE = QUICURB_EXE_PATH + "/quicurb_MACI.exe"; std::string qpEXE = QUICPLUME_EXE_PATH + "/quicplume_MACI.exe"; #else // In 5.72, the executable names have changed... was // std::string quEXE = QUICURB_EXE_PATH + "/quicurb_LINUX_64.exe"; // std::string qpEXE = QUICPLUME_EXE_PATH + "/quicplume_LINUX_64.exe"; // is now std::string quEXE = QUICURB_EXE_PATH + "/quicurb_LIN64.exe"; std::string qpEXE = QUICPLUME_EXE_PATH + "/quicplume_LIN64.exe"; // Old LInux path - "/home/cs/vr/software/QUICv5p51_07-30-2009pcode/executables/ #endif // sprintf(dirName2, "%s/optimizationRun_inner", outputDir.c_str()); outDirPath = outDirPath+"/optimizationRun_inner"; cout,"this shoyuld have worked " ,outDirPath," #########################################################",endl; char cmdBuffer[1024]; sprintf(cmdBuffer, "cd %s; %s", outDirPath.c_str(), quEXE.c_str()); log.debug( "Executing QUICURB to generate new wind field data..." ); system(cmdBuffer); sprintf(cmdBuffer, "cd %s; %s", outDirPath.c_str(), qpEXE.c_str()); log.debug( "Executing QUICPLUME for 1 iteration to generate turbulence field data..." ); system(cmdBuffer); // Now that quicplume has been run to generate the turbulence, // reset the QPParam data back to the original data and re-write // it since gpuPlume now uses the QPParam data to run the // simulation. /////////////////////////////////////////////////////////////////////////// getting the previous data qpParams qpParamData; qpParamData.readQUICFile(quqpData.m_quicProjectPath + "QP_params.inp"); int origNumParticles = qpParamData.numParticles; int origDuration = qpParamData.duration; /////////////////////////////////////////////////////////////////////////////////////TODO the origNumParticles and duration replacment if (useNumParticleSet) quqpData.qpParamData.numParticles = numParticle; else quqpData.qpParamData.numParticles = origNumParticles; if (useTimeStepSet) quqpData.qpParamData.timeStep = timeStep; // at this point, the cell type structure should have // been output, and thus, we could add it to the // mysql dataset... // don't do this if we don't need it... // optDB_ptr->insertCellTypeData(probInstID, currProbID, outputDir + "/QU_celltype.dat"); quqpData.qpParamData.duration = origDuration; // // need to modify the concentration box based on the emitter bounds // /////////////////////////////////////////////////////////////////////////////////////TODO:validate this quBuildingData etc int bld1Idx = quqpData.quBuildingData.findIdxByBldNum(1); assert(bld1Idx != -1); int bld2Idx = quqpData.quBuildingData.findIdxByBldNum(2); assert(bld2Idx != -1); quqpData.qpParamData.nbx = quqpData.quBuildingData.buildings[ bld2Idx ].xfo - quqpData.quBuildingData.buildings[ bld1Idx ].xfo + quqpData.quBuildingData.buildings[ bld1Idx ].length; quqpData.qpParamData.nby = 50; quqpData.qpParamData.nbz = quqpData.quBuildingData.buildings[ bld2Idx ].height; log.debug( "set conc N to " , quqpData.qpParamData.nbx , " x " , quqpData.qpParamData.nby , " x " , quqpData.qpParamData.nbz ); quqpData.qpParamData.xbl = quqpData.quBuildingData.buildings[ bld2Idx ].xfo - quqpData.qpParamData.nbx; quqpData.qpParamData.xbu = quqpData.quBuildingData.buildings[ bld2Idx ].xfo; quqpData.qpParamData.ybl = quqpData.quBuildingData.buildings[ bld2Idx ].yfo - quqpData.quBuildingData.buildings[ bld2Idx ].width/2; quqpData.qpParamData.ybu = quqpData.quBuildingData.buildings[ bld2Idx ].yfo + quqpData.quBuildingData.buildings[ bld2Idx ].width/2; quqpData.qpParamData.zbl = 0; quqpData.qpParamData.zbu = quqpData.quBuildingData.buildings[ bld2Idx ].height; log.debug( "set conc dim to [" , quqpData.qpParamData.xbl , ", " , quqpData.qpParamData.ybl , ", " , quqpData.qpParamData.zbl , "] X ]" , quqpData.qpParamData.xbu , ", " , quqpData.qpParamData.ybu , ", " , quqpData.qpParamData.zbu , "]" ); quqpData.qpSourceData.sources[0].points[0].x = quqpData.quBuildingData.buildings[ bld1Idx ].xfo + quqpData.quBuildingData.buildings[ bld1Idx ].length + 0.5; quqpData.qpSourceData.sources[0].points[1].x = quqpData.quBuildingData.buildings[ bld2Idx ].xfo - 0.5; quqpData.qpParamData.writeQUICFile(outDirPath + "/QP_params.inp"); } */ directory::directory(): log(logger(DEBUG, "directory")) { ///:TODO initlaize quqp object with quicPath counter=0; //file *a =new file("dam sure "); // dir.push_back(a); file* temp; temp=new file("optimizationRun.proj"); //this never changes ///0 dir.push_back(temp); temp=new file("QU_buildings.inp"); ///1 dir.push_back(temp); temp=new file("QU_fileoptions.inp"); ///2 dir.push_back(temp); temp=new file("QU_landuse.inp"); ///3 dir.push_back(temp); temp=new file("QU_metparams.inp"); ///4 dir.push_back(temp); temp=new file("QU_simparams.inp"); ///5 dir.push_back(temp); temp=new file("sensor1.inp"); ///6 dir.push_back(temp); temp=new file("optimizationRun.info"); ///7 dir.push_back(temp); temp=new file("QP_materials.inp"); ///8 dir.push_back(temp); temp=new file("QP_indoor.inp"); ///9 dir.push_back(temp); temp=new file("QP_source.inp"); ///10 dir.push_back(temp); temp=new file("QP_fileoptions.inp"); ///11 dir.push_back(temp); temp=new file("QP_params.inp"); ///12 dir.push_back(temp); temp=new file("QP_particlesize.inp"); ///13 dir.push_back(temp); temp=new file("QP_buildout.inp"); /////14 dir.push_back(temp); } directory::~directory() { for(unsigned int i=0;i<dir.size();i++) { delete dir.at(i); } } /* directory::directory(std::string out,std::string quicPath,quqpdata & quqpData,std:: string projFileName1) { char dirName2[128]; outputDir=out; //this directories path mkdir(outputDir.c_str(), S_IRUSR | S_IWUSR | S_IXUSR); //create the main directory // create the inner directory sprintf(dirName2, "%s/optimizationRun_inner", outputDir.c_str()); mkdir(dirName2, S_IRUSR | S_IWUSR | S_IXUSR); outputDir=dirName2; quqpData.quicFilesPath=quicPath; projFileName=projFileName1; }*/ void directory::copyFile(const std::string &sourceFilename, const std::string &destFilename) { int length; char *byteBuffer; std::ifstream is; is.open(sourceFilename.c_str(), ios::binary); if (is.good()) { // get length of file: is.seekg(0, ios::end); length = is.tellg(); is.seekg(0, ios::beg); // allocate memory: byteBuffer = new char[length]; // read data as a block: is.read(byteBuffer, length); is.close(); std::ofstream os; os.open(destFilename.c_str(), ios::binary); os.write(byteBuffer, length); os.close(); } else { log.error("Cannot copyFile: unable to open \"" , sourceFilename , "\"" ); } delete [] byteBuffer; return; } /* void directory::augmentBuildingDataFromSample( const sample &s, quBuildings &bData ) { log.debug( "augment building data" ); for (unsigned int i=0; i<s.size(); i++) { // Look up sample indices and match with population sample data types. namedOptParam *optData = lookupDataInRangeMap(i); log.debug( "checking idx=" , i , ", " , optData->description ); if (optData->description == "bldxfo") { for (unsigned int bidx=0; bidx<bData.buildings.size(); bidx++) if (bData.buildings[ bidx ].bldNum == optData->idx) { bData.buildings[ bidx ].xfo = (int)s[i]; // TRAINING DATA // export out the wind field information to the training data // //trainingModuleExport->appendData(s[i]); break; } } if (optData->description == "bldyfo") { for (unsigned int bidx=0; bidx<bData.buildings.size(); bidx++) if (bData.buildings[ bidx ].bldNum == optData->idx) { bData.buildings[ bidx ].yfo = (int)s[i]; // TRAINING DATA // export out the wind field information to the training data // //trainingModuleExport->appendData(s[i]); break; } } // vary the building heights across all buildings if (optData->description == "buildheight") { // set all building heights for (unsigned int bidx=0; bidx<bData.buildings.size(); bidx++) { bData.buildings[ bidx ].height = (int)s[i]; log.debug( "setting building height to " , bData.buildings[bidx].height ); } // TRAINING DATA // export out the wind field information to the training data // // trainingModuleExport->appendData(s[i]); } if (optData->description == "buildlength") { // set all building lengths for (unsigned int bidx=0; bidx<bData.buildings.size(); bidx++) { bData.buildings[ bidx ].length = (int)s[i]; log.debug( "setting building length to " , bData.buildings[bidx].length ); } // TRAINING DATA // export out the wind field information to the training data // // trainingModuleExport->appendData(s[i]); } } // once all other parameters are varied, including length, we can // set the separation... log.debug( "completing separation..." ); for (unsigned int i=0; i<s.size(); i++) { // Look up sample indices and match with population sample data types. namedOptParam *optData = lookupDataInRangeMap(i); log.debug( "checking idx=" , i , ", " , optData->description ); if (optData->description == "buildsep") { int bld1Idx = bData.findIdxByBldNum(1); assert(bld1Idx != -1); int bld2Idx = bData.findIdxByBldNum(2); assert(bld2Idx != -1); // set the xfo of bld1 based on length of buildings and separation value from sample int bld1xfo = bData.buildings[ bld2Idx ].xfo - bData.buildings[ bld2Idx ].length - (int)s[i]; bData.buildings[ bld1Idx ].xfo = bld1xfo; log.debug( "setting S, making building 1 xfo = " , bld1xfo ); } } } void directory::validate_QU_buildings(const sample& s,sivelab::QUICProject &quqpData) { augmentBuildingDataFromSample(s,quqpData.quBuildingData); // Write this file to the appropriate place. quqpData.quBuildingData.writeQUICFile(outputDir + "/"+dir[1]->fileName); } void directory::validate_sensor1(sivelab::QUICProject &quqpData,const float windangle) { quqpData.quMetParamData.quSensorData.direction = windangle; quqpData.quMetParamData.quSensorData.writeQUICFile(outputDir + "/"+dir[6]->fileName); } void directory::validate_QP_source(sivelab::QUICProject &quqpData) { // ... in the 5D test case, this means modifying the overall int bld1Idx = quqpData.quBuildingData.findIdxByBldNum(1); assert(bld1Idx != -1); int bld2Idx = quqpData.quBuildingData.findIdxByBldNum(2); assert(bld2Idx != -1); quqpData.qpSourceData.sources[0].points[0].x = quqpData.quBuildingData.buildings[ bld1Idx ].xfo + quqpData.quBuildingData.buildings[ bld1Idx ].length; quqpData.qpSourceData.sources[0].points[0].z = 0.5; quqpData.qpSourceData.sources[0].points[1].x = quqpData.quBuildingData.buildings[ bld2Idx ].xfo; quqpData.qpSourceData.sources[0].points[1].z = 0.5; quqpData.qpSourceData.writeQUICFile(outputDir + "/"+dir[10]->fileName); } void directory::validate_QP_params(sivelab::QUICProject &quqpData) { int origNumParticles = quqpData.qpParamData.numParticles; int origDuration = quqpData.qpParamData.duration; quqpData.qpParamData.numParticles = 1; quqpData.qpParamData.duration = 0.1; quqpData.qpParamData.writeQUICFile(outputDir + "/"+dir[12]->fileName); } void directory::validateDir(const sample& s,sivelab::QUICProject &quqpData,const float windangle) { counter++; dir[1]->isValid=false; dir[6]->isValid=false; dir[10]->isValid=false; dir[12]->isValid=false; unsigned int ite; for(ite=0;ite<dir.size();ite++) { if(dir[ite]->isValid==false) { if(ite==1) { validate_QU_buildings(s,quqpData); } else if(ite==6) { validate_sensor1(quqpData,windangle); } else if(ite==10) { validate_QP_source(quqpData); } else if(ite==12) { validate_QP_params(quqpData); } else { std::cerr<<"big error with directory manager"<<std::endl; exit(1); } } } } */ void directory::validateOutputDir(std::vector<std::string> &dataS,sivelab::QUICProject &quqpData) { for(unsigned int i=0 ; i <dataS.size();i++) { if(dataS.at(i)=="quSimParams") { quqpData.quSimParamData.writeQUICFile(outputDir + "/"+dir[5]->fileName); } else if(dataS.at(i)=="quBuildings") { quqpData.quBuildingData.writeQUICFile(outputDir + "/"+dir[1]->fileName); } else if(dataS.at(i)=="quMetParams") { quqpData.quMetParamData.writeQUICFile(outputDir +"/"+dir[4]->fileName); } else if(dataS.at(i)=="qpBuildout") { quqpData.qpBuildoutData.writeQUICFile(outputDir + "/"+dir[14]->fileName); } else if(dataS.at(i)=="qpParams") { quqpData.qpParamData.writeQUICFile(outputDir + "/"+dir[12]->fileName); } else if(dataS.at(i)=="qpSource") { quqpData.qpSourceData.writeQUICFile(outputDir + "/"+dir[10]->fileName); } else if(dataS.at(i)=="quSensor") { quqpData.quMetParamData.quSensorData.writeQUICFile(outputDir + "/"+dir[6]->fileName); } else { log.debug("exit because of unrecognized dataStructure Name"); } } dataS.clear(); } <file_sep>/src/mpi_qes_spf/simpleLSM_job.cpp #include "mpi_qes_spf/simpleLSM_job.h" #include "string" //#include "QESGui.h" //#include "ViewTracer.h" #include <boost/timer/timer.hpp> // this is wallclock AND cpu time bool simpleLSM_job::eval_population_fitness(population &pop) { char pwd[FILENAME_MAX]; getcwd(pwd, sizeof(pwd)); log.debug("Current working directory", pwd); float cputime=0; float walltime=0; for (sample &s : pop) { prepare_work_dir_for_sample(s); boost::timer::cpu_timer timer; eval_sample_fitness(s); boost::timer::cpu_times elapsed = timer.elapsed(); log.debug(" CPU TIME: ", (elapsed.user + elapsed.system) / 1e9, " seconds", ", WALLCLOCK TIME: ", elapsed.wall / 1e9, " seconds"); cputime+=((elapsed.user + elapsed.system) / 1e9); walltime+=(elapsed.wall / 1e9); } log.debug("total CPU TIME:", cputime, "total WALLCLOCK TIME:", walltime); log.debug("avergae CPU TIME:", cputime/pop.size(), "avergae WALLCLOCK TIME:", walltime/pop.size()); return true; } bool simpleLSM_job::eval_sample_fitness( sample &s) { int max_gpus = 1; qes::QESContext context( max_gpus ); // Now we create the Simple Land Surface Model. qes::RadiationTracer radModel; qes::SimpleLSM simpleLSM; qes::ViewTracer viewFactor; simpleLSM.setRadiationTracer( &radModel ); context.joinModel( &radModel ); context.joinModel( &simpleLSM ); context.joinModel( &viewFactor ); // Lets use another function to setup our scene. if ( !loadScene( &context ) ) { return EXIT_FAILURE; } // Now that we've added all the models we want to use and created // our scene, it's time to initialize and compile the system. This // will return false if there is a problem. //context.getVariableTracker()->setBool("verbose_output", false); if ( !context.initialize() ) { return EXIT_FAILURE; } // runDiurnalCycle( &context ); // Run a simulation. //may be get this from opt file qes::SunTracker *g_sunTracker = context.getSunTracker(); int minute_interval = 1; g_sunTracker->updateTimeByMinutes( -minute_interval ); // just to handle the first iteration for ( int min = 0; min <= 2; min += minute_interval ) { log.debug("running simulation ", min+1, "th time"); // This just adds n number of minutes to the current time. g_sunTracker->updateTimeByMinutes( minute_interval ); // Run simulation if ( !context.runSimulation() ) { return EXIT_FAILURE; } } // if ( !context.runSimulation() ) // { // return EXIT_FAILURE; // } // Now we will do something a bit more fun. // QUIC EnvSim has a default visualizer, and it's really easy to use. // To do this we must first create the GUI object: // int screen_width = 1024; // int screen_height = 768; // qes::QESGui gui( screen_height, screen_width, &context ); // Next, call display. This loads the render loop. // Pressing escape or closing the gui will return from this function // and the program can end. // gui.display(); // Exit the program. The QESContext takes care of all the cleanup! if(fitness->eval_fitness(s, &context)) return EXIT_SUCCESS; else return EXIT_FAILURE; } bool simpleLSM_job::loadScene( qes::QESContext *context ) { qes::SceneTracker *g_sceneTracker = context->getSceneTracker(); qes::SunTracker *g_sunTracker = context->getSunTracker(); qes::VariableTracker *g_varTracker = context->getVariableTracker(); std::stringstream project_file; // project_file << QUIC_DATA_DIR << "/NakamuraOke1988/NakamuraOke1988.proj"; project_file << QUIC_DATA_DIR << "/SLC_4m_extended/SLC_4m_extended.proj"; // project_file << QUIC_DATA_DIR << "/SimpleDomain2x2BuildingGrid/SimpleDomain2x2BuildingGrid.proj"; // project_file << "/scratch/quicTests/testGen_2x2/testGen_2x2.proj"; // project_file << QUIC_DATA_DIR << "/Mills/Mills.proj"; g_sceneTracker->setUseAircells( false ); bool scene_built = g_sceneTracker->initScene( workDir.outputDir+"/", "" ); // Make sure the scene was built before doing anything else if ( !scene_built ) { std::cout << "\n**Error building scene! Exiting...\n" << std::endl; return false;; } // Before we run our simulation we should set it to a time where // the radiation model isn't full of errors. Let's do 2pm. int hour = 20; int minute = 0; int second = 0; g_sunTracker->setTimeUTC( hour, minute, second ); g_sunTracker->setDate( 2014, 9, 15 ); // We need to give our models input. This is done through the InputTracker // in the form of surface weather map (SWM) xml files. Each file contains // a list of observations for a given latitude, longitude, date, and time. // Each observation holds records such as air temperature and humidity. // So we need to load a file for SLC in October, 2011. // // First, get the tracker qes::InputTracker *g_inputTracker = context->getInputTracker(); // Next, remove unneeded default data. This step is not necessary, but will // speed up observation retrieval during the simulation. g_inputTracker->clearAll(); // Now load the surface weather map file stored in the resources directory. std::stringstream ss; ss << QES_ROOT_DIR << "/resources/SLCOct2011SWM.xml"; g_inputTracker->loadSWMXML( ss.str() ); // Store energy balance terms that are computed on the host // g_varTracker->setBool( "store_terms", true ); return true; } // end load scene void simpleLSM_job::runDiurnalCycle( qes::QESContext *context ) { // Minutes between simulations int minute_interval = 15; // This patch is just one in an urban canyon near the origin. // Just picking it for now... // int patch_id = 107213; int patch_id = 0; // QES tools qes::SunTracker *g_sunTracker = context->getSunTracker(); qes::BufferTracker *g_buffTracker = context->getBufferTracker(); // Set starting date and time g_sunTracker->setDate( 2011, 10, 1 ); g_sunTracker->setTimeLocal( 0, 0, 0 ); // Output table of surface energy balance for designated patch id. std::map< int, std::vector<double> > seb_output; // minutes elapsed -> [ Rsn, Rl_dowm, Rl_up, Qg, Qh, Qe ] // The dirunal cycle loop g_sunTracker->updateTimeByMinutes( -minute_interval ); // just to handle the first iteration for ( int min = 0; min <= 1440; min += minute_interval ) { // This just adds n number of minutes to the current time. g_sunTracker->updateTimeByMinutes( minute_interval ); // Run simulation if ( !context->runSimulation() ) { return; } // Get energy balance terms std::vector<double> Rs_terms; std::vector<double> Rl_down_terms; std::vector<double> Rl_up_terms; std::vector<double> Qg_terms; std::vector<double> Qh_terms; std::vector<double> Qe_terms; g_buffTracker->getHostBuffer<double>( "Rs_terms", &Rs_terms ); g_buffTracker->getHostBuffer<double>( "Rl_down_terms", &Rl_down_terms ); g_buffTracker->getHostBuffer<double>( "Rl_up_terms", &Rl_up_terms ); g_buffTracker->getHostBuffer<double>( "Qg_terms", &Qg_terms ); g_buffTracker->getHostBuffer<double>( "Qh_terms", &Qh_terms ); g_buffTracker->getHostBuffer<double>( "Qe_terms", &Qe_terms ); // Store energy balance terms std::vector<double> output_vec; // output_vec.push_back( Rs_terms[ patch_id ] ); // output_vec.push_back( Rl_down_terms[ patch_id ] ); // output_vec.push_back( Rl_up_terms[ patch_id ] ); double Rn = Rs_terms[ patch_id ] + Rl_down_terms[ patch_id ] - Rl_up_terms[ patch_id ]; output_vec.push_back( Rn ); output_vec.push_back( Qg_terms[ patch_id ] ); output_vec.push_back( Qh_terms[ patch_id ] ); output_vec.push_back( Qe_terms[ patch_id ] ); seb_output.insert( std::pair< int, std::vector<double> >( min, output_vec ) ); } // end diurnal cycle loop // Output energy balance terms to a file std::ofstream filestream; std::stringstream filename; filename << QES_OUTPUT_DIR << "/seb_output.txt"; filestream.open( filename.str().c_str() ); // filestream << "minutes elapsed, Rsn, Rl_dowm, Rl_up, Qg, Qh, Qe" << std::endl; // header filestream << "minutes elapsed, Rn, Qg, Qh, Qe" << std::endl; // header // Loop over the output generated by the simulation loop std::map< int, std::vector<double> >::iterator it = seb_output.begin(); for ( it; it != seb_output.end(); ++it ) { // Get data int min_elapsed = it->first; std::vector<double> output_vec = it->second; // Output data to file filestream << min_elapsed; for ( int i = 0; i < output_vec.size(); ++i ) { filestream << "\t" << output_vec[i]; } filestream << std::endl; } // end loop seb output filestream.close(); } // end run diurnal cycle <file_sep>/src/utils/include/namedOptParam.h #ifndef NAMED_OPT_PARAM_H #define NAMED_OPT_PARAM_H 1 #include <iostream> #include <string> #include "boost/serialization/access.hpp" #include "boost/serialization/string.hpp" class namedOptParam { private: friend class boost::serialization::access; // When the class Archive corresponds to an output archive, the // & operator is defined similar to <<. Likewise, when the class Archive // is a type of input archive the & operator is defined similar to >>. template<class Archive> void serialize(Archive &ar, const unsigned int version) { ar &description; ar &idx; ar &step; ar &value; ar &type; } public: std::string description; int idx; float step; std::string value; std::string type; /// single || range || set }; #endif <file_sep>/src/opt_grammar/CMakeLists.txt cmake_minimum_required (VERSION 2.6) project (OptimizationFileAntlrParser) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/antlr) add_custom_command(OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/OptFileGrammarParser.cpp ${CMAKE_CURRENT_SOURCE_DIR}/OptFileGrammarParser.hpp ${CMAKE_CURRENT_SOURCE_DIR}/OptFileGrammarLexer.cpp ${CMAKE_CURRENT_SOURCE_DIR}/OptFileGrammarLexer.hpp COMMAND java -jar antlr-3.5.2-complete.jar OptFileGrammar.g DEPENDS OptFileGrammar.g WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} ) add_library(optfileparser OptFileGrammarParser.cpp OptFileGrammarLexer.cpp OptFileGrammar.g ) SET(ANTLR_INCLUDES ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/antlr PARENT_SCOPE)<file_sep>/src/utils/CMakeLists.txt cmake_minimum_required (VERSION 2.8) project (optimizationCode) include_directories (${LIBSIVELAB_PATH}) include_directories(${CMAKE_SOURCE_DIR}/include) add_library(optm-utils ArgumentParsing.cpp directory.cpp FitnessCache.cpp population.cpp solver.cpp population_gen.cpp #concentrationRedux.cpp opt_params.cpp )<file_sep>/src/utils/include/population.h #ifndef SAMPLES_H #define SAMPLES_H #include <math.h> #include <list> #include <cstdlib> #include <vector> #include <iostream> #include <ostream> #include "map" #include <boost/serialization/vector.hpp> #include <boost/serialization/map.hpp> #include "logger/logger.h" using namespace std; using namespace sivelab; // Helper function to generate a sample from a 1D gaussian distribution with // standard deviation sigma double ran_gaussian (const double sigma); // A base class for an n-dimensional point/vector. class pt : public vector< double > { private: friend class boost::serialization::access; // When the class Archive corresponds to an output archive, the // & operator is defined similar to <<. Likewise, when the class Archive // is a type of input archive the & operator is defined similar to >>. template<class Archive> void serialize(Archive &ar, const unsigned int version) { ar &boost::serialization::base_object< vector<double> >(*this); } public: // constructors with some easy low-dimension ones pt(); pt(int dimension); pt( double x ); pt( double x, double y ); pt( double x, double y, double z ); // This is the generic dimension constructor pt ( vector< double > &in ); // Destructor ~pt(); // Some simple math operations - note we treat as vectors so can do + pt operator+(const pt &p); pt operator-(const pt &p); pt operator*(const double &scalar); pt operator/(const double &scalar); }; ostream &operator<<( ostream &os, pt &s ); // A sample is a point in the n-dimensional domain with the ability // to evaluate and store a fitness value. // In the building case, the passed in eval_func should convert the point // to integer and run a test to get a fitness score. class sample : public pt { private: friend class boost::serialization::access; // When the class Archive corresponds to an output archive, the // & operator is defined similar to <<. Likewise, when the class Archive // is a type of input archive the & operator is defined similar to >>. template<class Archive> void serialize(Archive &ar, const unsigned int version) { ar &boost::serialization::base_object< pt >(*this); ar &fitness; } public: std::map<string, double> fitness; sample(); sample(int dimension); sample(pt &in); ~sample(); // You must pass in the function that will do that actual fitness scoring double eval_sample( double (*eval_func)( sample &s ) ); //bool operator<(sample rhs) { return fitness < rhs.fitness; } ///this function was to use the sort function in std :: }; ostream &operator<<( ostream &os, sample &s ); // A population is a collection of samples. class population : public vector< sample > { private : logger log; friend class boost::serialization::access; // When the class Archive corresponds to an output archive, the // & operator is defined similar to <<. Likewise, when the class Archive // is a type of input archive the & operator is defined similar to >>. template<class Archive> void serialize(Archive &ar, const unsigned int version) { ar &boost::serialization::base_object< vector<sample> >(*this); ar &dimension; } public: int dimension; population &operator=( const population &source ); population() { log = logger(ERROR, "population"); }; population( int pop_size, int dimension_ ); population(double pop[], int no_of_samples_, int dimensions_); ///this constructor converts a 1d array to a population void eval_population_fitness( double (*eval_func)( sample &s ) ); void randomize_samples( vector< double > &domain_min, vector< double > &domain_max ); double sum_fitnesses(); void print(); void draw_population(); int get_subset(int start, int size, population &pop); }; ostream &operator<<( ostream &os, population &p ); #endif <file_sep>/fitness_lib/include/fitness_function.h #ifndef __FITNESS_FUNCTION__ #define __FITNESS_FUNCTION__ 1 #include <iostream> #include <map> #include <string> #include "utils/population.h" #include "QESContext.h" #include "quicutil/QUICProject.h" #include "utils/opt_params.h" using namespace std; using namespace sivelab; class Fitness{ private: std::vector<int> patchIDs; QUICProject& quqpData; opt_params& optParams; std::map<string, std::vector<float> > buffers; public: Fitness(QUICProject& _quqpData, opt_params& _optParams); //make the result a template value so users can return whatever type of results they want virtual bool eval_fitness(sample& s, qes::QESContext* context); virtual void fetchBuffers(qes::QESContext* context); virtual void fetchPatchIds(qes::QESContext* context); }; #endif <file_sep>/src/utils/include/opt_params.h #ifndef __OPT_PARAMS__ #define __OPT_PARAMS__ 1 #include "boost/serialization/string.hpp" #include "boost/serialization/vector.hpp" #include "logger/logger.h" #include "utils/namedOptParam.h" #include "utils/dependencyOptParam.h" #include "vector" #include "string" #include "map" using namespace sivelab; namespace sivelab { //**This is a stupid design let this be a giant class containing optimization parameters for every job class opt_params { private: //TODO check boost archive once and see if the following needs to be put in public or private friend class boost::serialization::access; // When the class Archive corresponds to an output archive, the // & operator is defined similar to <<. Likewise, when the class Archive // is a type of input archive the & operator is defined similar to >>. template<class Archive> void serialize(Archive &ar, const unsigned int version) { ar &use_BruteForceSolver; ar &useTimeStepSet; ar &useNumParticleSet; ar &use_Population; ar &use_avgParam; ar &seednumber; ar &baseproj_inner_path; ar &solver_name; //ar &populationFile; //ar &fitness_function; ar &avgParamName; ar &rangeOptMap; ar &setOptMap; ar &singleOptMap; ar &dependencyOptMap; ar &solverOptMap; ar &minValues; ar &maxValues; ar &stepValues; ar &singleValues; ar &setValues; ar &numParticleSet; ar &timeStepSet; ar &avgParam; ///this is a vector that holds the set values of the averaging paramter // ar &filePopulation ; } public: bool readParams(const std::map<string, map<string, string>> &optParams); void printOptimizationParams(); opt_params(); std::vector<double> minValues; std::vector<double> maxValues; std::vector<int> stepValues; std::vector<std::string> singleValues; std::vector<vector<double> > setValues; std::vector<int> numParticleSet; std::vector<float> timeStepSet; std::vector<namedOptParam> rangeOptMap; std::vector<namedOptParam> setOptMap; std::vector<namedOptParam> singleOptMap; std::vector<dependencyOptParam> dependencyOptMap; std::vector<namedOptParam> solverOptMap; std::vector<double> avgParam; ///this is a vector that holds the set values of the averaging paramter bool use_BruteForceSolver; bool useTimeStepSet; bool useNumParticleSet; bool use_Population; bool use_avgParam; long int seednumber; string baseproj_inner_path; std::string avgParamName; string solver_name; logger log; }; } #endif<file_sep>/src/utils/include/dependencyOptParam.h #ifndef __DEPENDENCYOPTPARAM__ #define __DEPENDENCYOPTPARAM__ 1 #include <boost/serialization/string.hpp> class dependencyOptParam { private: friend class boost::serialization::access; // When the class Archive corresponds to an output archive, the // & operator is defined similar to <<. Likewise, when the class Archive // is a type of input archive the & operator is defined similar to >>. template<class Archive> void serialize(Archive &ar, const unsigned int version) { ar &variable_name; ar &operand1; ar &operand2; ar &op; ar &idx; } public: std::string variable_name; std::string operand1; std::string operand2; char op; int idx; /// single || range || set }; #endif <file_sep>/CMakeLists.txt cmake_minimum_required (VERSION 2.8) project (optimizationCode) #Matt has his own version of libsivelab I am also using that since using a seperate once #is resulting in naming colissions. SET(LIBSIVELAB_PATH "${CMAKE_SOURCE_DIR}/lib/quic_envsim/lib/libsivelab") SET(QUIC_DATA_PATH "${CMAKE_SOURCE_DIR}/../quicdata") SET(QES_ROOT_DIR "${CMAKE_SOURCE_DIR}/../quic_envsim") SET(GMOCK_SOURCE_DIR "${CMAKE_SOURCE_DIR}/lib/gmock") SET(GTEST_SOURCE_DIR "${GMOCK_SOURCE_DIR}/gtest") #Build QES libraries only set(BUILD_LIBS_ONLY "TRUE") #Build unit tests set(BUILD_TESTS "TRUE") #set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib) #Setting compiler to use C++11 SET (DEFAULT_CXX_FLAGS ${CMAKE_CXX_FLAGS}) SET (CMAKE_CXX_FLAGS "${DEFAULT_CXX_FLAGS} -std=c++11") SET (CMAKE_BUILD_TYPE Debug) message(STATUS "###Adding lib directory###") add_subdirectory(lib) #this include directories for quic_envsim #the variable is set in lib/quic_envsim with PARENT_SCOPE #setting it here again so that it is visible in sibling directories of lib i.e., src, fitness_lib, test set(QES_INCLUDE_DIRECTORIES ${QES_INCLUDE_DIRECTORIES}) #need for quic_envsim include files add_definitions( -DQES_OUTPUT_DIR="${CMAKE_CURRENT_BINARY_DIR}/output" ) # QES_OUTPUT_DIR add_definitions( -DQES_PTX_DIR="${CMAKE_CURRENT_BINARY_DIR}/programs" ) # QES_PTX_DIR message(STATUS "###Adding src directory###") add_subdirectory(src) SET(ANTLR_INCLUDES ${ANTLR_INCLUDES}) #fintess function shared library message(STATUS "###Adding fitness_lib directory###") add_subdirectory(fitness_lib) if(BUILD_TESTS) enable_testing( ) message(STATUS "###Adding test directory###") add_subdirectory(tests) endif() <file_sep>/tests/utils/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project (optimizationCode) #population generation test #Add test cpp file add_executable( test_population_gen test_population_gen.cpp ) #Link test executable against gtest & gtest_main target_link_libraries( test_population_gen gtest gtest_main optm-utils) add_test( NAME populationGenerationTest WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/bin COMMAND test_population_gen) #population test add_executable( test_population test_population.cpp ) #Link test executable against gtest & gtest_main target_link_libraries( test_population gtest gtest_main optm-utils) add_test( NAME populationTest WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/bin COMMAND test_population) #opt params test #Add test cpp file add_executable( test_optParams test_optParams.cpp ) #Link test executable against gtest & gtest_main target_link_libraries( test_optParams gmock gmock_main gtest gtest_main optm-utils) add_test( NAME optParamsTest WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/bin COMMAND test_optParams) #Add test cpp file add_executable( test_directory test_directory.cpp ) #Link test executable against gtest & gtest_main target_link_libraries( test_directory gmock gmock_main gtest gtest_main optm-utils) target_link_libraries( test_directory sive-quicutil) target_link_libraries( test_directory sive-util) add_test( NAME directoryTest WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/bin COMMAND test_directory) add_custom_command(TARGET test_directory PRE_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/testFile.txt ${CMAKE_BINARY_DIR}/bin)<file_sep>/tests/utils/test_directory.cpp #include "gtest/gtest.h" #include "gmock/gmock.h" #include "utils/directory.h" std::string exec(string& str) { const char *cmd = str.c_str(); FILE* pipe = popen(cmd, "r"); if (!pipe) return "ERROR"; char buffer[128]; std::string result = ""; while(!feof(pipe)) { if(fgets(buffer, 128, pipe) != NULL) result += buffer; } pclose(pipe); return result; } TEST(DirectoryTest, test_file_copy){ directory d; d.copyFile("./testFile.txt", "./testFile.out"); string cmd = "diff --ignore-all-space ./testFile.txt ./testFile.out"; string diff = exec(cmd); ASSERT_EQ("", diff); }<file_sep>/src/mpi_qes_spf/simpleLSM.cpp /** * @author <NAME> */ #include "QESContext.h" #include "SimpleLSM.h" //#include "QESGui.h" #include "util/handleQUICArgs.h" #include "quicutil/QUICProject.h" #include "ViewTracer.h" bool loadScene( qes::QESContext *context ); void runDiurnalCycle( qes::QESContext *context ); int main( int argc, char** argv ) { // The first thing we need to do is create our QUIC EnvSim context. // The context controls many of the environment variables we need // for the system to run smoothly. It also acts as a simple wrapper // for OptiX and CUDA. // // We set it up by joining all the models we want, building the // scene, then intializing the context. Initialization of the context // will compile everything together. This means no new geometry or // models can be added, and attempts to do so will be blocked. // // When running different model sets and different scenes within // the same executable, it's best to just destroy the QESContext // and build a new one. int max_gpus = 1; qes::QESContext context( max_gpus ); // Now we create the Simple Land Surface Model. qes::RadiationTracer radModel; qes::SimpleLSM simpleLSM; qes::ViewTracer viewFactor; simpleLSM.setRadiationTracer( &radModel ); context.joinModel( &radModel ); context.joinModel( &simpleLSM ); context.joinModel( &viewFactor ); // Lets use another function to setup our scene. if( !loadScene( &context ) ){ return EXIT_FAILURE; } // Now that we've added all the models we want to use and created // our scene, it's time to initialize and compile the system. This // will return false if there is a problem. if( !context.initialize() ){ return EXIT_FAILURE; } // runDiurnalCycle( &context ); // Run a simulation. if( !context.runSimulation() ){ return EXIT_FAILURE; } // Now we will do something a bit more fun. // QUIC EnvSim has a default visualizer, and it's really easy to use. // To do this we must first create the GUI object: // int screen_width = 1024; // int screen_height = 768; // qes::QESGui gui( screen_height, screen_width, &context ); // Next, call display. This loads the render loop. // Pressing escape or closing the gui will return from this function // and the program can end. // gui.display(); // Exit the program. The QESContext takes care of all the cleanup! return EXIT_SUCCESS; } // end main bool loadScene( qes::QESContext *context ){ qes::SceneTracker *g_sceneTracker = context->getSceneTracker(); qes::SunTracker *g_sunTracker = context->getSunTracker(); qes::VariableTracker *g_varTracker = context->getVariableTracker(); std::stringstream project_file; // project_file << QUIC_DATA_DIR << "/NakamuraOke1988/NakamuraOke1988.proj"; project_file << QUIC_DATA_DIR << "/SLC_4m_extended/SLC_4m_extended.proj"; // project_file << QUIC_DATA_DIR << "/SimpleDomain2x2BuildingGrid/SimpleDomain2x2BuildingGrid.proj"; // project_file << "/scratch/quicTests/testGen_2x2/testGen_2x2.proj"; // project_file << QUIC_DATA_DIR << "/Mills/Mills.proj"; g_sceneTracker->setUseAircells( false ); bool scene_built = g_sceneTracker->initScene( project_file.str(), "" ); // Make sure the scene was built before doing anything else if( !scene_built ){ std::cout << "\n**Error building scene! Exiting...\n" << std::endl; return false;; } // Before we run our simulation we should set it to a time where // the radiation model isn't full of errors. Let's do 2pm. int hour = 14; int minute = 0; int second = 0; g_sunTracker->setTimeLocal( hour, minute, second ); g_sunTracker->setDate( 2011, 10, 1 ); // We need to give our models input. This is done through the InputTracker // in the form of surface weather map (SWM) xml files. Each file contains // a list of observations for a given latitude, longitude, date, and time. // Each observation holds records such as air temperature and humidity. // So we need to load a file for SLC in October, 2011. // // First, get the tracker qes::InputTracker *g_inputTracker = context->getInputTracker(); // Next, remove unneeded default data. This step is not necessary, but will // speed up observation retrieval during the simulation. g_inputTracker->clearAll(); // Now load the surface weather map file stored in the resources directory. std::stringstream ss; ss << QES_ROOT_DIR << "/resources/SLCOct2011SWM.xml"; g_inputTracker->loadSWMXML( ss.str() ); // Store energy balance terms that are computed on the host // g_varTracker->setBool( "store_terms", true ); return true; } // end load scene void runDiurnalCycle( qes::QESContext *context ){ // Minutes between simulations int minute_interval = 15; // This patch is just one in an urban canyon near the origin. // Just picking it for now... // int patch_id = 107213; int patch_id = 0; // QES tools qes::SunTracker *g_sunTracker = context->getSunTracker(); qes::BufferTracker *g_buffTracker = context->getBufferTracker(); // Set starting date and time g_sunTracker->setDate( 2011, 10, 1 ); g_sunTracker->setTimeLocal( 0, 0, 0 ); // Output table of surface energy balance for designated patch id. std::map< int, std::vector<double> > seb_output; // minutes elapsed -> [ Rsn, Rl_dowm, Rl_up, Qg, Qh, Qe ] // The dirunal cycle loop g_sunTracker->updateTimeByMinutes( -minute_interval ); // just to handle the first iteration for( int min=0; min <= 1440; min += minute_interval ){ // This just adds n number of minutes to the current time. g_sunTracker->updateTimeByMinutes( minute_interval ); // Run simulation if( !context->runSimulation() ){ return; } // Get energy balance terms std::vector<double> Rs_terms; std::vector<double> Rl_down_terms; std::vector<double> Rl_up_terms; std::vector<double> Qg_terms; std::vector<double> Qh_terms; std::vector<double> Qe_terms; g_buffTracker->getHostBuffer<double>( "Rs_terms", &Rs_terms ); g_buffTracker->getHostBuffer<double>( "Rl_down_terms", &Rl_down_terms ); g_buffTracker->getHostBuffer<double>( "Rl_up_terms", &Rl_up_terms ); g_buffTracker->getHostBuffer<double>( "Qg_terms", &Qg_terms ); g_buffTracker->getHostBuffer<double>( "Qh_terms", &Qh_terms ); g_buffTracker->getHostBuffer<double>( "Qe_terms", &Qe_terms ); // Store energy balance terms std::vector<double> output_vec; // output_vec.push_back( Rs_terms[ patch_id ] ); // output_vec.push_back( Rl_down_terms[ patch_id ] ); // output_vec.push_back( Rl_up_terms[ patch_id ] ); double Rn = Rs_terms[ patch_id ] + Rl_down_terms[ patch_id ] - Rl_up_terms[ patch_id ]; output_vec.push_back( Rn ); output_vec.push_back( Qg_terms[ patch_id ] ); output_vec.push_back( Qh_terms[ patch_id ] ); output_vec.push_back( Qe_terms[ patch_id ] ); seb_output.insert( std::pair< int, std::vector<double> >( min, output_vec ) ); } // end diurnal cycle loop // Output energy balance terms to a file std::ofstream filestream; std::stringstream filename; filename << QES_OUTPUT_DIR << "/seb_output.txt"; filestream.open( filename.str().c_str() ); // filestream << "minutes elapsed, Rsn, Rl_dowm, Rl_up, Qg, Qh, Qe" << std::endl; // header filestream << "minutes elapsed, Rn, Qg, Qh, Qe" << std::endl; // header // Loop over the output generated by the simulation loop std::map< int, std::vector<double> >::iterator it = seb_output.begin(); for( it; it != seb_output.end(); ++it ){ // Get data int min_elapsed = it->first; std::vector<double> output_vec = it->second; // Output data to file filestream << min_elapsed; for( int i=0; i<output_vec.size(); ++i ){ filestream << "\t" << output_vec[i]; } filestream << std::endl; } // end loop seb output filestream.close(); } // end run diurnal cycle <file_sep>/src/utils/include/concentrationRedux.h #ifndef __CONCENTRATIONREDUX_H__ #define __CONCENTRATIONREDUX_H__ 1 #include <cstdlib> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <list> #include <limits> #include <cmath> #include "quicutil/QUBuildings.h" #include "quicutil/QPSource.h" ///wiling to put the logic into calc mean so it wont create problems class concentrationRedux { public: concentrationRedux(); concentrationRedux(const std::string &filename, const quBuildings &quBuildingData, const qpSource &qpSourceData, double zSliceMax=1.5); ~concentrationRedux(); struct concData { double x, y, z, c; }; // sets the Z Height max for doing statistics. Since we're // generally interested in the urban layer, this is a first crack at // letting the stats be from Z = 2.5 or lower. void setZSliceMax(const double sliceMax) { m_zslice_max = sliceMax; } void useAllData() { m_useAllData = true; } double max(void) const { return m_max; } double min(void) const { return m_min; } double mean(void) const { return m_mean; } double sum(void) const { return m_sum; } double stddev(void) const { return m_stddev; } double norm1(void) const { return m_norm1; } double norm2(void) const { return m_norm2; } double norm3(void) const { return m_norm3; } double norm4(void) const { return m_norm4; } // Max concentration at a specific elevation // double max(const double elev); const { return m_max; } int exceedances(void) const { return m_exceedanceCount; } std::string getLocalFilename() const { return m_concFilename; } void writeConcFile(); void clearData(void) { m_exceedanceCount = 0; m_concData.clear(); m_concFilename=""; } private: std::string m_concFilename; std::list<concData> m_concData; double m_max; double m_min; double m_mean; double m_sum; double m_stddev; double m_norm1; ///values to hold the norm values double m_norm2; double m_norm3; double m_norm4; int m_exceedanceCount; double m_zslice_max; bool m_useAllData; void calcMean(void); void calcMinMax(void); void calcExceedances(double threshold); void removeEmitterCells(const qpSource &qpSourceData); void removeBuildingCells(const quBuildings &quBuildingData); }; #endif // #define __CONCENTRATIONREDUX_H__ 1 <file_sep>/tests/opt_grammar/test_opt_grammar.cpp //Following are the valid strings that can be parsed by "OptFileGrammar.g" grammar //Some extra strings like arithmetic operations are also supported by "OptFileGrammar.g" // but their functionality is not used yet. #include "OptFileGrammarLexer.hpp" #include "OptFileGrammarParser.hpp" #include "gtest/gtest.h" #include "sstream" using namespace std; class OptFileParseTest: public testing::Test { public: stringstream OptfileContents; map < string, map<string, string>> optParams; string error; int readOptimizationFile() { OptFileGrammarLexer::InputStreamType input((ANTLR_UINT8 *) "", ANTLR_ENC_8BIT, 0, (ANTLR_UINT8 *) "userinput"); std::string inputLine; istream *input_stream = &OptfileContents; long line_number = 1; while (getline(*input_stream, inputLine)) { if (inputLine.size() != 0) { input.reuse((ANTLR_UINT8 *) inputLine.c_str(), inputLine.length(), (ANTLR_UINT8 *) "userinput"); OptFileGrammarLexer lexer(&input); OptFileGrammarParser::TokenStreamType token_stream(ANTLR_SIZE_HINT, lexer.get_tokSource()); OptFileGrammarParser parser(&token_stream); parser.unit(); if (lexer.error_in_lexer || parser.error_in_parser) { error.clear(); error = lexer.err_stream.str()+parser.errtext.str(); return -1; } else { for (auto &itr : parser.each_line){ cout<<itr.first<<" : "<<itr.second<<endl; } if(parser.each_line.size()!=0) optParams[parser.each_line["lval"]] = parser.each_line; } } line_number++; } return 0; } }; /* const job_type = 'lsm'\n" <<"//dummy = [1:1:100]\n" <<"const seed = 9999\n" <<"quBuildings.buildings[0].xfo = [23 24]\n" <<"quBuildings.buildings[0].yfo = [37.0:1.0:40.0]\n" <<"//quBuildings.buildings[4].xfo = 23 + quBuildings.buildings[0].xfo\n"; */ TEST_F(OptFileParseTest, comment) { OptfileContents<<"//This is a comment"; ASSERT_NE(-1, readOptimizationFile())<<"Expected error: : "<<error; //comments are not included in opt params, they are ignored. ASSERT_EQ(0, optParams.size()); SUCCEED(); } TEST_F(OptFileParseTest, number_assignment) { OptfileContents<<" a=1"; ASSERT_NE(-1, readOptimizationFile())<<"Expected error: : "<<error; //there must be one entry in optparams ASSERT_EQ(optParams.size(), 1); auto current_map = optParams["a"]; ASSERT_EQ("a", current_map["lval"]); ASSERT_EQ("project_variable", current_map["lval_type"]); ASSERT_EQ("1", current_map["rval"]); ASSERT_EQ("number", current_map["rval_type"]); } TEST_F(OptFileParseTest, string_assignment) { string str = "str='../this/is/a/path'"; OptfileContents<<str; ASSERT_NE(-1, readOptimizationFile())<<"Expected error: : "<<error; //there must be one entry in optparams ASSERT_EQ(optParams.size(), 1); auto current_map = optParams["str"]; ASSERT_EQ("str", current_map["lval"]); ASSERT_EQ("project_variable", current_map["lval_type"]); ASSERT_EQ("../this/is/a/path", current_map["rval"]); ASSERT_EQ("string", current_map["rval_type"]); } //There are two type of variables project variables and control variables //Project variables specify changes to parameters etc //Control variables specify things that all simulations need like //base project path, type of solver to use etc TEST_F(OptFileParseTest, control_variable) { string str = "const str='../this/is/a/path'"; OptfileContents<<str; ASSERT_NE(-1, readOptimizationFile())<<"Expected error: : "<<error; //there must be one entry in optparams ASSERT_EQ(optParams.size(), 1); auto current_map = optParams["str"]; ASSERT_EQ("str", current_map["lval"]); ASSERT_EQ("control", current_map["lval_type"]); ASSERT_EQ("../this/is/a/path", current_map["rval"]); ASSERT_EQ("string", current_map["rval_type"]); } TEST_F(OptFileParseTest, empty_input) { string str = ""; OptfileContents<<str; ASSERT_NE(-1, readOptimizationFile())<<"Expected error: : "<<error; //there must be one entry in optparams ASSERT_EQ(optParams.size(), 0); } TEST_F(OptFileParseTest, set_assignment){ //beware this is not a mathematical set it is an array //TODO: change the naming to array someday string str = "setVar = [10 11 12]"; OptfileContents<<str; ASSERT_NE(-1, readOptimizationFile())<<"Expected error: : "<<error; //there must be one entry in optparams ASSERT_EQ(optParams.size(), 1); auto current_map = optParams["setVar"]; ASSERT_EQ("setVar", current_map["lval"]); ASSERT_EQ("project_variable", current_map["lval_type"]); string vecString = current_map["rval"]; ASSERT_EQ("set", current_map["rval_type"]); string expectedVecString= "10 11 12"; ASSERT_EQ(expectedVecString.length(), vecString.length()); ASSERT_EQ(expectedVecString, vecString); } TEST_F(OptFileParseTest, range_assignment){ string str = "rangeVar = [1:3:10]"; OptfileContents<<str; ASSERT_NE(-1, readOptimizationFile())<<"Expected error: : "<<error; //there must be one entry in optparams ASSERT_EQ(optParams.size(), 1); auto current_map = optParams["rangeVar"]; ASSERT_EQ("rangeVar", current_map["lval"]); ASSERT_EQ("project_variable", current_map["lval_type"]); ASSERT_EQ("range", current_map["rval_type"]); string minExpected = "1"; string stepExpected = "3"; string maxExpected = "10"; ASSERT_EQ(minExpected, current_map["min"]); ASSERT_EQ(stepExpected, current_map["step"]); ASSERT_EQ(maxExpected, current_map["max"]); } TEST_F(OptFileParseTest, vector_variable_missing_index){ string str = "object[] = 20"; OptfileContents<<str; //this test should result in a parse error ASSERT_EQ(-1, readOptimizationFile())<<"Expected error: : "<<error; } TEST_F(OptFileParseTest, vector_variable){ string str = "object[10] = 20"; //There are no stand alone vector variables in this language. //A vector must always be followed by a '.identifier' e.g.object[1].member[0] //It's funny! OptfileContents<<str; ASSERT_EQ(-1, readOptimizationFile())<<"Expected error: : "<<error; } TEST_F(OptFileParseTest, member_variable){ string str = "object.member = 20"; OptfileContents<<str; ASSERT_NE(-1, readOptimizationFile())<<"Expected error: : "<<error; //there must be one entry in optparams ASSERT_EQ(optParams.size(), 1); auto current_map = optParams["object.member"]; ASSERT_EQ("object.member", current_map["lval"]); ASSERT_EQ("project_variable", current_map["lval_type"]); ASSERT_EQ("number", current_map["rval_type"]); ASSERT_EQ("20", current_map["rval"]); } TEST_F(OptFileParseTest, last_member_variable_is_array){ string str = "object.member[0] = 20"; OptfileContents<<str; //There are no stand alone vector variables in this language. //A vector must always be followed by a '.identifier' e.g.object[1].member[0] //this test should result in a parse error ASSERT_EQ(-1, readOptimizationFile())<<"Expected error: : "<<error; } TEST_F(OptFileParseTest, invalid_memeber_variable_of_array){ string str = "quBuildings[0].xfo = [23 24]"; OptfileContents<<str; //this test should result in a parse error //member variables must begin with an identifier valid //eg. quBuildings.buildings[0].xfo = [23 24] //this test should result in a parse error ASSERT_EQ(-1, readOptimizationFile())<<"Expected error: : "<<error; } TEST_F(OptFileParseTest, memeber_variable_of_array){ string str = "quBuildings.buildings[0].xfo = 23"; OptfileContents<<str; ASSERT_NE(-1, readOptimizationFile())<<"Expected error: : "<<error; //there must be one entry in optparams ASSERT_EQ(optParams.size(), 1); auto current_map = optParams["quBuildings.buildings[0].xfo"]; ASSERT_EQ("quBuildings.buildings[0].xfo", current_map["lval"]); ASSERT_EQ("project_variable", current_map["lval_type"]); ASSERT_EQ("23", current_map["rval"]); ASSERT_EQ("number", current_map["rval_type"]); } //test <file_sep>/src/quic.cpp //stdlib headers #include "iostream" #include "sstream" #include "fstream" #include "math.h" //framerworks headers #include "boost/mpi.hpp" #include "boost/variant.hpp" #include "boost/serialization/variant.hpp" #include <boost/timer/timer.hpp> #include "logger/logger.h" //application headers //use the ArgumentParsing.h in libsivelab. For now I have just renamed the class as I am getting compile errors #include "utils/ArgumentParsing.h" #include "utils/opt_params.h" #include "utils/population_gen.h" #include "MPI_framework/job.h" //#include "mpi_gpuplume/gpu_plume_job.h" #include "opt_grammar/OptFileGrammarLexer.hpp" #include "opt_grammar/OptFileGrammarParser.hpp" #include "mpi_qes_spf/simpleLSM_job.h" //using namespaces using namespace std; using namespace boost; //application namespaces using namespace sivelab; constexpr int MASTER = 0; enum MESSAGE_TYPE { JOB_DATATYPE, OPT_PARAMS, POPULATION, RESULTS, EXIT }; //modify this as new jobs are added enum JOB_TYPE { GPU_PLUME_JOB, SIMPLE_LSM_JOB, INVALID_JOB }; //modify this as new jobs are added //typedef boost::variant<gpu_plume_job> ANY_JOB; /* Reads in optfile and returns a map of optimization parameters read */ //consider adding interpreter support if you feel like doing it //constexpr bool RUN_AS_INTERPRETER = false; void readOptimizationFile(string optfile, map < string, map<string, string>> &optParams) { //creating logger logger log(DEBUG, "quic-parsing opt"); OptFileGrammarLexer::InputStreamType input((ANTLR_UINT8 *) "", ANTLR_ENC_8BIT, 0, (ANTLR_UINT8 *) "userinput"); std::string inputLine; ifstream fin(optfile, std::ifstream::in); istream *input_stream = &fin; long line_number = 1; while (getline(*input_stream, inputLine)) { log.debug("\n\nInput line:", inputLine); trim(inputLine); if (inputLine.size() != 0) { input.reuse((ANTLR_UINT8 *) inputLine.c_str(), inputLine.length(), (ANTLR_UINT8 *) "userinput"); OptFileGrammarLexer lexer(&input); OptFileGrammarParser::TokenStreamType token_stream(ANTLR_SIZE_HINT, lexer.get_tokSource()); OptFileGrammarParser parser(&token_stream); parser.unit(); if (lexer.error_in_lexer || parser.error_in_parser) { //WTF is wrong with this line its throwing an exception /* [1,0]<stderr>:*** Error in `./quic': munmap_chunk(): invalid pointer: 0x000000000197a150 *** [1,0]<stderr>:[csdev01:28255] *** Process received signal *** [1,0]<stderr>:[csdev01:28255] Signal: Aborted (6) [1,0]<stderr>:[csdev01:28255] Signal code: (-6) [1,0]<stderr>:[csdev01:28255] [ 0] /lib/x86_64-linux-gnu/libc.so.6(+0x36ff0) [0x7fc092e32ff0] [1,0]<stderr>:[csdev01:28255] [ 1] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x39) [0x7fc092e32f79] [1,0]<stderr>:[csdev01:28255] [ 2] /lib/x86_64-linux-gnu/libc.so.6(abort+0x148) [0x7fc092e36388] [1,0]<stderr>:[csdev01:28255] [ 3] /lib/x86_64-linux-gnu/libc.so.6(+0x741d4) [0x7fc092e701d4] [1,0]<stderr>:[csdev01:28255] [ 4] /lib/x86_64-linux-gnu/libc.so.6(+0x7ef37) [0x7fc092e7af37] [1,0]<stderr>:[csdev01:28255] [ 5] /usr/lib/x86_64-linux-gnu/libstdc++.so.6(_ZNSsD1Ev+0x1f) [0x7fc0937984df] [1,0]<stderr>:[csdev01:28255] [ 6] ./quic(_ZNK7sivelab6logger5printIPKcISsS3_lS3_EEEvT_DpT0_+0xb3) [0x5367e9] [1,0]<stderr>:[csdev01:28255] [ 7] ./quic(_ZNK7sivelab6logger5errorIJPKclS3_EEEvDpT_+0x64) [0x533424] [1,0]<stderr>:[csdev01:28255] [ 8] ./quic(_Z20readOptimizationFileSsRSt3mapISsS_ISsSsSt4lessISsESaISt4pairIKSsSsEEES1_SaIS2_IS3_S6_EEE+0x26d) [0x52920a] [1,0]<stderr>:[csdev01:28255] [ 9] ./quic(main+0xd0a) [0x52a3ef] [1,0]<stderr>:[csdev01:28255] [10] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5) [0x7fc092e1dec5] [1,0]<stderr>:[csdev01:28255] [11] ./quic() [0x528edf] [1,0]<stderr>:[csdev01:28255] *** End of error message *** */ /* Was a bug in atomExp codeblock in antlr grammar file cause antlr was executing the code block even when there is only partial matching in parsing The atomExp was accessing memory out of bounds */ log.error("At line ", line_number, "\n"); } else { log.debug("Extracted info:"); for (auto &itr : parser.each_line) { log.debug(itr.first, " : ", itr.second, ", "); } if(parser.each_line.size()!=0){ optParams[parser.each_line["lval"]] = parser.each_line; } } } line_number++; } } int main(int argc, char *argv[]) { /*{ int i = 0; char hostname[256]; gethostname(hostname, sizeof(hostname)); printf("PID %d on %s ready for attach\n", getpid(), hostname); fflush(stdout); while (0 == i) sleep(5); }*/ //creating a logger logger log( DEBUG, "quic"); //initializing mpi environment mpi::environment env; mpi::communicator world; int total_servants = world.size() - 1; //excluding master // total_servants = 1;//REOMVE THIS if (total_servants < 1) { log.error("Need atleast 2 nodes"); exit(EXIT_FAILURE); } const string mastername = "<NAME>"; ArgumentParser argParser; argParser.reg("version", 'v', no_argument); argParser.reg("solver", 's', required_argument); argParser.reg("numsamples", 'n', required_argument); argParser.reg("sigma", 'q', required_argument); argParser.reg("convergence", 'c', required_argument); argParser.reg("optfile", 'o', required_argument);//fix this it is not erring out when an optimization file is not given argParser.reg("usedb", 'd', no_argument); argParser.reg("loglevel", 'l', required_argument); argParser.processCommandLineArgs(argc, argv); //setting log level string printinfo = "info"; if (argParser.isSet("loglevel", printinfo)) { if (printinfo == "debug") log.set_log_level(DEBUG); else if (printinfo == "info") log.set_log_level(INFO); else if (printinfo == "error") log.set_log_level(ERROR); else if (printinfo == "all") log.set_log_level(ALL); log.debug("Log level set to:", printinfo); } std::string output_location; { stringstream ss; ss << "/scratch/workingDir_"; ss << world.rank(); output_location = ss.str(); ss.clear(); } if (world.rank() == MASTER) { log.info("Master(", "\b" + mastername, "\b) node started"); log.info("Total no of servants: " , world.size()); if (argParser.isSet("version")) { std::cout << "plumeOptimization: version 0.0.1" << std::endl; } std::string argVal = ""; bool use_BruteForceSolver = false; if (argParser.isSet("solver", argVal)) { if (argVal == "bruteforce" || argVal == "BruteForce" || argVal == "brute") use_BruteForceSolver = true; } int SIR_numSamples = 5; if (argParser.isSet("numsamples", argVal)) { SIR_numSamples = atoi(argVal.c_str()); } float SIR_initialSigma = 2.25; if (argParser.isSet("sigma", argVal)) { SIR_initialSigma = atof(argVal.c_str()); } float SIR_convergence = 2.0; if (argParser.isSet("convergence", argVal)) { SIR_convergence = atof(argVal.c_str()); } bool useDB = false; std::string optimizationFile = ""; if (argParser.isSet("usedb")) { std::cout << "setting useDB to true" << std::endl; useDB = true; } else if (argParser.isSet("optfile", argVal)) { optimizationFile = argVal; } if (optimizationFile == "") { log.error("Need an optimization file! Please use the --optfile=<FILENAME> option to specify the opt file."); exit(1); } //peek into optfile or take a commandline argument and change this appropriately map<string, map<string, string>> optParamsMap; readOptimizationFile(optimizationFile, optParamsMap); opt_params optParams; optParams.readParams(optParamsMap); log.debug("job type: ", optParamsMap["job_type"]["rval"]); if (optParamsMap["job_type"]["rval"] != "") { string job_received = optParamsMap["job_type"]["rval"]; JOB_TYPE job_type; if (job_received == "lsm") job_type = SIMPLE_LSM_JOB; else if (job_received == "gpu_plume") job_type = GPU_PLUME_JOB; else { log.error("Unrecognized job, exiting"); exit(1); } populationGenerator popgen(optParams.minValues, optParams.maxValues, optParams.stepValues, optParams.setValues); population pop = popgen.generate_all_pop(); //check if population is generated correctly //distribute work to clients assuming they are homogeneous int population_size = pop.size(); int required_servants = total_servants; if (total_servants > population_size) { log.debug("Excess servants, required only " , population_size , "servants"); required_servants = population_size; } int each_servant_work_size = ceil((float)population_size / total_servants); log.debug("Population size: " , pop.size()); log.debug("Number of servants working: " , required_servants ); log.debug("Each servant work size " , each_servant_work_size ); int servant = 1; //send job type to all servants for (; servant <= total_servants; servant++) { world.send(servant, JOB_DATATYPE, job_type); } log.debug("Finished sending job types"); //send optimization parameters to all servants for (servant = 1; servant <= total_servants; servant++) { world.send(servant, OPT_PARAMS, optParams); } log.debug("Finished sending job objects"); //send work for each servant population subset; int next = 0; servant = 1; while ((next = pop.get_subset(next, each_servant_work_size, subset)) != -1) { log.debug(mastername, "sening work to servant:", servant); world.send(servant, POPULATION, subset); subset.clear(); world.isend(servant, EXIT); servant++; } //pop.print(); log.info(mastername, "distributed work to all servants, waiting for results"); long results_to_received = pop.size(); population results; log.debug("Expecting a total of ", pop.size()); while(results_to_received!=0){ log.debug("waiting for slaves"); mpi::status msg = world.probe(mpi::any_source, RESULTS); population temp_results; world.recv(msg.source(), RESULTS, temp_results); log.debug("received ", temp_results.size(), "from", msg.source()); results.insert( results.end(), temp_results.begin(), temp_results.end()); results_to_received -= temp_results.size(); log.debug("received ", results.size(), "results out of ", pop.size(), "until now"); } ///optimization function float min_avg_temperature = 9999; float min_temperature = 9999; vector<sample> min_avg_samples; vector<sample> min_samples; for(sample&s : results){ float temp_min_avg_temperature = s.fitness["patch_avg_temperature"]; float temp_min_temperature = s.fitness["patch_min_temperature"]; if(min_avg_temperature>=temp_min_avg_temperature){ if(min_avg_temperature>temp_min_avg_temperature) min_avg_samples.clear(); min_avg_temperature = temp_min_avg_temperature; min_avg_samples.push_back(s); } if(min_temperature>=temp_min_temperature){ if(min_temperature>temp_min_temperature) min_avg_samples.clear(); min_temperature = temp_min_temperature; min_samples.push_back(s); } } /// log.debug("sending exit signal to all clients"); for (int servant = 1; servant < world.size(); servant++) { world.send( servant, EXIT); } log.debug("sent exit signal to all clients"); log.info("min average samples"); for(sample& s: min_avg_samples){ log.debug(s); } log.info("min samples"); //for(sample& s: min_samples){ // log.debug(s); //} } else { log.error("Specify job type in optimization file eg. const job_type = 'gpu_plume'"); for (int servant = 1; servant < world.size(); servant++) { world.send( servant, EXIT); } } } else { log.info(mastername, "\b's servant", world.rank(), "ready to fight"); string base_proj_innerpath = ""; JOB_TYPE job_type = INVALID_JOB; job *temp = NULL; opt_params optParams; while (true) { population pop; class mpi::status status = world.probe(MASTER, mpi::any_tag); if (status.tag() == MESSAGE_TYPE::EXIT) { log.info("Servant", world.rank(), "well served giving it rest", "Exiting"); break; } else if (status.tag() == JOB_DATATYPE) { world.recv(status.source(), JOB_DATATYPE, job_type); log.debug("Received job type", job_type); } else if (status.tag() == OPT_PARAMS) { world.recv(status.source(), OPT_PARAMS, optParams); //instantiate a job depending on job type //We wait until the optparams are available to instantiate the job if (job_type == SIMPLE_LSM_JOB) temp = new simpleLSM_job(optParams); // else if(job_type == GPU_PLUME_JOB) // temp = new gpu_plume_job(optParams); else { log.error("Unrecognized job, exiting"); exit(1); } log.debug("Received optimization parameters object"); //optParams.printOptimizationParams(); } else { char pwd[FILENAME_MAX]; getcwd(pwd, sizeof(pwd)); log.debug("Servant", world.rank(), "Current working directory", pwd); //otherwise we receive need to perform the calculations world.recv(status.source(), POPULATION, pop); log.debug(mastername, "\b's servant" , world.rank(), "received work of size:" , pop.size() ); //pop.print(); class job &job = *temp; std::string output_location; { stringstream ss; ss << "/scratch/workingDir_"; ss << world.rank(); output_location = ss.str(); ss.clear(); } if (!job.setup_environment(output_location)) { log.error("Servant", world.rank(), "Error setting up environment"); exit(EXIT_FAILURE); } else { log.debug("Servant", world.rank(), "Environment setup successful"); } if (!job.eval_population_fitness(pop)) { log.error("Servant", world.rank(), "Error evaluating sample fitness"); //exit(EXIT_FAILURE); } else { log.debug("Servant", world.rank(), "Population fitness evaluation DONE"); // for (auto &s: pop) // { // log.debug("Servant", world.rank(), s); // } world.send( MASTER, RESULTS, pop); log.debug("Servant", world.rank(), "send results to master DONE"); } } } } return 0; } #ifdef BACKUP_CODE //stdlib headers #include "iostream" //framerworks headers #include "boost/mpi/environment.hpp" #include "boost/mpi/communicator.hpp" //application headers #include "ArgumentParsing.h" #include "logger/logger.h" #include "directory.h" //using namespaces using namespace std; //frameworks namespaces namespace mpi = boost::mpi; //application namespaces using namespace sivelab; constexpr int MASTER = 0; enum MESSAGE_TYPE { BASEPROJ_INNER_PATH, POPULATION, EXIT }; int main(int argc, char *argv[]) { { int i = 0; char hostname[256]; gethostname(hostname, sizeof(hostname)); printf("PID %d on %s ready for attach\n", getpid(), hostname); fflush(stdout); while (0 == i) sleep(5); } //creating a logger logger log( INFO, "quic"); //initializing mpi environment mpi::environment env; mpi::communicator world; int total_servants = world.size() - 1; //excluding master //total_servants = 1;//REOMVE THIS if (total_servants < 1) { log.error("Need atleast 2 nodes"); exit(EXIT_FAILURE); } const string mastername = "<NAME>"; ArgumentParsing argParser; argParser.reg("version", 'v', no_argument); argParser.reg("solver", 's', required_argument); argParser.reg("numsamples", 'n', required_argument); argParser.reg("sigma", 'q', required_argument); argParser.reg("convergence", 'c', required_argument); argParser.reg("optfile", 'o', required_argument);//fix this it is not erring out when an optimization file is not given argParser.reg("usedb", 'd', no_argument); argParser.reg("loglevel", 'l', required_argument); argParser.processCommandLineArgs(argc, argv); //setting log level string printinfo = "info"; if (argParser.isSet("loglevel", printinfo)) { if (printinfo == "debug") log.set_log_level(DEBUG); else if (printinfo == "info") log.set_log_level(INFO); else if (printinfo == "error") log.set_log_level(ERROR); else if (printinfo == "all") log.set_log_level(ALL); log.debug("log level set to:", printinfo); } std::string output_location; { stringstream ss; ss << "/scratch/workingDir_"; ss << world.rank(); output_location = ss.str(); ss.clear(); } if (world.rank() == MASTER) { log.info("Master(", "\b" + mastername, "\b) node started"); log.info("Total no of servants: " , total_servants); if (argParser.isSet("version")) { std::cout << "plumeOptimization: version 0.0.1" << std::endl; } std::string argVal = ""; bool use_BruteForceSolver = false; if (argParser.isSet("solver", argVal)) { if (argVal == "bruteforce" || argVal == "BruteForce" || argVal == "brute") use_BruteForceSolver = true; } int SIR_numSamples = 5; if (argParser.isSet("numsamples", argVal)) { SIR_numSamples = atoi(argVal.c_str()); } float SIR_initialSigma = 2.25; if (argParser.isSet("sigma", argVal)) { SIR_initialSigma = atof(argVal.c_str()); } float SIR_convergence = 2.0; if (argParser.isSet("convergence", argVal)) { SIR_convergence = atof(argVal.c_str()); } bool useDB = false; std::string optimizationFile = ""; if (argParser.isSet("usedb")) { std::cout << "setting useDB to true" << std::endl; useDB = true; } else if (argParser.isSet("optfile", argVal)) { optimizationFile = argVal; } if (optimizationFile == "") { log.error("Need an optimization file! Please use the --optfile=<FILENAME> option to specify the opt file."); exit(1); } class master master; population pop = master.get_population(optimizationFile); //distribute work to clients assuming they are homogeneous int population_size = pop.size(); int required_servants = total_servants; if (total_servants > population_size) { log.debug("Excess servants, required only " , population_size , "servants"); required_servants = population_size; } int each_servant_work_size = population_size / total_servants; log.debug("Population size: " , pop.size()); log.debug("Number of servants working: " , required_servants ); log.debug("Each servant work size " , each_servant_work_size ); int servant = 1; for (; servant <= total_servants; servant++) { world.isend(servant, BASEPROJ_INNER_PATH, master.BASEPROJ_INNER_PATH); log.debug("Sending base proj inner path to servant ", servant); } //send work for each servant population subset; int next = 0; servant = 1; while ((next = pop.get_subset(next, each_servant_work_size, subset)) != -1) { world.isend(servant, POPULATION, subset); log.debug(mastername, "sent work to servant:", servant); subset.clear(); world.isend(servant, EXIT); servant++; } //pop.print(); log.info(mastername, "distributed work to all servants, waiting for results"); } else { log.info(mastername, "\b's servant", world.rank(), "ready to fight"); string base_proj_innerpath = ""; while (true) { population pop; class mpi::status status = world.probe(MASTER, mpi::any_tag); if (status.tag() == EXIT) { log.info("Servant", world.rank(), " well served giving it rest", "Exiting"); break; } else if (status.tag() == BASEPROJ_INNER_PATH) { world.recv(status.source(), BASEPROJ_INNER_PATH, base_proj_innerpath); log.debug("Setting base proj inner path to", base_proj_innerpath); } else { char pwd[FILENAME_MAX]; getcwd(pwd, sizeof(pwd)); log.debug("Current working directory", pwd); //otherwise we receive population subset need to perform the calculations world.recv(status.source(), POPULATION, pop); log.debug(mastername, "\b's servant" , world.rank(), "received work of size: " , pop.size() ); //pop.print(); //fetch the project first it may not be available on the machine running a servent //make the following code cross platform //system("scp ") log.debug("Base proj inner path", base_proj_innerpath); //make the following code cross platform if (base_proj_innerpath.compare("") != 0) { sivelab::QUICProject quqpData; ///this is the Project file that holds all the quic Data std::string quicFilesPath = base_proj_innerpath + "/"; quqpData.initialize_quicProjecPath(quicFilesPath); quqpData.build_map(); //creating a copy of default/origional quic project files //mpi might create different processes on same machine so to avoid conflict make dirs with its rank log.debug("creating local copy of project"); log.debug("creating output location", output_location.c_str()); mkdir(output_location.c_str(), S_IRUSR | S_IWUSR | S_IXUSR); log.debug("creating local base copy", (output_location + "/localBaseCopy").c_str()); mkdir((output_location + "/localBaseCopy").c_str(), S_IRUSR | S_IWUSR | S_IXUSR); std::string projFileName = master::searchForPROJFile(base_proj_innerpath + "/.."); log.debug("copying proj file: from ", quicFilesPath + "../" + projFileName, "to", output_location + "/localBaseCopy/local.proj"); master::copyFile(quicFilesPath + "../" + projFileName, output_location + "/localBaseCopy/local.proj"); log.debug("creating local inner dir", (output_location + "/localBaseCopy/local_inner").c_str()); mkdir((output_location + "/localBaseCopy/local_inner").c_str(), S_IRUSR | S_IWUSR | S_IXUSR); ///copy all files to the local thingy . //bruteforce but later on replace quicProject std::string local_inner = output_location + "/localBaseCopy/local_inner"; log.debug("Local inner path", local_inner); quqpData.quBuildingData.writeQUICFile(local_inner + "/QU_buildings.inp"); master::copyFile(quicFilesPath + "QU_fileoptions.inp", local_inner + "/QU_fileoptions.inp"); master::copyFile(quicFilesPath + "QU_landuse.inp", local_inner + "/QU_landuse.inp"); quqpData.quMetParamData.writeQUICFile(local_inner + "/QU_metparams.inp"); quqpData.quSimParamData.writeQUICFile(local_inner + "/QU_simparams.inp"); quqpData.quMetParamData.quSensorData.writeQUICFile(local_inner + "/sensor1.inp"); master::copyFile(quicFilesPath + projFileName.substr(0, projFileName.length() - 5) + ".info", local_inner + "/local.info"); master::copyFile(quicFilesPath + "QP_materials.inp", local_inner + "/QP_materials.inp"); master::copyFile(quicFilesPath + "QP_indoor.inp", local_inner + "/QP_indoor.inp"); quqpData.qpSourceData.writeQUICFile(local_inner + "/QP_source.inp"); master::copyFile(quicFilesPath + "QP_fileoptions.inp", local_inner + "/QP_fileoptions.inp"); quqpData.qpParamData.writeQUICFile(local_inner + "/QP_params.inp"); quqpData.qpBuildoutData.writeQUICFile(local_inner + "/QP_buildout.inp"); ////////////////////////////////TODO TODO important ask if needed master::copyFile(quicFilesPath + "QP_particlesize.inp", local_inner + "/QP_particlesize.inp"); // Landuse file ///at this point copy all files // std::cerr<<"The values should have changed by now "<<std::endl; base_proj_innerpath = local_inner; log.debug("searching new local proj file", base_proj_innerpath + "/.."); projFileName = master::searchForPROJFile(base_proj_innerpath + "/.."); ///as the filename will change the path std::cerr << "the new BASE project is :" << base_proj_innerpath << std::endl; //workDir.intialRun("/tmp/workingDir",quicFilesPath,quqpData,projFileName); //for each sample in the population create a copy of quic project files to work on and change the appropriate values accroding to the sample //creating a copy of quic project files with optimized values workDir.intialRun(output_location + "/optimizingDir", output_location + "/localBaseCopy/local_inner/", quqpData, "local.proj"); } else { log.error("Need base proj inner path"); } } } } return 0; } #endif <file_sep>/src/utils/include/FitnessCache.h #ifndef __FITNESS_CACHE_H__ #define __FITNESS_CACHE_H__ 1 #include <vector> #include "population.h" class FitnessCache { public: struct sampleFitness { std::vector<int> sample; double fitness; }; void addToCache( const sample &s, double fitness ); bool inCache( const sample &s, double &fitness ); void clearCache(); ///added to support continous running of plumeOptimization when interface with envsim website private: std::vector<sampleFitness> m_cache; }; #endif <file_sep>/include/logger/logger.h #ifndef __LOGGER_H__ #define __LOGGER_H__ 1 #include "iostream" #include "tuple" using namespace std; namespace sivelab { typedef enum { ALL, DEBUG, INFO, ERROR } LOG_LEVEL; class logger { private: string class_name; LOG_LEVEL log_level; template <class T, class... Tail> void print(T head, Tail... tail) const { cout << head << " "; print(std::forward<Tail>(tail)...); } void print() const { cout << endl; } public: logger():log_level(INFO), class_name("Anonymous"){} logger(LOG_LEVEL log_level_, string class_name_): log_level(log_level_), class_name(class_name_) { } ~logger() {} template <class... Args> void error(Args... args) const { if (log_level <= LOG_LEVEL::ERROR) { print ("ERROR\t", class_name + ":", args ...); } } template <class... Args> void info(Args... args) const { if (log_level <= LOG_LEVEL::INFO) { print ("INFO\t", class_name + ":", args ...); } } template <class... Args> void debug(Args... args) const { if (log_level <= LOG_LEVEL::DEBUG) { print ("DEBUG\t", class_name + ":", args ...); } } void set_log_level(LOG_LEVEL log_level_) { log_level = log_level_; } }; } #endif <file_sep>/tests/MPI_framework/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project (optimizationCode) #job class test #Add test cpp file add_executable( test_job test_job.cpp ) #Link test executable against gtest & gtest_main target_link_libraries( test_job mpi_framework optm-utils ) target_link_libraries( test_job gtest gtest_main) target_link_libraries( test_job sive-quicutil) target_link_libraries( test_job sive-util) target_link_libraries( test_job QESLSM QESViewfactor ) target_link_libraries( test_job ${Boost_LIBRARIES}) add_test( NAME JobTest WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/bin COMMAND test_job) add_custom_command(TARGET test_job PRE_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/2by2_q572_270 ${CMAKE_BINARY_DIR}/resources/2by2_q572_270)<file_sep>/src/utils/ArgumentParsing.cpp /* * ArgumentParsing.cpp * NETCODE * * Created by <NAME> on 10/6/09. * Copyright 2009 Department of Computer Science, University of Minnesota-Duluth. All rights reserved. * */ #include "utils/ArgumentParsing.h" ArgumentParser::ArgumentParser() { } ArgumentParser::ArgumentParser(int argc, char *argv[]) { process(argc, argv); } ArgumentParser::~ArgumentParser() { } void ArgumentParser::reg(const std::string& argName, char shortArgName, int has_argument, bool required) { ModifiedOption nextArg; // the option structure uses C-style character strings so get our "string" into that form. nextArg.optParams.name = (const char *)malloc(argName.length() + 1); strcpy((char *)nextArg.optParams.name, argName.c_str()); nextArg.optParams.has_arg = has_argument; nextArg.optParams.flag = 0; nextArg.optParams.val = shortArgName; nextArg.isSet = false; nextArg.optionalArgument = ""; m_ArgVector.push_back(nextArg); } bool ArgumentParser::isSet(const std::string& argName) { for (unsigned int i=0; i<m_ArgVector.size(); ++i) { if (argName.compare(m_ArgVector[i].optParams.name) == 0) return m_ArgVector[i].isSet; } return false; } bool ArgumentParser::isSet(const std::string& argName, std::string &argValue) { for (unsigned int i=0; i<m_ArgVector.size(); ++i) if ((argName.compare(m_ArgVector[i].optParams.name) == 0) && (m_ArgVector[i].isSet)) { argValue = m_ArgVector[i].optionalArgument; return true; } argValue = ""; return false; } int ArgumentParser::process(int argc, char *argv[]) { // convert the vector into a temporary option struct needed for getopt_long option *getoptOptions = new option[m_ArgVector.size()]; for (unsigned int i=0; i<m_ArgVector.size(); ++i) { getoptOptions[i].name = (char *)malloc(strlen(m_ArgVector[i].optParams.name) + 1); strcpy((char *)getoptOptions[i].name, m_ArgVector[i].optParams.name); getoptOptions[i].has_arg = m_ArgVector[i].optParams.has_arg; getoptOptions[i].flag = m_ArgVector[i].optParams.flag; getoptOptions[i].val = m_ArgVector[i].optParams.val; } int c; while (1) { // which option index are we on? int this_option_optind = optind ? optind : 1; int option_index = 0; c = getopt_long(argc, argv, "", getoptOptions, &option_index); // when the getopt functions return a -1, there are no more // arguments to process. if (c == -1) break; int argIdx = 0; bool found = false; while (!found && argIdx < m_ArgVector.size() && c != '?') { if (c == (int)m_ArgVector[argIdx].optParams.val) { // std::cout << "found option: " << m_ArgVector[argIdx].optParams.name << std::endl; m_ArgVector[argIdx].isSet = true; if (m_ArgVector[argIdx].optParams.has_arg != no_argument) { m_ArgVector[argIdx].optionalArgument = optarg; // std::cout << "\t optarg = " << optarg << std::endl; } found = true; } argIdx++; } if (!found) { std::cerr << "?? getopt returned character code: " << c << std::endl; } } #if 0 // look over the non-option elements if (optind < argc) { printf("non-option ARGV-elements: "); while (optind < argc) printf("%s ", argv[optind++]); printf("\n"); } #endif // deallocate the memory we created to make this happen for (unsigned int i=0; i<m_ArgVector.size(); ++i) { free((char *)(getoptOptions[i].name)); } delete [] getoptOptions; return 1; } <file_sep>/fitness_lib/fitness_function.cpp #include "fitness_function.h" #include <boost/algorithm/string.hpp> using namespace std; using namespace sivelab; extern "C" Fitness* create_object(QUICProject& _quqpData, opt_params& _optParams){ return new Fitness(_quqpData, _optParams); } extern "C" void destroy_object(Fitness* object){ delete object; } Fitness::Fitness(QUICProject& _quqpData, opt_params& _optParams):quqpData(_quqpData), optParams(_optParams){} void Fitness::fetchPatchIds(qes::QESContext* context){ if(patchIDs.size()==0){ float nx = quqpData.nx; float ny = quqpData.ny; float dx = quqpData.dx; float dy = quqpData.dy; //somehow fetch these from optparams //Nope they will be given by the person who writes this file! float left = 30; float bottom = 25; float right = 40; float top = 35; // cout<<nx<<" "<<ny<<" "<<dx<<" "<<dy<<endl; if(dx<=0 || dy<=0) return; //Change real world cooredinates to quic world coordinates top /= dy; bottom /= dy; left /= dx; right /= dx; if(top<bottom || right<left || bottom<0 || left<0 || top>ny || right>nx) return ; //pull the points to the middle of each cell/patch //fix the bug for sinle stripe bounding box 1 x n or n x 1 left = 0.5 + floor(left); right = 0.5 + floor(right); top = 0.5 + floor(top); bottom = 0.5 + floor(bottom); cout<<"left: "<<left<<" bottom: "<<bottom<<" right:"<<right<<" top:"<<top<<endl; for(float i=left; i<right; i++) for(float j= bottom; j<top; j++){ float3 point = make_float3( i, j, 0.f ); int patch_id = qes::QESUtils::getNearestPatch( point, context->getSceneTracker() ); patchIDs.push_back(patch_id); } } } void Fitness::fetchBuffers(qes::QESContext* context){ qes::BufferTracker *g_buffTracker = context->getBufferTracker(); qes::SceneTracker *g_sceneTracker = context->getSceneTracker(); PatchMap *g_patchData = g_sceneTracker->getPatchData(); //fetch this from opt params //string buffers_names_str = optParams["buffers_names"]; string buffers_names_str="patch_temperature"; std::vector<std::string> buffers_names; boost::split(buffers_names, buffers_names_str, boost::is_any_of(":")); for(auto& buffer_name : buffers_names){ if(buffer_name == "patch_temperature"){ std::vector<float> temperature; g_buffTracker->getBuffer<float>( buffer_name, &temperature ); buffers[buffer_name] = temperature; } } } bool Fitness::eval_fitness(sample& s, qes::QESContext* context){ fetchPatchIds(context); fetchBuffers(context); //change this such that multiple fitness functions are executed here float avgTemperature = 0; float minTemperature = 9999; int minPatchID=-1; string query = "patch_temperature"; for(auto patchID: patchIDs){ float temp = buffers[query][patchID]; avgTemperature += temp; if(minTemperature > temp) minTemperature = temp; } cout<<"done calculating average temperature for "<<patchIDs.size()<<" patches"<<endl; s.fitness["patch_avg_temperature"] = avgTemperature/patchIDs.size(); s.fitness["patch_min_temperature"] = minTemperature; return true; } <file_sep>/src/opt_grammar/OptFileGrammar_interpreter.cpp #include <iostream> #include "fstream" #include "OptFileGrammarLexer.hpp" #include "OptFileGrammarParser.hpp" constexpr bool RUN_AS_INTERPRETER = false; int main() { OptFileGrammarLexer::InputStreamType input((ANTLR_UINT8 *) "", ANTLR_ENC_8BIT, 0, (ANTLR_UINT8 *) "userinput"); std::string inputLine; ifstream fin("optTest8D.opt", std::ifstream::in); istream *input_stream = &fin; if (RUN_AS_INTERPRETER) { input_stream = &std::cin; //std::cout << "Rias> "; } long line_number = 1; while (getline(*input_stream, inputLine)) { trim(inputLine); if (inputLine.size() != 0) { input.reuse((ANTLR_UINT8 *) inputLine.c_str(), inputLine.length(), (ANTLR_UINT8 *) "userinput"); OptFileGrammarLexer lexer(&input); OptFileGrammarParser::TokenStreamType token_stream(ANTLR_SIZE_HINT, lexer.get_tokSource()); OptFileGrammarParser parser(&token_stream); parser.unit(); if (lexer.error_in_lexer | parser.error_in_parser) { cout << "At line " << line_number<<endl<<endl; } else { //std::cout << "Parsing line: " << inputLine << endl; //std::cout << "Extracted info:" << std::endl; for (auto &itr : parser.each_line) { //std::cout << itr.first << " : " << itr.second << ", " << endl; } //std::cout << std::endl; } } if (RUN_AS_INTERPRETER) { //std::cout << "Rias>"; } line_number++; } }<file_sep>/src/mpi_qes_spf/include/simpleLSM_job.h #ifndef __SIMPLE_LSM__ #define __SIMPLE_LSM__ 1 #include "logger/logger.h" #include "MPI_framework/job.h" #include "utils/population.h" #include "util/handleQUICArgs.h" #include "quicutil/QUICProject.h" #include "ViewTracer.h" #include "QESContext.h" #include "SimpleLSM.h" namespace sivelab { class simpleLSM_job: public job{ private: logger log; public: simpleLSM_job(const opt_params &optParams_): job(optParams_), log(DEBUG, "simpleLSM_job") {} ~simpleLSM_job(){} bool eval_population_fitness( population &pop ); bool eval_sample_fitness( sample &s); bool loadScene( qes::QESContext *context ); void runDiurnalCycle( qes::QESContext *context ); }; } #endif <file_sep>/src/utils/population.cpp #include <math.h> #include <list> #include <cstdlib> #include <vector> #include <iostream> #include <ostream> #include "utils/population.h" using namespace std; // Helper function to generate a sample from a 1D gaussian distribution with // standard deviation sigma double ran_gaussian (const double sigma) { double x, y, r2; do { /* choose x,y in uniform square (-1,-1) to (+1,+1) */ // x = -1 + 2 * (rand() / (double)RAND_MAX); // y = -1 + 2 * (rand() / (double)RAND_MAX); // drand48 versions x = -1 + 2 * drand48(); y = -1 + 2 * drand48(); /* see if it is in the unit circle */ r2 = x * x + y * y; } while (r2 > 1.0 || r2 == 0); /* Box-Muller transform */ return sigma * y * sqrt (-2.0 * log (r2) / r2); } #if 0 // local helpers for drawing to an opengl window void BeginDraw() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-1, 1, -1, 1, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void EndDraw() { glFlush(); glutSwapBuffers(); } #endif pt::pt() { ; } pt::pt(int dimension) { resize( dimension ); } pt::pt( double x ) { resize( 1 ); (*this)[0] = x; } pt::pt( double x, double y ) { resize( 2 ); (*this)[0] = x; (*this)[1] = y; } pt::pt( double x, double y, double z ) { resize( 3 ); (*this)[0] = x; (*this)[1] = y; (*this)[2] = z; } pt::pt( vector< double > &in ) { resize(in.size() ); for (unsigned int i = 0; i < size(); i++ ) (*this)[i] = in[i]; } pt::~pt() { } pt pt::operator+(const pt &p) { pt t(*this); for (unsigned int i = 0; i < size(); i++ ) t[i] += p[i]; return t; } pt pt::operator-(const pt &p) { pt t(*this); for (unsigned int i = 0; i < size(); i++ ) t[i] -= p[i]; return t; } pt pt::operator*(const double &scalar) { pt t(*this); for (unsigned int i = 0; i < size(); i++ ) t[i] *= scalar; return t; } pt pt::operator/(const double &scalar) { pt t(*this); for (unsigned int i = 0; i < size(); i++ ) t[i] /= scalar; return t; } ostream &operator<<( ostream &os, pt &s ) { os << "pt coord: "; for (unsigned int i = 0; i < s.size() - 1; i++ ) os << s[i] << ", "; if ( s.size() > 0 ) os << s[s.size() - 1]; } sample::sample() { } sample::sample(int dimension) { (*this).resize( dimension ); } sample::sample( pt &in ) { resize(in.size() ); for (unsigned int i = 0; i < size(); i++ ) (*this)[i] = in[i]; } sample::~sample() { } double sample::eval_sample( double (*eval_func)( sample &s ) ) { //this->fitness = eval_func(*this); } ostream &operator<<( ostream &os, sample &s ) { os << "{"; os << " coord: "; for (unsigned int i = 0; i < s.size(); i++ ) os << s[i] << ", "; if ( s.size() > 0 ) for(auto& entry: s.fitness){ os<<entry.first<<": "<<entry.second<<", "; } os << "}"; } population & population::operator=( const population &source ) { this->resize( source.size() ); dimension = source.dimension; for (unsigned int i = 0; i < source.size(); i++ ) { (*this)[i].resize(dimension); (*this)[i] = source[i]; } return *this; } population::population(double pop[], int no_of_samples , int dimensions) { log = logger(DEBUG, "population"); unsigned int array_index = 0; this->resize(no_of_samples); for (unsigned int i = 0; i < no_of_samples; i++) { (*this)[i].resize( dimensions); for (unsigned int j = 0; j < dimensions; j++) (*this)[i].at(j) = pop[array_index++]; } std::cout << "trying to create a population using an array " << std::endl; dimension = dimensions; //forgot this } population::population( int pop_size, int dimension_ ) { log = logger(DEBUG, "population"); this->resize( pop_size ); for (unsigned int i = 0; i < pop_size; i++ ) (*this)[i].resize( dimension_ ); dimension = dimension_; } void population::eval_population_fitness( double (*eval_func)( sample &s ) ) { for (unsigned int i = 0; i < size(); i++ ) (*this)[i].eval_sample( eval_func ); } void population::randomize_samples( vector< double > &domain_min, vector< double > &domain_max ) { for (unsigned int i = 0; i < size(); i++ ) for ( unsigned int d = 0; d < domain_min.size(); d++ ) (* this)[i][d] = drand48() * (domain_max[d] - domain_min[d]) + domain_min[d]; } double population::sum_fitnesses() { // double sum = 0.0; // for (unsigned int i = 0; i < size(); i++ ) // sum += (*this)[i].fitness; // return sum; } void population::print() { std::cout << "population size: " << size() << " sample dimension: " << dimension << endl; for (unsigned int i = 0; i < size(); i++ ) std::cout << i << ": " << (*this)[i] << endl; std::cout << "--------------------" << endl; } #if 0 void population::draw_population() { BeginDraw(); glDisable(GL_LIGHTING); glPointSize(5.1); glColor3d( 0.0, 1.0, 0.0); glBegin( GL_POINTS ); double pt[3]; for (unsigned int i = 0; i < size(); i++ ) { pt[0] = (*this)[i][0]; pt[1] = (*this)[i][1]; pt[2] = 0.0; glVertex3dv( pt ); printf("drew %f %f\n", pt[0], pt[1]); } glEnd(); glPointSize(1); glEnable(GL_LIGHTING); EndDraw(); } #endif ostream &operator<<( ostream &os, population &p ) { os << "population size: " << p.size() << " sample dimension: " << p.dimension << endl; for (unsigned int i = 0; i < p.size(); i++ ) os << i << ": " << p[i] << endl; os << "--------------------" << endl; } /** * returns the sample number that will be the first sample in the next subset */ int population::get_subset(int start_pos, int size, population &pop) { if (start_pos >= this->size()) return -1; vector<sample>::const_iterator begin = this->begin() + start_pos; vector<sample>::const_iterator end; if (start_pos + size >= this->size()) end = this->end(); else end = this->begin() + start_pos + size; while (begin < end) { pop.push_back(*begin); log.debug(*begin); ++begin; } return end - (this->begin()); }<file_sep>/src/mpi_gpuplume/include/gpu_plume_job.h #ifndef __GPU_PLUME_JOB__ #define __GPU_PLUME_JOB__ 1 #include "boost/serialization/string.hpp" #include "boost/serialization/vector.hpp" #include "logger/logger.h" #include "MPI_framework/job.h" #include "utils/namedOptParam.h" #include "utils/dependencyOptParam.h" #include "utils/population.h" #include "utils/FitnessCache.h" #include "utils/solver.h" using namespace sivelab; namespace sivelab { class gpu_plume_job: public job { private: bool readNumParticleSet(const char *line, std::vector<int> &npSet); bool readTimeStepSet(const char *line, std::vector<float> &tsSet); bool removeCommentLines( char *buf ); bool isNumeric(std::string value); void readPreferencesFile(); bool read1String(const char *line, const char *settingName, std::string *s); logger log; // std::string populationFile; // std::string fitness_function; // population filePopulation ; FitnessCache cache; int remove_me = 0; string QUICURB_EXE_PATH; string QUICPLUME_EXE_PATH; bool environment_ready = false; public: ~gpu_plume_job() {} //gpu_plume_job() {} gpu_plume_job(const opt_params &optParams_): job(optParams_), log(DEBUG, "gpu_plume_job") {} bool eval_population_fitness( population &pop ); //TODO: resurrect this when needed // bool eval_sample_fitness( sample &s ); }; } #endif<file_sep>/tests/opt_grammar/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project (optimizationCode) #Add test cpp file add_executable( test_optGrammarTest test_opt_grammar.cpp ) #Link test executable against gtest & gtest_main target_link_libraries( test_optGrammarTest gtest gtest_main optfileparser) add_test( NAME optGrammarTest WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/bin COMMAND test_optGrammarTest) <file_sep>/src/utils/population_gen.cpp #include "utils/population_gen.h" #include <algorithm> populationGenerator::populationGenerator(population full_pop_) { entire_pop = full_pop_; } populationGenerator::populationGenerator(vector <double> min_domain_ , vector<double> max_domain_ , vector<int> steps_, vector <vector<double > > setvalues_) { log = logger(ERROR, "populationGenerator"); log.debug("ENTERD THE POPULATION GENERATOR CONSTRUCTOR"); min_domain = min_domain_; max_domain = max_domain_; steps = steps_; // setvalues = setValues; //copying the setValues over //setValues.resize(setvalues_.size()); for (unsigned int i = 0; i < setvalues_.size(); i++ ) { setValues.push_back(setvalues_[i]); } dimensions = min_domain.size() + setValues.size(); log.debug("done copying set values"); // Create the population based on the above info int num_samples = 1; //std::cout<<"size of domain"<<min_domain.size()<<"cout the size of steps"<<steps.size(); for ( unsigned int i = 0; i < min_domain.size(); i++ ){ long temp = (long)((max_domain[i] - min_domain[i]) / steps[i]) + 1; num_samples = num_samples * temp; } for ( unsigned int i = 0; i < setValues.size(); i++ ) num_samples = num_samples * setValues.at(i).size(); log.debug("calculated no of samples: ", num_samples); total_population_size = num_samples; ///total numbe of possible samples //std::cout<<"trying to get the whole pop"<<std::endl; // entire_pop = generate_entire_pop(); /*for(unsigned int j=0 ; j< entire_pop.size();j++) { for(unsigned int i =0; i<entire_pop.at(j).size();i++) std::cout<<entire_pop.at(j).at(i)<<"\t"; std::cout<<std::endl; }*/ //std::cout<<"am i done "<<std::endl; // std::cout<<"total number of samples "<<total_populationSize<<std::endl; } ///need min max and set values and step values as params population populationGenerator::generate_all_pop() { log.debug("In the funciton generate_all_pop"); if (entire_pop.size() == 0) entire_pop = generate_entire_pop(); return entire_pop; } population populationGenerator::generate_fromfile(std::string fileName, std::vector <namedOptParam> &rangeMap) { population newpop; int dimensions; int populationSize; int linemax = 1024; char *linebuf = new char[linemax]; std::string line; std::stringstream ss(line, std::stringstream::in | std::stringstream::out); std::string variable_name; ///read from the file ///file format : //// line1 :! size of population ////line2 : ! size of sample //line 3 : parameter names seperated by space or tab ///line 4 : start of populations //opening the file first std::ifstream pop_file(fileName.c_str()); if (pop_file.is_open() == false) { std::cerr << " Error opening file \"" << fileName << "\". Exiting ." << std::endl; exit(1); } std::cerr << "file opened " << std::endl; getline(pop_file, line); ///the first line should be size of population ss.str(line); ss >> populationSize; getline(pop_file, line); ss.str(line); ss >> dimensions; getline(pop_file, line); ss.str(line); while (ss >> variable_name) { namedOptParam np; np.description = variable_name; np.idx = 12345; np.type = "rangeValue"; rangeMap.push_back(np); std::cerr << "varaible nam " << variable_name; } std::cout << "the size of rangeMap" << rangeMap.size(); if (rangeMap.size() != dimensions) { std::cerr << "The number of dimensions and the number of parameters specified are wrong " << std::endl; std::cerr << "Exiting" << std::endl; exit(1); } sample s(dimensions); for (unsigned int i = 0; i < populationSize; i++) { getline(pop_file, line); ss.flush(); ss.clear(); ss.str(line); for (unsigned int j = 0; j < dimensions; j++) { ss >> s.at(j); } ss.flush(); ss.clear(); newpop.push_back(s); } std::cout << "Done reading the population " << std::endl; std: cout << newpop << std::endl; //now to read in the required parameters newpop.dimension = dimensions; return newpop; } population populationGenerator::generate_entire_pop() { if ((min_domain.size() + setValues.size()) == 0) { log.error("withing populationGenerator the proper constructor has not been called so cannot generate_Entire_pop"); exit(1); } log.debug("In genereate_entire_pop"); //calculating the lenght of the sample ///contemplate on how the array or the population is going to be passed in or out of this as if we send reference it would create problems . ////array will have copy constructor checka and see if population has one or else write one or do something ///calling it samples //creating a dummy sample population samples(total_population_size, dimensions); int samplenum = 0; sample s(dimensions); unsigned int i; //setting all values to a min for ( i = 0; i < min_domain.size(); i++ ) ////setting the sample with minimum data s[i] = min_domain[i]; for ( ; i < dimensions; i++) s[i] = setValues.at(i - min_domain.size()).at(0); log.debug("Created intial sample of dimensions ", dimensions); // std::cout<<"Done with min sample"<<std::endl; bool done = false; while (!done) { // cout <<"samplenumber: "<< samplenum+1 << endl; // cout <<"sample :"<< s << endl; //if(samplenum==1) // exit(1); samples[samplenum] = s; int dim_inc = 0; bool done_incrementing = false; // std::cout<<"the size of the domain:"<<min_domain.size()<<std::endl; while (!done_incrementing ) { // std::cout<<"only once dim number"<<dim_inc<<":"<<std::endl; // std::cout<<"before condition checks the if condition is :"<<(dim_inc<min_domain.size())<<std::endl; if (dim_inc < min_domain.size()) { // std::cout<<"should have reached here"<<std::endl; s[dim_inc] += steps[dim_inc]; //( max_domain[dim_inc] - min_domain[dim_inc] ) / (steps[dim_inc] - 1); if ( s[dim_inc] <= max_domain[dim_inc] ) { done_incrementing = true; // std::cout<<"here too"<<std::endl; // std::cout<<"the value of sample"<<s[dim_inc]<<std::endl; } else { s[dim_inc] = min_domain[dim_inc]; dim_inc++; // std::cout<<"*****************"<<dim_inc<<"*********"<<std::endl <<"this should be zero "<<done_incrementing<<std::endl; } } else { // std::cout<<"**fffffffffffffff******************************************************************f*******"<<std::endl; std::vector<double>::iterator it; std::vector<double> temp_setValue; temp_setValue = setValues.at(dim_inc - min_domain.size()); it = find(temp_setValue.begin(), temp_setValue.end(), s[dim_inc]); int index = it - temp_setValue.begin(); //it=find(setValues.at(dim_inc-min_domain.size()).begin(),setValues.at(dim_inc-min_domain.size()).end(),101);//s[dim_inc]); // int index = it - setValues.at(dim_inc - min_domain.size()).begin(); if (it == temp_setValue.end()) { std::cout << "value not found" << std::endl; ////Trash condition check } if (index == temp_setValue.size() - 1) { //std::cout<<"at the last value do reset"<<std::endl; s[dim_inc] = temp_setValue.at(0); dim_inc++; } else { s[dim_inc] = temp_setValue.at(index + 1); done_incrementing = true; } // std::cout<<"Reached the point i want the index is :"<<index <<std::endl; } //std::cout<<"next point and status of done_incrementing:"<<done_incrementing<<":sample number"<<samplenum<<":sample"<<s<<std::endl; if ( dim_inc > min_domain.size() + setValues.size() - 1 ) { //std::cout<<"***************************************************"<<std::endl; done_incrementing = true; done = true; } } //std::cout<<"sample number incremented"<<std::endl; samplenum++; } log.debug("Population generated"); return samples; } population populationGenerator::generate_random_pop(int number) { if ((min_domain.size() + setValues.size()) == 0) { std::cerr << "withing populationGenerator the proper constructor has not been called so cannot generate_Entire_pop" << std::endl; exit(1); } //////copuld yuse this \\if(std::find(dataStructureNames.begin(),dataStructureNames.end(),dataStructureName)==dataStructureNames.end()) ///// use drand48 to generate ///// if (number > total_population_size) { std::cout << "we cannont get more than the possible combinations" << std::endl; exit(1); } std::cout << "entered random generator" << std::endl; population random_pop(number, dimensions); sample random_sample(dimensions); double random_number; int random_pop_index = 0; while (random_pop_index < number) { //std::cout<<"value of i"<<i<<std::endl; for (unsigned int j = 0; j < dimensions ; j++) { //std::cout<<"value of j"<<j<<std::endl; //two ways if the dimension is a range values //// setValues if (j < min_domain.size()) //generate a random { random_number = (drand48() * (max_domain.at(j) - min_domain.at(j) + 1) + min_domain.at(j)); // std::cout<<"random nuber"<<random_number<<std::endl; random_sample.at(j) = normalize_value(random_number, j); } else ///generate a random set value { random_number = (drand48() * (setValues.at(j - min_domain.size()).size())); random_sample.at(j) = setValues.at(j).at(random_number); } } if (std::find(random_pop.begin(), random_pop.end(), random_sample) == random_pop.end()) { //std::cout<<"new sample"<<std::endl; //std::cout<<random_sample<<std::endl; random_pop.at(random_pop_index++) = random_sample; } } ///std::cout<<"the random population "<<"=================="<<std::endl; //std::cout<<random_pop<<std::endl; return random_pop; } int populationGenerator::generate_random_array(double samples[], int number) { if (number >= total_population_size || number < 1) { std::cerr << "cannot generate the required number of unique samples " << std::endl; exit(1); } //samples = new double[length*dimensions]; population temp_rand_pop = generate_random_pop(number); int sampleindex = 0; for (unsigned int i = 0; i < temp_rand_pop.size(); i++) { for (unsigned int j = 0 ; j < temp_rand_pop.at(i).size(); j++) samples[sampleindex++] = temp_rand_pop.at(i).at(j); } return number * dimensions; }; population populationGenerator::generate_random_pop_usingentire(int length) { if (length >= total_population_size || length < 1) { std::cerr << "cannot generate the required number of unique samples " << std::endl; exit(1); } population temp_pop = entire_pop; population new_rand_pop; int random ; for (unsigned int i = 0; i < length; i++) { random = round(drand48() * (temp_pop.size() - 1)); //std::cout<<"\n"<<"random index:"<<random<<"\n"; new_rand_pop.push_back(temp_pop.at(random)); temp_pop.erase(temp_pop.begin() + random); } return new_rand_pop; /*std::cout<<"-------____THE RANDOM POPULATION IS ___________----"<<std::endl; for(unsigned int j=0 ; j< new_rand_pop.size();j++) { for(unsigned int i =0; i<new_rand_pop.at(j).size();i++) std::cout<<new_rand_pop.at(j).at(i)<<"\t"; std::cout<<std::endl; } */ ///TO generate random population ///todo generate a random sample random and then compare the sample with the already generated samples to see if it matches ///generating for range values is easy /// (unsigned int i = 0; i < size(); i++ ) // for ( unsigned int d = 0; d < domain_min.size(); d++ ) // (* this)[i][d] = drand48() * (domain_max[d] - domain_min[d]) + domain_min[d]; ///generating for a set of values to see how to do it } int populationGenerator::generate_random_array_usingentire(double samples [], int length) { if (length >= total_population_size || length < 1) { std::cerr << "cannot generate the required number of unique samples " << std::endl; exit(1); } //samples = new double[length*dimensions]; population temp_rand_pop = generate_random_pop_usingentire(length); int sampleindex = 0; for (unsigned int i = 0; i < temp_rand_pop.size(); i++) { for (unsigned int j = 0 ; j < temp_rand_pop.at(i).size(); j++) samples[sampleindex++] = temp_rand_pop.at(i).at(j); } return length * dimensions; } int populationGenerator::generate_all_array(double samples[]) //double *&samples) { //samples =new double[total_population_size*dimensions]; int sampleindex = 0; for (unsigned int i = 0; i < entire_pop.size(); i++) { for (unsigned int j = 0 ; j < entire_pop.at(i).size(); j++) samples[sampleindex++] = entire_pop.at(i).at(j); } return dimensions * total_population_size; } int populationGenerator::generate_entire_array(double *&samples) { if ((min_domain.size() + setValues.size()) == 0) { std::cerr << "withing populationGenerator the proper constructor has not been called so cannot generate_Entire_pop" << std::endl; exit(1); } samples = new double[total_population_size * dimensions]; //double samples[total_population_size*dimensions]; ///hopefully the whole array size int samples_index = 0; int samplenum = 0; double s[dimensions]; unsigned int i; //setting all values to a min for ( i = 0; i < min_domain.size(); i++ ) ////TODO: all single values could be set here and never changed s[i] = min_domain[i]; for ( ; i < dimensions; i++) s[i] = setValues.at(i - min_domain.size()).at(0); //making sure that the initial sample is not overwritten std::cout << "Done with min sample am i here ?" << std::endl; bool done = false; while (!done) { cout << "samplenumber: " << samplenum + 1 << endl; // cout <<"sample :"<< s << endl; //if(samplenum==1) // exit(1); // samples[samplenum] = s; ////TODO replace this with array copy for (unsigned int temp_copy = 0; temp_copy < dimensions ; temp_copy++) samples[samples_index++] = s[temp_copy]; ///this should have copied all the values from a sample to the population int dim_inc = 0; bool done_incrementing = false; // std::cout<<"the size of the domain:"<<min_domain.size()<<std::endl; while (!done_incrementing ) { // std::cout<<"only once dim number"<<dim_inc<<":"<<std::endl; // std::cout<<"before condition checks the if condition is :"<<(dim_inc<min_domain.size())<<std::endl; if (dim_inc < min_domain.size()) { // std::cout<<"should have reached here"<<std::endl; s[dim_inc] += ( max_domain[dim_inc] - min_domain[dim_inc] ) / (steps[dim_inc] - 1); if ( s[dim_inc] <= max_domain[dim_inc] ) { done_incrementing = true; // std::cout<<"here too"<<std::endl; // std::cout<<"the value of sample"<<s[dim_inc]<<std::endl; } else { s[dim_inc] = min_domain[dim_inc]; dim_inc++; // std::cout<<"*****************"<<dim_inc<<"*********"<<std::endl <<"this should be zero "<<done_incrementing<<std::endl; } } else { // std::cout<<"**fffffffffffffff******************************************************************f*******"<<std::endl; std::vector<double>::iterator it; std::vector<double> temp_setValue; temp_setValue = setValues.at(dim_inc - min_domain.size()); it = find(temp_setValue.begin(), temp_setValue.end(), s[dim_inc]); int index = it - temp_setValue.begin(); //it=find(setValues.at(dim_inc-min_domain.size()).begin(),setValues.at(dim_inc-min_domain.size()).end(),101);//s[dim_inc]); // int index = it - setValues.at(dim_inc - min_domain.size()).begin(); if (it == temp_setValue.end()) { std::cout << "value not found" << std::endl; ////Trash condition check } if (index == temp_setValue.size() - 1) { std::cout << "at the last value do reset" << std::endl; s[dim_inc] = temp_setValue.at(0); dim_inc++; } else { s[dim_inc] = temp_setValue.at(index + 1); done_incrementing = true; } // std::cout<<"Reached the point i want the index is :"<<index <<std::endl; } //std::cout<<"next point and status of done_incrementing:"<<done_incrementing<<":sample number"<<samplenum<<":sample"<<s<<std::endl; if ( dim_inc > min_domain.size() + setValues.size() - 1 ) { //std::cout<<"***************************************************"<<std::endl; done_incrementing = true; done = true; } } //std::cout<<"sample number incremented"<<std::endl; samplenum++; } std::cout << "returned from the function " << std::endl; return total_population_size * dimensions; } double populationGenerator::normalize_value(double value, int sample_index) { if ((min_domain.size() + setValues.size()) == 0) { std::cerr << "withing populationGenerator the proper constructor has not been called so cannot generate_Entire_pop" << std::endl; exit(1); } //std::cout<<"the value submitted for normalize"<<value<<" index"<<sample_index<<std::endl; bool match = false; double low, high; if (sample_index >= dimensions) { std::cout << "There is a problem with the value passed to normalize_value withing populationGenerations" << std::endl; } else if (sample_index < min_domain.size()) { //this is a range value if (value <= min_domain.at(sample_index)) { value = min_domain.at(sample_index); } else if (value >= max_domain.at(sample_index)) { value = max_domain.at(sample_index); } else { //so the value is greater than or equal to min|max domains //currValue = min_domain.at(i); low = min_domain.at(sample_index); high = low + ( max_domain[sample_index] - min_domain[sample_index] ) / (steps[sample_index] - 1); //currValue=high; while (!(high > max_domain.at(sample_index))) { // std::cout<<"In the while loop "<<std::endl; // std::cout<<"low ="<<low<<" high "<<high<<std::endl; if (high == value) { match = true; break; } else if (high < value) { low = high; high += ( max_domain[ sample_index] - min_domain[sample_index] ) / (steps[sample_index] - 1); } else //when low <value value>high { break; } } if (match == false) { //std::cout<<"did not match any of these "<<std::endl; //std::cout<<" low "<<low<<"high " <<high<<std::endl; double diff1 = value - low; double diff2 = high - value; value = (diff1 < diff2) ? low : high; } } } else { //this is a set value unsigned int setValue_index = sample_index - min_domain.size(); //std::cout<<"inside the setValue normailize:"<<std::endl; //std::cout<<"the value being checked is "<<value; if (value <= setValues.at(setValue_index).at(0)) ///if less than the first element in the set { value = setValues.at(setValue_index).at(0); } else if (value >= setValues.at(setValue_index).at(setValues.at(setValue_index).size() - 1)) ///if greater than the last element in the set { value = setValues.at(setValue_index).at(setValues.at(setValue_index).size() - 1); } else { //so the value is greater than or equal to min|max domains unsigned int inner_index = 0; //currValue = min_domain.at(i); low = setValues.at(setValue_index).at(0); if (setValues.at(setValue_index).size() == 1) { std::cout << "setValues cannot have a single value . This should have been taken as a single value " << std::endl; exit(1); } high = setValues.at(setValue_index).at(1); //currValue=high; inner_index++; while (inner_index < setValues.at(setValue_index).size()) { // std::cout<<"In the while loop "<<std::endl; // std::cout<<"low ="<<low<<" high "<<high<<std::endl; if (high == value) { match = true; break; } else if (high < value) { low = high; inner_index++; high = setValues.at(setValue_index).at(inner_index); } else //when low <value value>high { break; } } if (match == false) { //std::cout<<"did not match any of these "<<std::endl; //std::cout<<" low "<<low<<"high " <<high<<std::endl; double diff1 = value - low; double diff2 = high - value; value = (diff1 < diff2) ? low : high; } } /*vector<double>::iterator low,high; low = lower_bound(setValues.at(setValue_index).begin(),setValues.at(setValue_index).end(),par[par_index]); high = upper_bound(setValues.at(setValue_index).begin(),setValues.at(setValue_index).end(),par[par_index]); std::cout<<"the size of the vector "<<setValues.at(setValue_index).size()<<" , low index"<<(int)(low-setValues.at(setValue_index).begin()); std::cout<<" high index"<<(int)high-setValues.at(setValue_index).begin()<<std::endl<<"the value being searched"<<par[par_index];; ///TODO currWorkwrite this functionality std::cout<<"done with range "<<std::endl;*/ } //std::cout<<"the normalized value"<<value<<std::endl; return value; } population populationGenerator::normalize_bounds(double par[], int popsize) { if ((min_domain.size() + setValues.size()) == 0) { std::cerr << "withing populationGenerator the proper constructor has not been called so cannot generate_Entire_pop" << std::endl; exit(1); } //popsize is the no of samples ///double par ][] has all the parameters int par_index = 0; for (unsigned int j = 0 ; j < popsize; j++) for (unsigned int i = 0 ; i < dimensions; i++) { par_index = j * dimensions + i; std::cout << "the par_index" << par_index << std::endl; //double currValue; bool match = false; double low, high; if (i < min_domain.size()) { //std::cout<<"parameter number "<<i<<std::endl; if (par[par_index] <= min_domain.at(i)) { par[par_index] = min_domain.at(i); } else if (par[par_index] >= max_domain.at(i)) { par[par_index] = max_domain.at(i); } else { //so the value is greater than or equal to min|max domains //currValue = min_domain.at(i); low = min_domain.at(i); high = low + ( max_domain[i] - min_domain[i] ) / (steps[i] - 1); //currValue=high; while (!(high > max_domain.at(i))) { // std::cout<<"In the while loop "<<std::endl; // std::cout<<"low ="<<low<<" high "<<high<<std::endl; if (high == par[par_index]) { match = true; break; } else if (high < par[par_index]) { low = high; high += ( max_domain[ i] - min_domain[i] ) / (steps[i] - 1); } else //when low <value value>high { break; } } if (match == false) { //std::cout<<"did not match any of these "<<std::endl; //std::cout<<" low "<<low<<"high " <<high<<std::endl; double diff1 = par[par_index] - low; double diff2 = high - par[par_index]; par[par_index] = (diff1 < diff2) ? low : high; } } ///deal with steos TODO :: come back ///this is a range value } else if ((i - min_domain.size()) < setValues.size()) { //this is a set value unsigned int setValue_index = i - min_domain.size(); std::cout << "inside the setValue normailize:" << std::endl; std::cout << "the value being checked is " << par[par_index]; if (par[par_index] <= setValues.at(setValue_index).at(0)) ///if less than the first element in the set { par[par_index] = setValues.at(setValue_index).at(0); } else if (par[par_index] >= setValues.at(setValue_index).at(setValues.at(setValue_index).size() - 1)) ///if greater than the last element in the set { par[par_index] = setValues.at(setValue_index).at(setValues.at(setValue_index).size() - 1); } else { //so the value is greater than or equal to min|max domains unsigned int inner_index = 0; //currValue = min_domain.at(i); low = setValues.at(setValue_index).at(0); if (setValues.at(setValue_index).size() == 1) { std::cout << "setValues cannot have a single value . This should have been taken as a single value " << std::endl; exit(1); } high = setValues.at(setValue_index).at(1); //currValue=high; inner_index++; while (inner_index < setValues.at(setValue_index).size()) { // std::cout<<"In the while loop "<<std::endl; // std::cout<<"low ="<<low<<" high "<<high<<std::endl; if (high == par[par_index]) { match = true; break; } else if (high < par[par_index]) { low = high; inner_index++; high = setValues.at(setValue_index).at(inner_index); } else //when low <value value>high { break; } } if (match == false) { //std::cout<<"did not match any of these "<<std::endl; //std::cout<<" low "<<low<<"high " <<high<<std::endl; double diff1 = par[par_index] - low; double diff2 = high - par[par_index]; par[par_index] = (diff1 < diff2) ? low : high; } } /*vector<double>::iterator low,high; low = lower_bound(setValues.at(setValue_index).begin(),setValues.at(setValue_index).end(),par[par_index]); high = upper_bound(setValues.at(setValue_index).begin(),setValues.at(setValue_index).end(),par[par_index]); std::cout<<"the size of the vector "<<setValues.at(setValue_index).size()<<" , low index"<<(int)(low-setValues.at(setValue_index).begin()); std::cout<<" high index"<<(int)high-setValues.at(setValue_index).begin()<<std::endl<<"the value being searched"<<par[par_index];; ///TODO currWorkwrite this functionality std::cout<<"done with range "<<std::endl;*/ std::cout << "the new values" << par[par_index]; int pause; std::cin >> pause; } else { std::cout << "something wrong in populationGenerator:: normalize_bounds " << std::endl; exit(1); } } population random_pop(par, popsize, dimensions); ///this is generating the population based on the array return random_pop; } <file_sep>/tests/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project (optimizationCode) ######################### # GTest ######################### add_subdirectory(${GMOCK_SOURCE_DIR} ${CMAKE_BINARY_DIR}/lib/google_mock) link_directories(${CMAKE_BIN_DIR}/lib) enable_testing( ) include_directories (${GTEST_SOURCE_DIR} ${GTEST_SOURCE_DIR}/include) include_directories (${GMOCK_SOURCE_DIR}/include) include_directories (${CMAKE_SOURCE_DIR}/include) include_directories (${CMAKE_SOURCE_DIR}/fitness_lib/include) include_directories (${Boost_INCLUDE_DIRS}) include_directories (${MPI_CXX_INCLUDE_PATH}) include_directories (${LIBSIVELAB_PATH}) include_directories (${CMAKE_SOURCE_DIR}/include) include_directories (${CMAKE_SOURCE_DIR}/fitness_lib/include) include_directories (${ANTLR_INCLUDES}) include_directories (${QES_INCLUDE_DIRECTORIES}) ######################### # Unit Tests ######################### add_subdirectory(opt_grammar) add_subdirectory(utils)<file_sep>/include/logger/log_tester.cpp #include "logger.h" using namespace sivelab; int main(int argc, char *argv[]) { logger log(LOG_LEVEL::ALL, "main"); log.error("This is an error message", 1 ); log.info("This is a info message"); log.debug("This is a debug message"); return 0; }<file_sep>/src/mpi_gpuplume/CMakeLists.txt cmake_minimum_required (VERSION 2.8) project (optimizationCode) include_directories (${LIBSIVELAB_PATH}) include_directories(${CMAKE_SOURCE_DIR}/include) add_library(mpi_gpuplume gpu_plume_job.cpp) target_link_libraries (mpi_gpuplume optm-utils) target_link_libraries (mpi_gpuplume dl) target_link_libraries (mpi_gpuplume mpi_framework) target_link_libraries (mpi_gpuplume mpi_framework)<file_sep>/src/MPI_framework/CMakeLists.txt cmake_minimum_required (VERSION 2.8) project (optimizationCode) include_directories (${LIBSIVELAB_PATH}) include_directories(${CMAKE_SOURCE_DIR}/include) include_directories (${CMAKE_SOURCE_DIR}/fitness_lib/include) include_directories (${QES_INCLUDE_DIRECTORIES}) link_directories(${LIBSIVELAB_PATH}) add_library(mpi_framework job.cpp) target_link_libraries (mpi_framework optm-utils) target_link_libraries (mpi_framework sive-quicutil) <file_sep>/src/MPI_framework/include/job.h #ifndef __JOB_H__ #define __JOB_H__ 1 #include "iostream" #include "map" #include "logger/logger.h" #include "utils/population.h" #include "utils/opt_params.h" #include "quicutil/QUICProject.h" #include "utils/directory.h" #include "utils/namedOptParam.h" #include "utils/dependencyOptParam.h" #include "utils/solver.h" #include "utils/FitnessCache.h" #include "fitness_function.h" #include <dlfcn.h> #ifndef FITNESS_FUNCTION_LIBRARY #define FITNESS_FUNCTION_LIBRARY "../lib/libfitness.so" #endif namespace sivelab { class job { private: void *dl_handle; Fitness* (*create)(QUICProject&, opt_params&); void (*destroy)(Fitness*); public: opt_params optParams; string output_location; logger log; QUICProject quqpData; directory workDir; Fitness* fitness; job(const opt_params &optParams_): optParams(optParams_), log(DEBUG, "job") { //setup_environment //TODO: Do error handling char *error; char lib[] = FITNESS_FUNCTION_LIBRARY; dl_handle = dlopen(lib, RTLD_LAZY ); if (!dl_handle) { printf( "!!! %s\n", dlerror() ); } //these are made pointer as nx, ny, etc are not available in quqpData yet. They are filled in once //setup environment is finished, hence sending a reference create = (Fitness* (*) (QUICProject&, opt_params&))dlsym(dl_handle, "create_object"); destroy = (void (*)(Fitness*))dlsym(dl_handle, "destroy_object"); //fetch these from optparams fitness = (Fitness*) create(quqpData, optParams); error = dlerror(); if (error != NULL) { printf( "!!! %s\n", error ); } } virtual ~job() { destroy(fitness); dlclose( dl_handle ); } virtual bool eval_population_fitness( population &pop ) = 0; virtual string prepare_work_dir_for_sample(sample &s); virtual bool setup_environment(string &output_location); std::string searchForPROJFile(const std::string &dir); void copyFile(const std::string &sourceFilename, const std::string &destFilename); dependencyOptParam *lookupDataInDependencyMap(unsigned int idx); namedOptParam *lookupDataInMapFromSampleIndex(unsigned int idx); namedOptParam *lookupDataInSolverMap(unsigned int idx); namedOptParam *lookupDataInRangeMap(unsigned int idx); namedOptParam *lookupDataInSingleMap(unsigned int idx); namedOptParam *lookupDataInSetMap(unsigned int idx); void augmentDataFromSingleValues(sivelab::QUICProject &quqpData, std::vector<std::string> &singleValues); //// set to deal with singleValues void augmentDataforAvgParam(sivelab::QUICProject &quqpData, std::vector<std::string> &dataStructureNames, int index); ///this is used to change the value for a single sample . i.e the avegraing parameter void augmentDataFromSample( const sample &s, sivelab::QUICProject &quqpData, std::vector<std::string> &dataStructureNames); //// as of now deas with only range values ///languageMap void augmentBuildingDataFromSample( const sample &s, quBuildings &bData ); ///languageMap void augmentDataBasedOnDependency(sivelab::QUICProject &quqpData, std::vector<std::string> &dataStructureNames); //// as of now deas with only range values ///languageMap //TODO: resurrect this when needed //virtual bool eval_sample_fitness( sample &s ) = 0; //below code is from eval_sample_fitness from gpu_plume_job }; } #endif ///usr/bin/c++ -std=c++11 -g CMakeFiles/quic.dir/quic.cpp.o -o quic -L/home/csgrads/vuggu001/workspace/quik/optimizationCode/../libsivelab/lib -rdynamic -lmpi_cxx -lmpi -ldl -lhwloc -Wl,-Bstatic -lboost_mpi -lboost_serialization opt_grammar/liboptfileparser.a mpi_gpuplume/libmpi_gpuplume.a MPI_framework/libmpi_framework.a utils/liboptm-utils.a ../../qes-v1/lib/libsivelab/lib/libsive-quicutil.a ../../qes-v1/lib/libsivelab/lib/libsive-util.a -Wl,-Bdynamic -ldl -Wl,-rpath,/home/csgrads/vuggu001/workspace/quik/optimizationCode/../libsivelab/lib <file_sep>/src/utils/concentrationRedux.cpp #include "utils/concentrationRedux.h" // 1) Identifying / removing emitter cells (I usually remove 3 // cells). May be you can provide an option where the program asks the // user how many cells should be removed (0, 1, 3, 5 etc). // 2) Calculating the max in the collecting box region and identifying // the coordinates of the grid point where it occurs. Also, may be // compute the first 4 moments (mean, standard deviation, skewness and // kurtosis) so that we may get an idea about the distribution of the // concentration values. // 3) If the main code can take as an input from the user a threshold // value (we may provide this through the Perl scripts), then // computing total number of exceedances at a few elevations above the // ground. concentrationRedux::concentrationRedux() { m_exceedanceCount = 0; m_zslice_max = 1.5; m_useAllData = false; } concentrationRedux::concentrationRedux(const std::string &filename, const quBuildings &quBuildingData, const qpSource &qpSourceData, double zSliceMax) { // store the file name for reference m_concFilename = filename; m_zslice_max = zSliceMax; std::ifstream concFile; concFile.open(filename.c_str(), std::ifstream::in); if(!concFile.is_open()) { std::cerr << "Error! could not open :: " << filename << "." << std::endl; exit(EXIT_FAILURE); } std::string line; std::stringstream ss(line, std::stringstream::in | std::stringstream::out); getline(concFile, line); getline(concFile, line); getline(concFile, line); getline(concFile, line); getline(concFile, line); ss.str(line); std::string name; ss >> name; ss.clear(); std::cout << "Reading " << name << std::endl; concData cd; bool done = false; std::string tmpStr; while (!done && !concFile.eof()) { getline(concFile, line); ss.str(line); ss >> tmpStr; if (tmpStr == "];") { done = true; } else { ss.str(line); ss >> cd.x >> cd.y >> cd.z >> cd.c; m_concData.push_back(cd); } ss.clear(); } concFile.close(); writeConcFile(); std::cerr<<"Before removing buildings cells"<<std::endl; removeBuildingCells(quBuildingData); std::cerr<<"After removing "<<std::endl; removeEmitterCells(qpSourceData); std::cerr<<"After removing emitter"<<std::endl; calcMean(); std::cerr<<"After mean \n"; calcMinMax(); std::cerr<<"After min max\n"; calcExceedances(1.0e-4); return; } concentrationRedux::~concentrationRedux() { } void concentrationRedux::writeConcFile() { std::ofstream concFile; concFile.open("/tmp/testOut.m"); if(!concFile.is_open()) { std::cerr << "Error! could not open tst conc file" << std::endl; exit(EXIT_FAILURE); } concFile << "% The following array contains the locations of the" << std::endl; concFile << "% collection box cells in X, Y, and Z followed by the " << std::endl; concFile << "% concentration in the cell." << std::endl; concFile << "dc = [" << std::endl; std::list<concData>::iterator cIter; for (cIter=m_concData.begin(); cIter!=m_concData.end(); ++cIter) { concFile << "\t" << (*cIter).x << " " << (*cIter).y << " " << (*cIter).z << " " << (*cIter).c << ";" << std::endl; } concFile << "];" << std::endl; concFile << "x=dc(:,1);" << std::endl; concFile << "y=dc(:,2);" << std::endl; concFile << "z=dc(:,3);" << std::endl; concFile << "con=dc(:,4);" << std::endl; concFile << "xUni=unique(x);" << std::endl; concFile << "yUni=unique(y);" << std::endl; concFile << "zUni=unique(z);" << std::endl; concFile << "xLen = length(xUni);" << std::endl; concFile << "yLen = length(yUni);" << std::endl; concFile << "zLen = length(zUni);" << std::endl; concFile << "[X Y] = meshgrid(xUni, yUni);" << std::endl; // only care about first three layers for now concFile << "for i=1:3" << std::endl; concFile << "fid = figure;" << std::endl; concFile << "concSlice=con(z==zUni(i));" << std::endl; concFile << "C=reshape(concSlice,xLen,yLen);" << std::endl; concFile << "pcolor(C')" << std::endl; concFile << "colorbar;" << std::endl; concFile << "title(['Concentration - Z = ',num2str(zUni(i)),'m'])" << std::endl; concFile << "set(gcf,'color','w')" << std::endl; concFile << "print -dpng" << std::endl; concFile << "end" << std::endl; concFile.close(); } void concentrationRedux::calcMean(void) { std::list<concData>::iterator cIter; unsigned int meanCount = 0; double value =0; m_sum = m_mean = 0.0; m_norm1 = m_norm2 = m_norm3 = m_norm4 = 0.0; for (cIter=m_concData.begin(); cIter!=m_concData.end(); ++cIter) { if ((*cIter).z <= m_zslice_max) { value=(*cIter).c; // std::cout << "z height = " << (*cIter).z << std::endl; m_sum += value; m_norm1 += fabs(value); m_norm2 += pow(fabs(value),2); m_norm3 += pow(fabs(value),3); m_norm4 += pow(fabs(value),4); /////to calculate norm's meanCount++; } } m_mean = m_sum / meanCount; m_stddev = 0.0; for (cIter=m_concData.begin(); cIter!=m_concData.end(); ++cIter) { if ((*cIter).z <= m_zslice_max) { m_stddev += (((*cIter).c - m_mean) * ((*cIter).c - m_mean)); } } m_stddev /= meanCount; m_stddev = sqrt(m_stddev); m_norm2 = pow(m_norm2,(double)1/2.0); m_norm3 = pow(m_norm3,(double)1/3.0); m_norm4 = pow(m_norm4,(double)1/3.0); std::cerr<<"THE value of norm2------------- = "<<m_norm2<<std::endl; } void concentrationRedux::calcMinMax(void) { m_max = std::numeric_limits<double>::min(); m_min = std::numeric_limits<double>::max(); double eps = 1.0e-3; std::list<concData>::iterator cIter; for (cIter=m_concData.begin(); cIter!=m_concData.end(); ++cIter) { // std::cout << "cIter.z = " << (*cIter).z << ", zSliceMax = " << m_zslice_max << std::endl; // std::cout << "cIter.z=" << (*cIter).z << ", (m_zslice_max+eps)=" << (m_zslice_max+eps) << ", (m_zslice_max-eps)=" << (m_zslice_max-eps) << std::endl; if (((*cIter).z <= (m_zslice_max+eps)) && ((*cIter).z >= (m_zslice_max-eps))) { // found the slice we care about if ((*cIter).c > m_max) m_max = (*cIter).c; if ((*cIter).c < m_min) m_min = (*cIter).c; } #if 0 if ((*cIter).z <= m_zslice_max) { if ((*cIter).c > m_max) m_max = (*cIter).c; if ((*cIter).c < m_min) m_min = (*cIter).c; } #endif } } void concentrationRedux::removeEmitterCells(const qpSource &qpSourceData) { float cx, cy, cz; float minX, minY, minZ; float maxX, maxY, maxZ; std::list<concData>::iterator cIter; std::vector<std::list<concData>::iterator> toBeRemoved; for (cIter=m_concData.begin(); cIter!=m_concData.end(); ++cIter) { cx = (*cIter).x; cy = (*cIter).y; cz = (*cIter).z; for (unsigned int eIdx=0; eIdx<qpSourceData.sources.size(); eIdx++) { if (qpSourceData.sources[eIdx].geometry == qpSource::LINE) // line would be 2 { if (qpSourceData.sources[eIdx].points[0].x < qpSourceData.sources[eIdx].points[1].x) { minX = (int)floor(qpSourceData.sources[eIdx].points[0].x); maxX = (int)ceil(qpSourceData.sources[eIdx].points[1].x); } else { minX = (int)floor(qpSourceData.sources[eIdx].points[1].x); maxX = (int)ceil(qpSourceData.sources[eIdx].points[0].x); } if (qpSourceData.sources[eIdx].points[0].y < qpSourceData.sources[eIdx].points[1].y) { minY = (int)floor(qpSourceData.sources[eIdx].points[0].y); maxY = (int)ceil(qpSourceData.sources[eIdx].points[1].y); } else { minY = (int)floor(qpSourceData.sources[eIdx].points[1].y); maxY = (int)ceil(qpSourceData.sources[eIdx].points[0].y); } if (qpSourceData.sources[eIdx].points[0].z < qpSourceData.sources[eIdx].points[1].z) { minZ = (int)floor(qpSourceData.sources[eIdx].points[0].z); maxZ = (int)ceil(qpSourceData.sources[eIdx].points[1].z); } else { minZ = (int)floor(qpSourceData.sources[eIdx].points[1].z); maxZ = (int)ceil(qpSourceData.sources[eIdx].points[0].z); } } if (((cx >= minX) && (cx <= maxX)) && ((cy >= minY) && (cy <= maxY)) && ((cz >= minZ) && (cz <= maxZ))) { // Collection box center is within a emitter so remove the collection box from the main list // some emitters cross so we don't want to eliminate a bad emitter iterator toBeRemoved.push_back( cIter ); } } } std::cout << "Preparing to remove " << toBeRemoved.size() << " emitter cells from concentration data (size=" << m_concData.size() << ")" << std::endl; for (unsigned int tbr=0; tbr<toBeRemoved.size(); tbr++) { if (cIter != m_concData.end()) m_concData.erase(toBeRemoved[tbr]); } std::cout << "Removed. Concentration data (size=" << m_concData.size() << ")" << std::endl; } void concentrationRedux::removeBuildingCells(const quBuildings &quBuildingData) { float cx, cy, cz; float minX, minY, minZ; float maxX, maxY, maxZ; std::list<concData>::iterator cIter; std::vector<std::list<concData>::iterator> toBeRemoved; for (cIter=m_concData.begin(); cIter!=m_concData.end(); ++cIter) { cx = (*cIter).x; cy = (*cIter).y; cz = (*cIter).z; for (unsigned int bldIdx=0; bldIdx<quBuildingData.buildings.size(); bldIdx++) { minX = quBuildingData.buildings[bldIdx].xfo; maxX = quBuildingData.buildings[bldIdx].xfo + quBuildingData.buildings[bldIdx].length; minY = quBuildingData.buildings[bldIdx].yfo - quBuildingData.buildings[bldIdx].width/2.0; maxY = quBuildingData.buildings[bldIdx].yfo + quBuildingData.buildings[bldIdx].width/2.0; minZ = quBuildingData.buildings[bldIdx].zfo; maxZ = quBuildingData.buildings[bldIdx].zfo + quBuildingData.buildings[bldIdx].height; if (((cx >= minX) && (cx <= maxX)) && ((cy >= minY) && (cy <= maxY)) && ((cz >= minZ) && (cz <= maxZ))) { // Collection box center is within a building so remove the collection box from the if (cIter != m_concData.end()) toBeRemoved.push_back( cIter ); } } } std::cout << "Preparing to remove " << toBeRemoved.size() << " building cells from concentration data (size=" << m_concData.size() << ")" << std::endl; for (unsigned int tbr=0; tbr<toBeRemoved.size(); tbr++) { // std::cerr<<"before accessing the element"<<std::endl; // std::cerr<<"tbr index"<<tbr<<"\t"<<"the element trying to remove"<<(*toBeRemoved[tbr]).z<<std::endl; m_concData.erase(toBeRemoved[tbr]); // std::cerr<<"After removing it from the m_concData"<<std::endl; } std::cerr << "Removed. Concentration data (size=" << m_concData.size() << ")" << std::endl; } void concentrationRedux::calcExceedances(double threshold) { // reset the count m_exceedanceCount = 0; std::list<concData>::iterator cIter; for (cIter=m_concData.begin(); cIter!=m_concData.end(); ++cIter) { if ((*cIter).c > threshold) m_exceedanceCount++; } } <file_sep>/tests/utils/test_population.cpp #include "utils/population.h" #include "utils/population_gen.h" #include <vector> #include "gtest/gtest.h" #include "gmock/gmock.h" using namespace std; using namespace sivelab; using ::testing::ElementsAre; using ::testing::ContainerEq; class PopulationTest: public testing::Test { public: std::vector<double> minValues; std::vector<double> maxValues; std::vector<int> stepValues; std::vector<std::vector<double> > setValues; populationGenerator popgen; population pop; PopulationTest():minValues{1, 2.5, 1}, maxValues{10, 10, 10}, stepValues{1, 2, 7}, setValues{{1, 2}, {3, 4, 5}}, popgen(minValues, maxValues, stepValues, setValues) { pop = popgen.generate_all_pop(); } }; TEST_F(PopulationTest, full_population_subset){ long populationSize = pop.size(); population temp_pop; pop.get_subset(0, populationSize, temp_pop); for(int i=0;i>populationSize;i++) ASSERT_THAT(temp_pop[i], ContainerEq(pop[i])); } TEST_F(PopulationTest, subsets_with_equal_samples){ long populationSize = pop.size(); //this test case generates a population of 480 samples //lets divide the total population into subsets of 10 long samplesSize = populationSize/48; population temp_pop; long from=0; //get_subset returns the sample number that will be the first sample in the next subset for(;(from=pop.get_subset(from, samplesSize, temp_pop))!=-1;){} //check if we got all population for(int i=0;i>populationSize;i++) ASSERT_THAT(temp_pop[i], ContainerEq(pop[i])); } TEST_F(PopulationTest, final_subset_with_less_samples){ long populationSize = pop.size(); //this test case generates a population of 480 samples //lets divide the total population into subsets of 25 samples //then the last sample has only 5 samples long samplesSize = populationSize/25; population temp_pop; population another_temp; long from=0; for(;(from=pop.get_subset(from, samplesSize, temp_pop))!=-1;) { } for(int i=0;i>populationSize;i++) ASSERT_THAT(temp_pop[i], ContainerEq(pop[i])); }<file_sep>/tests/MPI_framework/test_job.cpp #include "MPI_framework/job.h" #include "gmock/gmock.h" #include "utils/opt_params.h" #include "utils/population.h" #include "map" #include "string" #include "iostream" #include "stdio.h" using namespace std; using ::testing::ElementsAre; using ::testing::ContainerEq; class testJob: public job{ public: testJob(opt_params &optParams_):job(optParams_){} virtual ~testJob(){} bool eval_population_fitness(population &pop){} }; //http://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c std::string exec(string& str) { // const char *cmd = str.c_str(); FILE* pipe = popen(cmd, "r"); if (!pipe) return "ERROR"; char buffer[128]; std::string result = ""; while(!feof(pipe)) { if(fgets(buffer, 128, pipe) != NULL) result += buffer; } pclose(pipe); return result; } TEST(Job, setup_environment_test){ opt_params optParams; optParams.baseproj_inner_path = "../resources/2by2_q572_270/2by2_q572_270_inner"; testJob job(optParams); string output_path = "./"; job.setup_environment(output_path); string diff_command = "diff -r ../resources/2by2_q572_270/2by2_q572_270_inner ../localBaseCopy/local_inner"; string output = exec(diff_command); //ASSERT with your eyes it is difficult to automate this :| //ASSERT_EQ("", output); FAIL()<<"This test must be examined manually running the following command\n"<< "diff -r ../resources/2by2_q572_270/2by2_q572_270_inner ../localBaseCopy/local_inner"; // string cleanup_command = "rm "+optParams.baseproj_inner_path; // output = exec(diff_command); } //TODO write test for validating paramater changes in local copy of QUICProject <file_sep>/src/opt_grammar/makefile all: OptFileGrammar OptFileGrammarLexer.cpp OptFileGrammarParser.cpp: OptFileGrammar.g java -jar antlr-3.5.2-complete.jar OptFileGrammar.g OptFileGrammar: OptFileGrammar_interpreter.cpp OptFileGrammarLexer.cpp OptFileGrammarParser.cpp g++ -Wall -g -std=c++11 -I `pwd`/antlr -o OptFileGrammar OptFileGrammar_interpreter.cpp OptFileGrammarLexer.cpp OptFileGrammarParser.cpp clean: rm -f OptFileGrammarLexer.cpp OptFileGrammarParser.cpp OptFileGrammar OptFileGrammarLexer.hpp OptFileGrammarParser.hpp <file_sep>/src/mpi_qes_spf/CMakeLists.txt cmake_minimum_required (VERSION 2.8) project (optimizationCode) # # CMake Module path for including additional CMake macros to make # finding libraries and other requirements easier. # Don't need this anymore seems to work with newer versions of CMake # SET( CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules" ${CMAKE_MODULE_PATH} ) # # Include local source directories # add_definitions( -DQUIC_DATA_DIR="${QUIC_DATA_PATH}" ) # QUIC_DATA_DIR add_definitions( -DQES_ROOT_DIR="${QES_ROOT_DIR}" ) # QES_ROOT_DIR # # Make some directories that are used by the system # when dumping build files and simulation output # file( MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/programs" ) # for ptx files file( MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/output" ) #end include_directories (${QES_INCLUDE_DIRECTORIES}) include_directories (${CMAKE_SOURCE_DIR}/include) include_directories (${CMAKE_SOURCE_DIR}/fitness_lib/include) include_directories (${LIBSIVELAB_PATH}) ##QES include directories add_library ( mpi_simpleLSM simpleLSM_job.cpp ) target_link_libraries( mpi_simpleLSM QESLSM QESViewfactor ) target_link_libraries (mpi_simpleLSM optm-utils) target_link_libraries (mpi_simpleLSM dl) target_link_libraries (mpi_simpleLSM mpi_framework) target_link_libraries (mpi_simpleLSM ${Boost_LIBRARIES}) <file_sep>/src/utils/include/ArgumentParsing.h /* * ArgumentParsing.h * NETCODE * * Created by <NAME> on 10/6/09. * Copyright 2009 Department of Computer Science, University of Minnesota-Duluth. All rights reserved. * */ #ifndef __ARGUMENT_PARSING_H__ #define __ARGUMENT_PARSING_H__ 1 #include <iostream> #include <cstdlib> #include <cstring> #include <vector> #ifdef WIN32 #include "getopt_win32.h" #else #include <getopt.h> #endif class ArgumentParser { public: ArgumentParser(); ArgumentParser(int argc, char *argv[]); ~ArgumentParser(); void reg(const std::string& argName, char shortArgName, int has_argument, bool required=false); int processCommandLineArgs(int argc, char *argv[]) { return process(argc, argv); } bool isSet(const std::string& argName); bool isSet(const std::string& argName, std::string &argValue); protected: int process(int argc, char *argv[]); private: // getopt_long structure variables // struct option { // const char *name; // int has_arg; // int *flag; // int val; // }; struct ModifiedOption { bool isSet; option optParams; std::string optionalArgument; }; std::vector<ModifiedOption> m_ArgVector; }; #endif // __ARGUMENT_PARSING_H__ 1 <file_sep>/tests/utils/test_optParams.cpp #include "utils/opt_params.h" #include "gmock/gmock.h" using namespace std; using ::testing::ElementsAre; using ::testing::ContainerEq; TEST(OPT_Params, opt_params){ //prep test data std::map<string, map<string, string>> optParams; //single values map<string, string> single_value_1; single_value_1["lval"]="a"; single_value_1["lval_type"]="project_variable"; single_value_1["rval"] = "1"; single_value_1["rval_type"] = "number"; optParams["a"] = single_value_1; map<string, string> single_value_2; single_value_2["lval"]="b"; single_value_2["lval_type"]="project_variable"; single_value_2["rval"] = "2"; single_value_2["rval_type"] = "number"; optParams["b"] = single_value_2; //strings map<string, string> string_value_1 = { {"lval", "BaseProjectPath"}, //lval types are not used anywhere yet there are just included for //future validation checks //e.g. Does this simulation have all the required controls variables //etc {"lval_type", "control"}, {"rval", "../this/is/a/path"}, {"rval_type","string"} }; optParams["BaseProjectPath"] = string_value_1; //not all variables are used only certain specail variables like //"BaseProjectPath", "solver" etc are recognized my opt_params::readParams //You may need to extend that method if you want to recognize additional //special strings map<string, string> string_value_2 = { {"lval", "unused_string"}, {"lval_type", "project_variable"}, {"rval", "this tring variable is unused"}, {"rval_type","string"} }; optParams["unused_string"] = string_value_2; //set map<string, string> set_value1 = { {"lval", "set1"}, {"lval_type", "project_variable"}, {"rval", "10 11 12"}, {"rval_type","set"} }; optParams["set1"] = set_value1; map<string, string> set_value2 = { {"lval", "set2"}, {"lval_type", "project_variable"}, {"rval", "13, 14 15"}, {"rval_type","set"} }; optParams["set2"] = set_value2; //range map<string, string> range_value1 = { {"lval", "range1"}, {"lval_type", "project_variable"}, {"min", "1.0"}, {"max", "10.0"}, {"step", "3"},//steps are always integrals {"rval_type","range"} }; optParams["range1"] = range_value1; map<string, string> range_value2 = { {"lval", "range2"}, {"lval_type", "project_variable"}, {"min", "1.0"}, {"max", "10.0"}, {"step", "2"}, {"rval_type","range"} }; optParams["range2"] = range_value2; //create an instance of opt_params class opt_params ops; ops.readParams(optParams); //std::vector<int> expectedSingleValues = {1, 2}; //single values are not yet used dang! //TODO //EXPECT_THAT(ops.singleValues, ContainerEq(expectedSingleValues)); ASSERT_THAT(ops.setValues, ElementsAre(ElementsAre(10, 11, 12), ElementsAre(13, 14, 15))); std::vector<double> expectedMinValues = {1, 1}; ASSERT_THAT(ops.minValues, ContainerEq(expectedMinValues)); std::vector<double> expectedMaxValues = {10, 10}; ASSERT_THAT(ops.maxValues, ContainerEq(expectedMaxValues)); std::vector<int> expectedStepValues = {3, 2}; ASSERT_THAT(ops.stepValues, ContainerEq(expectedStepValues)); //Update tests for named parmaeters // std::vector<namedOptParam> rangeOptMap; // std::vector<namedOptParam> setOptMap; // std::vector<namedOptParam> singleOptMap; // std::vector<dependencyOptParam> dependencyOptMap; // std::vector<namedOptParam> solverOptMap; } int main( int argc, char *argv[] ) { ::testing::InitGoogleMock( &argc, argv ); return RUN_ALL_TESTS( ); }<file_sep>/README.md ##Compile & build Instructions## ``` .../optimizationCode$ mkdir build .../optimizationCode$ cd build .../optimizationCode/build$ cmake -DCMAKE_BUILD_TYPE=RELEASE -DOptiX_INSTALL_DIR=/home/cs/software/sivelab/NVIDIA-OptiX-SDK-3.6.2-linux64 -DCUDA_TOOLKIT_ROOT_DIR=/home/cs/software/sivelab/cuda_6.0 .. .../optimizationCode/build$ make ``` ##Run instructions## ``` .../optimizationCode/build$ cd src .../optimizationCode/build/src$ mpirun -np {no. of processes to be created} --machinefile {file containing the list of slaves} ./quic --optfile={path to optimization file} --loglevel={info, debug, error} eg. mpirun -np 10 -v --machinefile ../../inputs/machines.txt ./quic --optfile=../../inputs/optfiles/optTest8D_LSM_job_antlr_tiny.opt --loglevel=info ``` Directory Structure ------------------- optimizationCode * docs (documentation) * fitness_lib (fitness function shared lib) * include (Contains symbolic links to include directories all libraries in src) * inputs (sample optfiles and hostsfile) * src (source code)--| * MPI_Framework (Code which needs to be implemented by all jobs) * mpi_gpuplume (GPU Plume code implementing MPI_framework) * opt_grammar (ANTLR grammar for reading optimization files) * qes_spf_mpi (TODO) * Utils (Utility code) * tests (Visit this if you have any questions) * thesisDoc(Thesis story) * CMakeLists.txt (Top level cmake file) * README.md (you are reading it right now!) <file_sep>/fitness_lib/CMakeLists.txt cmake_minimum_required(VERSION 2.6) project (optimizationCode) add_library (fitness SHARED fitness_function.cpp) #include_directories (${LIBSIVELAB_PATH}/include) include_directories (${CMAKE_SOURCE_DIR}/include) include_directories (${Boost_INCLUDE_DIRS}) include_directories (${CMAKE_CURRENT_SOURCE_DIR}/include) include_directories (${QES_INCLUDE_DIRECTORIES}) <file_sep>/src/utils/include/solver.h #ifndef SOLVER_H #define SOLVER_H #include <math.h> #include <list> #include <cstdlib> #include "population.h" #include <vector> #include "quicutil/language_map.h" using namespace std; // A generic base solver class for n-dimensional problems. class solver : public languageMap { public: /* Some basic stuff to set to define the problem */ // The fitness function takes a sample point and returns a scalar value double (*fitness_func)( sample &s); // This is a pointer to a func // The domain is a min and max for each dimension in the space vector< double > min_domain; vector< double > max_domain; vector< int > steps; vector< vector< double > > setValues; // We store the convergence epsilon for later use double m_converge_eps; // The population of samples population samples; /* Constructors */ solver(); /* Some methods for swapping the fitness and domain size */ void set_fitness_function( double (*fitness)( sample &s ) ); void set_domain( vector< double > min_domain_, vector< double > max_domain_ ,vector <int > steps , vector< vector<double > > setvalues_ ); /* The solver is mostly virtual until a particular derived class is defined and instantiated */ // These things seem fairly generic to a solver, although all may not really want them. /* virtual bool convergence_test(); virtual pt cooling_schedule( pt &sigmas ); virtual pt find_solution( pt &sigmas, // the std deviation of the blur function double converge_eps); // The convergence eps */ }; #endif <file_sep>/docs/plumeOptimization.md Population optimization code is located in /gpuplume/populationSampleOpt/ Compiling ---------- /gpuplume/populationSampleOpt $ cmake . /gpuplume/populationSampleOpt $ make Running ----------- <file_sep>/src/utils/solver.cpp #include <math.h> #include <list> #include <cstdlib> #include <cstdio> #include "utils/population.h" #include "utils/solver.h" //check what this is //#include "AS047.h" #include <algorithm> #include <vector> using namespace std; solver::solver() { ; } void solver::set_fitness_function( double (*fitness)( sample &s ) ) { fitness_func = fitness; } void solver::set_domain( vector< double > min_domain_, vector< double > max_domain_ , vector<int> steps_ , vector< vector<double > > setvalues_) { min_domain = min_domain_; max_domain = max_domain_; steps=steps_; for (unsigned int i = 0; i < setvalues_.size(); i++ ) { setValues.push_back(setvalues_[i]); } } <file_sep>/src/MPI_framework/job.cpp #include "MPI_framework/job.h" using namespace sivelab; //Change the optimizingDir as per the sample string job::prepare_work_dir_for_sample(sample &s) { //TODO change this //magic! workdir.outputDir is set in //workDir.intialRun(output_location + "/optimizingDir", output_location + "/localBaseCopy/local_inner/", quqpData, "local.proj"); //at this point it is output_location + "/optimizingDir" std::string outputDir = workDir.outputDir; ///TODO single values are being handled // Given the sample information stored in "s", we should be able to // "instance" a new simulation. This will be done by generating the // appropriate files in a tmp directory. Some of the files can be // "copied" from the base project directory. Others will need to be // loaded, modified, and then written out to the scratch space. /// boost::timer t; double retFitness; //TODO: add cache char dirName[128], dirName2[128]; // need to get the correct .proj file from the base directory... and not assume a .proj file name // find the name of the .proj file in the base directory path provided... std::string projFileName = searchForPROJFile(optParams.baseproj_inner_path + "/.."); // std::string projPrefix = projFileName.substr(0, projFileName.length() - 5); long probInstID = 1; ///adding this to make the avg param work :D retFitness = 0.0; // use the problemID and the problemInstanceID to // generate a unique ID for the concentration. This // will at least allow us to link it back to the correct // simulation. long currProbID = 1; probInstID++; //log.debug("Starting work on problem instance ", probInstID, " of Problem #", currProbID); //log.debug("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); int pause_temp1; std::string quicFilesPath = optParams.baseproj_inner_path + "/"; std::vector<std::string> dataStructureNames; //contains dataStructureNames that are being modified in the sample ////modifying data in the datastructures .... augmentDataFromSample(s, quqpData, dataStructureNames); // log.debug( "before modifying dependency"); // log.debug( "---------------------_"); // log.debug( "quqpData.quBuildingData.x_subdomain_sw = " , quqpData.quBuildingData.x_subdomain_sw ); // log.debug( "quqpData.quBuildingData.y_subdomain_sw = " , quqpData.quBuildingData.y_subdomain_sw ); // log.debug( "quqpData.quBuildingData.x_subdomain_ne = " , quqpData.quBuildingData.x_subdomain_ne ); // log.debug( "quqpData.quBuildingData.y_subdomain_ne = " , quqpData.quBuildingData.y_subdomain_ne ); // log.debug( "quqpData.quBuildingData.zo = " , quqpData.quBuildingData.zo); augmentDataBasedOnDependency(quqpData, dataStructureNames); // log.debug( "after modifying "); // log.debug( "quqpData.quBuildingData.x_subdomain_sw = ", quqpData.quBuildingData.x_subdomain_sw); // log.debug( "quqpData.quBuildingData.y_subdomain_sw = ", quqpData.quBuildingData.y_subdomain_sw); // log.debug( "quqpData.quBuildingData.x_subdomain_ne = ", quqpData.quBuildingData.x_subdomain_ne); // log.debug( "quqpData.quBuildingData.y_subdomain_ne = ", quqpData.quBuildingData.y_subdomain_ne); // log.debug( "quqpData.quBuildingData.zo = ", quqpData.quBuildingData.zo); // ... in the 5D test case, this means modifying the overall int bld1Idx = quqpData.quBuildingData.findIdxByBldNum(1); assert(bld1Idx != -1); int bld2Idx = quqpData.quBuildingData.findIdxByBldNum(2); assert(bld2Idx != -1); /* quqpData.qpSourceData.sources[0].points[0].x = quqpData.quBuildingData.buildings[ bld1Idx ].xfo + quqpData.quBuildingData.buildings[ bld1Idx ].length; quqpData.qpSourceData.sources[0].points[0].z = 0.5; quqpData.qpSourceData.sources[0].points[1].x = quqpData.quBuildingData.buildings[ bld2Idx ].xfo; quqpData.qpSourceData.sources[0].points[1].z = 0.5;*/ // quqpData.qpSourceData.writeQUICFile(outputDir + "/QP_source.inp"); // copyFile(quicFilesPath + "QP_fileoptions.inp", outputDir + "/QP_fileoptions.inp"); //dataStructureNames.push_back("qpSource"); // qpParams qpParamData; // qpParamData.readQUICFile(quicFilesPath + "QP_params.inp"); // We need to modify the QP Param data to only use 1 particle // and run for a minimum amount of time while generating the // turbulence field... //int origNumParticles = quqpData.qpParamData.numParticles; //int origDuration = quqpData.qpParamData.duration; // quqpData.qpParamData.numParticles = 1; // quqpData.qpParamData.duration = 0.1; // quqpData.qpParamData.writeQUICFile(outputDir + "/QP_params.inp"); //dataStructureNames.push_back("qpParams"); // copyFile(quicFilesPath + "QP_particlesize.inp", outputDir + "/QP_particlesize.inp"); workDir.validateOutputDir(dataStructureNames, quqpData); //// outputDir = workDir.outputDir; //// get rid of this now TODO TODO // std::cout<<"the size of the dataStructeNames should be zero "<<dataStructureNames.size()<<std::endl; // std::cin>>pause_temp1; // log.debug( "done with changing the buildings params . Only that should change nothing else and before gpuPlume "); /*if (testing_day) std::cin >> pause_temp1;*/ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////point of execution // std::cout<<"pausing before quicUrb "<<std::endl; //quqpData.qpParamData.numParticles = origNumParticles; // /////////////////////////////////////////////////////////////// // Update the optimization DB with the correct particle // number and timestep values //TODO: no idea what this does // if (avgParam_index == 0) ////Only when the intial run for avgParam_index is run // { // int pause_temp2; // std::cout << "pausing before updateParameter calls" << std::endl; // // std::cin>>pause_temp2; // std::ostringstream name(""); // double value; // ///call update paramIndex // ///update numParticleSet // ////update TimeStepSet; // name.str(""); // name << "Time Step"; // value = quqpData.qpParamData.timeStep; // if (useDB) // optDB_ptr->updateParameterInstance(currProbID, probInstID, name.str(), value); // name.str(""); // name << "Number of Particles"; // value = quqpData.qpParamData.numParticles; // /*if (useDB) // { // optDB_ptr->updateParameterInstance(currProbID, probInstID, name.str(), value); // updateParamInstances(currProbID, probInstID, s); // }*/ // std::cout << "pausing after updateParameter calls" << std::endl; // //std::cin>>pause_temp2; // } // /////////////////////////////////////////////////////////////// // at this point, the cell type structure should have // been output, and thus, we could add it to the // mysql dataset... // don't do this if we don't need it... // optDB_ptr->insertCellTypeData(probInstID, currProbID, outputDir + "/QU_celltype.dat"); //std::cerr << "Done with updates completely" << std::endl; //quqpData.qpParamData.duration = origDuration; // // need to modify the concentration box based on the emitter bounds // /* quqpData.qpParamData.nbx = quqpData.quBuildingData.buildings[ bld2Idx ].xfo - quqpData.quBuildingData.buildings[ bld1Idx ].xfo + quqpData.quBuildingData.buildings[ bld1Idx ].length; quqpData.qpParamData.nby = 50; quqpData.qpParamData.nbz = quqpData.quBuildingData.buildings[ bld2Idx ].height; std::cout << "set conc N to " << quqpData.qpParamData.nbx << " x " << quqpData.qpParamData.nby << " x " << quqpData.qpParamData.nbz << std::endl; quqpData.qpParamData.xbl = quqpData.quBuildingData.buildings[ bld2Idx ].xfo - quqpData.qpParamData.nbx; quqpData.qpParamData.xbu = quqpData.quBuildingData.buildings[ bld2Idx ].xfo; quqpData.qpParamData.ybl = quqpData.quBuildingData.buildings[ bld2Idx ].yfo - quqpData.quBuildingData.buildings[ bld2Idx ].width/2; quqpData.qpParamData.ybu = quqpData.quBuildingData.buildings[ bld2Idx ].yfo + quqpData.quBuildingData.buildings[ bld2Idx ].width/2; quqpData.qpParamData.zbl = 0; quqpData.qpParamData.zbu = quqpData.quBuildingData.buildings[ bld2Idx ].height; std::cout << "set conc dim to [" << quqpData.qpParamData.xbl << ", " << quqpData.qpParamData.ybl << ", " << quqpData.qpParamData.zbl << "] X ]" << quqpData.qpParamData.xbu << ", " << quqpData.qpParamData.ybu << ", " << quqpData.qpParamData.zbu << "]" << std::endl; quqpData.qpSourceData.sources[0].points[0].x = quqpData.quBuildingData.buildings[ bld1Idx ].xfo + quqpData.quBuildingData.buildings[ bld1Idx ].length + 0.5; quqpData.qpSourceData.sources[0].points[1].x = quqpData.quBuildingData.buildings[ bld2Idx ].xfo - 0.5; */ //dataStructureNames.push_back("qpParams"); //std::cout << "the size of " << dataStructureNames.size(); ///This is where we want to augment the data based on et dependency // if (optParams.use_avgParam) // { // augmentDataforAvgParam(quqpData, dataStructureNames, avgParam_index); // // read the /tmp/"concFile"... reduce // } // quqpData.qpParamData.writeQUICFile(outputDir + "/QP_params.inp"); // //workDir.validateOutputDir(dataStructureNames, quqpData); return outputDir; } bool job::setup_environment(string &output_location) { bool environment_ready; this->output_location = output_location; //set the base inner project string baseproj_inner_path = optParams.baseproj_inner_path; log.debug("Base proj inner path", baseproj_inner_path); //Prepare local base directory //make the following code cross platform if (baseproj_inner_path.compare("") != 0) { ///this is the Project file that holds all the quic Data std::string quicFilesPath = baseproj_inner_path + "/"; log.debug(__LINE__, "Begin initializing quicProjec path\n"); //read all quic project data into ququpData quqpData.initialize_quicProjecPath(quicFilesPath); log.debug(__LINE__, "End initializing quicProjec path\n"); log.debug(__LINE__, "Begin building map\n"); //build a map of quicdata quqpData.build_map(); log.debug(__LINE__, "End building map\n"); //creating a copy of default/origional quic project files //TODO mpi might create different processes on same machine so to avoid conflict make dirs with its rank log.debug("creating local copy of project"); log.debug("creating output location", output_location.c_str()); mkdir(output_location.c_str(), S_IRUSR | S_IWUSR | S_IXUSR); log.debug("creating local base copy", (output_location + "/localBaseCopy").c_str()); mkdir((output_location + "/localBaseCopy").c_str(), S_IRUSR | S_IWUSR | S_IXUSR); //there is only one proj file for both inner and outer std::string projFileName = searchForPROJFile(baseproj_inner_path + "/.."); log.debug(__LINE__, "Begin writing out quic files / copying files\n"); log.debug("copying proj file: from ", quicFilesPath + "../" + projFileName, "to", output_location + "/localBaseCopy/local.proj"); copyFile(quicFilesPath + "../" + projFileName, output_location + "/localBaseCopy/local.proj"); //copy the inner directory log.debug("creating local inner dir", (output_location + "/localBaseCopy/local_inner").c_str()); mkdir((output_location + "/localBaseCopy/local_inner").c_str(), S_IRUSR | S_IWUSR | S_IXUSR); ///copy all files to the local thingy . //bruteforce but later on replace quicProject std::string local_inner = output_location + "/localBaseCopy/local_inner/"; log.debug("Local inner path", local_inner); quqpData.quBuildingData.writeQUICFile(local_inner + "/QU_buildings.inp"); copyFile(quicFilesPath + "QU_fileoptions.inp", local_inner + "/QU_fileoptions.inp"); copyFile(quicFilesPath + "QU_landuse.inp", local_inner + "/QU_landuse.inp"); quqpData.quMetParamData.writeQUICFile(local_inner + "/QU_metparams.inp"); quqpData.quSimParamData.writeQUICFile(local_inner + "/QU_simparams.inp"); quqpData.quMetParamData.quSensorData.writeQUICFile(local_inner + "/sensor1.inp"); copyFile(quicFilesPath + projFileName.substr(0, projFileName.length() - 5) + ".info", local_inner + "/local.info"); copyFile(quicFilesPath + "QP_materials.inp", local_inner + "/QP_materials.inp"); copyFile(quicFilesPath + "QP_indoor.inp", local_inner + "/QP_indoor.inp"); quqpData.qpSourceData.writeQUICFile(local_inner + "/QP_source.inp"); copyFile(quicFilesPath + "QP_fileoptions.inp", local_inner + "/QP_fileoptions.inp"); quqpData.qpParamData.writeQUICFile(local_inner + "/QP_params.inp"); quqpData.qpBuildoutData.writeQUICFile(local_inner + "/QP_buildout.inp"); ////////////////////////////////TODO TODO important ask if needed copyFile(quicFilesPath + "QP_particlesize.inp", local_inner + "/QP_particlesize.inp"); // Landuse file log.debug(__LINE__, "End writing out quic files / copying files\n"); ///at this point copy all files // std::cerr<<"The values should have changed by now "<<std::endl; baseproj_inner_path = local_inner; log.debug("searching new local proj file", baseproj_inner_path + "/.."); projFileName = searchForPROJFile(baseproj_inner_path + "/.."); ///as the filename will change the path log.debug("the new BASE project is :", baseproj_inner_path); //workDir.intialRun("/tmp/workingDir",quicFilesPath,quqpData,projFileName); //for each sample in the population create a copy of quic project files to work on and change the appropriate values accroding to the sample //creating a copy of quic project files with optimized values log.debug("Begin workDir initialRun\n"); //Prepare optimizationrun directory workDir.intialRun(output_location + "/optimizingDir", output_location + "/localBaseCopy/local_inner/", quqpData, "local.proj"); log.debug("End workDir initialRun"); environment_ready = true; } else { log.error("Need base proj inner path"); environment_ready = false; } return environment_ready; } std::string job::searchForPROJFile(const std::string &dir) { DIR *directoryPtr = opendir(dir.c_str()); if (directoryPtr == 0) { log.error ("Unable to open directory for search operations."); return ""; } dirent *dirEntryPtr = 0; while ((dirEntryPtr = readdir(directoryPtr)) != 0) { if (dirEntryPtr->d_type != DT_DIR) { //log.debug("Checking file: ", dirEntryPtr->d_name, " for .proj extenstion..."); // only search in the last 5 characters std::string dirEntry_name = dirEntryPtr->d_name; size_t found = dirEntry_name.find( ".proj", dirEntry_name.length() - 5 ); if (found != std::string::npos) { closedir(directoryPtr); return dirEntry_name; } } } return ""; } void job::copyFile(const std::string &sourceFilename, const std::string &destFilename) { int length; char *byteBuffer; std::ifstream is; is.open(sourceFilename.c_str(), ios::binary); if (is.good()) { // get length of file: is.seekg(0, ios::end); length = is.tellg(); is.seekg(0, ios::beg); // allocate memory: byteBuffer = new char[length]; // read data as a block: is.read(byteBuffer, length); is.close(); std::ofstream os; os.open(destFilename.c_str(), ios::binary); os.write(byteBuffer, length); os.close(); } else { std::cerr << "Cannot copyFile: unable to open \"" << sourceFilename << "\"." << std::endl; } delete [] byteBuffer; return; } dependencyOptParam* job::lookupDataInDependencyMap(unsigned int idx) { if (idx >= 0 && idx < optParams.dependencyOptMap.size()) return &(optParams.dependencyOptMap[idx]); else { std::cerr << "**************************************************************ERROR ERROR*******************************" << std::endl; std::cerr << "**************************************************************ERROR ERROR*******************************" << std::endl; return 0; } } namedOptParam* job::lookupDataInMapFromSampleIndex(unsigned int idx) { if (idx >= 0 && idx < optParams.rangeOptMap.size() + optParams.setOptMap.size()) { if (idx >= 0 && idx < optParams.rangeOptMap.size()) return &(optParams.rangeOptMap[idx]); else return &(optParams.setOptMap[idx - optParams.rangeOptMap.size()]); } else { std::cerr << "**************************************************************ERROR ERROR*******************************" << std::endl; std::cerr << "**************************************************************ERROR ERROR*******************************" << std::endl; return 0; } } namedOptParam* job::lookupDataInSolverMap(unsigned int idx) { if (idx >= 0 && idx < optParams.solverOptMap.size()) return &(optParams.solverOptMap[idx]); else { std::cerr << "**************************************************************ERROR ERROR*******************************" << std::endl; std::cerr << "**************************************************************ERROR ERROR*******************************" << std::endl; return 0; } } namedOptParam* job::lookupDataInRangeMap(unsigned int idx) { if (idx >= 0 && idx < optParams.rangeOptMap.size()) return &(optParams.rangeOptMap[idx]); else { std::cerr << "**************************************************************ERROR ERROR*******************************" << std::endl; std::cerr << "**************************************************************ERROR ERROR*******************************" << std::endl; return 0; } } namedOptParam* job::lookupDataInSingleMap(unsigned int idx) { if (idx >= 0 && idx < optParams.singleOptMap.size()) return &(optParams.singleOptMap[idx]); else { std::cerr << "**************************************************************ERROR ERROR*******************************" << std::endl; std::cerr << "**************************************************************ERROR ERROR*******************************" << std::endl; return 0; } } namedOptParam* job::lookupDataInSetMap(unsigned int idx) { if (idx >= 0 && idx < optParams.setOptMap.size()) return &(optParams.setOptMap[idx]); else { std::cerr << "**************************************************************ERROR ERROR*******************************" << std::endl; std::cerr << "**************************************************************ERROR ERROR*******************************" << std::endl; return 0; } } void job::augmentDataFromSingleValues(sivelab::QUICProject &quqpData, std::vector<std::string> &singleValues) //// set to deal with singleValues { // std::cout << "augment every single value into the quqpData total number of single arguments:" << singleValues.size() << std::endl; for (unsigned int i = 0; i < singleValues.size(); i++) { namedOptParam *optData = lookupDataInSingleMap(i); std::string variable_name = optData->description; //std::cout << "checking idx=" << i << ", " << optData->description << std::endl; std::string value = singleValues.at(i); if (variable_name.compare("WindRange") == 0) { std::cerr << "Support for the windRange is only available as a averaging Parameter " << std::endl; std::cerr << "This error is from augmentDataFromSingleValues" << std::endl; exit(1); } quqpData.modify_value(variable_name, value); } } //TODO: might not need this // void augmentDataForSolver(solver *solver_parent) // { // namedOptParam *optData = 0; // std::string variable_name; // std::string value; // std::cout << "augmenting solver data" << std::endl; // for (unsigned int i = 0; i < solverOptMap.size(); i++) // { // optData = lookupDataInSolverMap(i); // std::cout << "checking idx=" << i << ", " << optData->description << " it is a :" << optData->type << ":value is " << optData->value << ":" << std::endl; // variable_name = optData->description; // value = optData->value; // solver_parent->modify_value(variable_name, value); // } // } void job::augmentDataforAvgParam(sivelab::QUICProject &quqpData, std::vector<std::string> &dataStructureNames, int index) ///this is used to change the value for a single sample . i.e the avegraing parameter { if (!optParams.use_avgParam) { std::cerr << "this function should not be calleD" << std::endl; exit(1); } std::cerr << "augment the avg parameter" << std::endl; if (optParams.avgParamName.compare("WindRange") == 0) { quqpData.quMetParamData.quSensorData.direction.setDegrees(optParams.avgParam.at(index), sivelab::MET); dataStructureNames.push_back("quSensor"); } else { std::string value = boost::lexical_cast<string>(optParams.avgParam.at(index)); //get the name index and value call the modify_value add it to datastructrueNames quqpData.modify_value(optParams.avgParamName, value); dataStructureNames.push_back(optParams.avgParamName.substr(0, optParams.avgParamName.find("."))); } } void job::augmentDataFromSample( const sample &s, sivelab::QUICProject &quqpData, std::vector<std::string> &dataStructureNames) //// as of now deas with only range values ///languageMap { //std::cout << "augment every range data available in min max etc " << std::endl; std::string dataStructureName; for (unsigned int i = 0; i < s.size(); i++) { // Look up sample indices and match with population sample data types. sample p = s; namedOptParam *optData; //std::cout << "The sample is :" << p << std::endl; if (i < optParams.rangeOptMap.size()) optData = lookupDataInRangeMap(i); else if ((i - optParams.rangeOptMap.size()) < optParams.setOptMap.size()) optData = lookupDataInSetMap(i - optParams.rangeOptMap.size()); std::string variable_name = optData->description; if (!(variable_name.compare("dummy") == 0)) ///This make sure the variable is not modified { //std::cout << "checking idx=" << i << ", " << optData->description << " it is a :" << optData->type << ":value is " << s[i] << ":" << std::endl; std::string value = boost::lexical_cast<string>(s[i]); quqpData.modify_value(variable_name, value); if (variable_name.compare("WindRange") == 0) { std::cerr << "Cannot have windRange as a sample value for now " << std::endl; std::cerr << "This error is from augmentDataFromSample" << std::endl; exit(1); } ////this is to insert the data into size_t found = variable_name.find("."); if (found != std::string::npos) { dataStructureName = variable_name.substr(0, found); if (std::find(dataStructureNames.begin(), dataStructureNames.end(), dataStructureName) == dataStructureNames.end()) dataStructureNames.push_back(dataStructureName); } else { std::cerr << "illegal variable name " << std::endl; exit(1); } } /* if((variable_name.substr(0,variable_name.find("."))).compare("quBuildings")==0) { std::cout<<"we are trying to access the quBuildings struture and the variable name is"<<variable_name<<std::endl; std::string dataMemberName; dataMemberName=variable_name.substr(variable_name.find('.')+1,variable_name.length()-(variable_name.find('.')+1)); //std::cout<<":"<<dataMemberName<<":"<<(int)s[i]<<std::endl; std::string value = boost::lexical_cast<string>(s[i]); // std::cout<<"before modification x_subdomain_sw :"<<bData.x_subdomain_sw<<" buildings[0].height"<<bData.buildings[19].height<<std::endl; bData.modify_value(dataMemberName,value); // std::cout<<" after modification x_subdomain_sw:"<<bData.x_subdomain_sw<<" buildings[0].height"<<bData.buildings[19].height<<std::endl; } */ } } void job::augmentBuildingDataFromSample( const sample &s, quBuildings &bData ) ///languageMap { std::cout << "augment building data" << std::endl; for (unsigned int i = 0; i < s.size(); i++) { // Look up sample indices and match with population sample data types. namedOptParam *optData = lookupDataInRangeMap(i); std::string variable_name = optData->description; if ((variable_name.substr(0, variable_name.find("."))).compare("quBuildings") == 0) { std::cout << "we are trying to access the quBuildings struture and the variable name is" << variable_name << std::endl; std::string dataMemberName; dataMemberName = variable_name.substr(variable_name.find('.') + 1, variable_name.length() - (variable_name.find('.') + 1)); //std::cout<<":"<<dataMemberName<<":"<<(int)s[i]<<std::endl; std::string value = boost::lexical_cast<string>(s[i]); // std::cout<<"before modification x_subdomain_sw :"<<bData.x_subdomain_sw<<" buildings[0].height"<<bData.buildings[19].height<<std::endl; bData.modify_value(dataMemberName, value); // std::cout<<" after modification x_subdomain_sw:"<<bData.x_subdomain_sw<<" buildings[0].height"<<bData.buildings[19].height<<std::endl; } std::cout << "checking idx=" << i << ", " << optData->description << std::endl; } } /* //langugageMap void augmentBuildingDataFromSample( const sample &s, quBuildings &bData ) { std::cout << "augment building data" << std::endl; for (unsigned int i=0; i<s.size(); i++) { // Look up sample indices and match with population sample data types. namedOptParam *optData = lookupDataInMap(i); std::cout << "checking idx=" << i << ", " << optData->description << std::endl; if (optData->description == "bldxfo") { for (unsigned int bidx=0; bidx<bData.buildings.size(); bidx++) if (bData.buildings[ bidx ].bldNum == optData->idx) { bData.buildings[ bidx ].xfo = (int)s[i]; // TRAINING DATA // export out the wind field information to the training data // trainingModuleExport->appendData(s[i]); break; } } if (optData->description == "bldyfo") { for (unsigned int bidx=0; bidx<bData.buildings.size(); bidx++) if (bData.buildings[ bidx ].bldNum == optData->idx) { bData.buildings[ bidx ].yfo = (int)s[i]; // TRAINING DATA // export out the wind field information to the training data // trainingModuleExport->appendData(s[i]); break; } } // vary the building heights across all buildings if (optData->description == "buildheight") { // set all building heights for (unsigned int bidx=0; bidx<bData.buildings.size(); bidx++) { bData.buildings[ bidx ].height = (int)s[i]; std::cout << "setting building height to " << bData.buildings[bidx].height << std::endl; } // TRAINING DATA // export out the wind field information to the training data // // trainingModuleExport->appendData(s[i]); } if (optData->description == "buildlength") { // set all building lengths for (unsigned int bidx=0; bidx<bData.buildings.size(); bidx++) { bData.buildings[ bidx ].length = (int)s[i]; std::cout << "setting building length to " << bData.buildings[bidx].length << std::endl; } // TRAINING DATA // export out the wind field information to the training data // // trainingModuleExport->appendData(s[i]); } } // once all other parameters are varied, including length, we can // set the separation... std::cout << "completing separation..." << std::endl; for (unsigned int i=0; i<s.size(); i++) { // Look up sample indices and match with population sample data types. namedOptParam *optData = lookupDataInMap(i); std::cout << "checking idx=" << i << ", " << optData->description << std::endl; if (optData->description == "buildsep") { int bld1Idx = bData.findIdxByBldNum(1); assert(bld1Idx != -1); int bld2Idx = bData.findIdxByBldNum(2); assert(bld2Idx != -1); // set the xfo of bld1 based on length of buildings and separation value from sample int bld1xfo = bData.buildings[ bld2Idx ].xfo - bData.buildings[ bld2Idx ].length - (int)s[i]; bData.buildings[ bld1Idx ].xfo = bld1xfo; std::cout << "setting S, making building 1 xfo = " << bld1xfo << std::endl; } } }*/ void job::augmentDataBasedOnDependency(sivelab::QUICProject &quqpData, std::vector<std::string> &dataStructureNames) //// as of now deas with only range values ///languageMap { //std::cout << "augment every dependency the size is " << optParams.dependencyOptMap.size() << std::endl; std::string dataStructureName; for (unsigned int i = 0; i < optParams.dependencyOptMap.size(); i++) { dependencyOptParam *optData = lookupDataInDependencyMap(i); std::string variable_name = optData->variable_name; // std::cout << "checking idx=" << i << ", " << variable_name << std::endl; //std::cout << "opr1 " << optData->operand1 << ":opr2:" << optData->operand2 << "op" << optData->op << std::endl; ///to get the values of the opr1 and opr2 and then perform the corresponding values string op1, op2; double operand1 , operand2, result; char op = optData->op; std::cout << "trying to retrieve value" << optData->operand1 << std::endl; op1 = quqpData.retrieve(optData->operand1); std::cerr << "The retrieved string is " << op1 << std::endl; std::cout << "-----------------stage 2---------------------" << std::endl; op2 = quqpData.retrieve(optData->operand2); std::cout << "---------------------done with stage 3-----------" << std::endl; std::cout << "The values of the opreands after retrieve are " << op1 << ":" << op2 << std::endl; try { operand1 = boost::lexical_cast<double>(op1); operand2 = boost::lexical_cast<double>(op2); } catch (boost::bad_lexical_cast &) { std::cerr << "something wrong with dependency values i.e we cannot change value based on non-numeric data types" << std::endl; exit(1); } if (op == '+') { result = operand1 + operand2; } else if (op == '-') { result = operand1 - operand2; } else if (op == '*') { result = operand1 * operand2; } else { std::cerr << "undefined op in dependency " << std::endl; exit(1); } ///now have to reflect the change std::string newvalue = boost::lexical_cast<std::string>(result);; quqpData.modify_value(variable_name, newvalue); size_t found = variable_name.find("."); if (found != std::string::npos) { dataStructureName = variable_name.substr(0, found); if (std::find(dataStructureNames.begin(), dataStructureNames.end(), dataStructureName) == dataStructureNames.end()) dataStructureNames.push_back(dataStructureName); } else { std::cerr << "illegal variable name " << std::endl; exit(1); } std::cout << "The result: " << result << std::endl; } }<file_sep>/src/utils/opt_params.cpp #include "utils/opt_params.h" #include "boost/algorithm/string.hpp" #include "sstream" using namespace std; using namespace boost; using namespace sivelab; opt_params::opt_params(): log(DEBUG, "opt_parameters") { use_BruteForceSolver = false; useTimeStepSet = false; useNumParticleSet = false; use_Population = false; use_avgParam = false; seednumber = 0; } void opt_params::printOptimizationParams() { unsigned int temp; if (!use_Population) { log.info("PRINTING TESTING VALUES READ IN FROM THE OPTIMIZATION FILE"); if (rangeOptMap.size() == 0) { log.info("Range values absent");//is this even possible? } else { log.info("ALL range values "); } for (temp = 0; temp < rangeOptMap.size(); temp++) { log.info("variable:", rangeOptMap.at(temp).description, "min:", minValues.at(temp), "max:", maxValues.at(temp), "step:", stepValues.at(temp)); } if (setOptMap.size() == 0) { log.info("Set values absent"); } else { log.info("All set Values"); } unsigned int temp2 = 0; for (temp = 0; temp < setOptMap.size(); temp++) { log.info("variable:", setOptMap.at(temp).description, "\t"); for (temp2 = 0; temp2 < setValues.at(temp).size(); temp2++) { log.info(setValues.at(temp).at(temp2), ","); } } } else { log.info("This is the case where hte population has been specified in a file"); } if (singleOptMap.size() == 0) { log.info("Single values absent"); } else { log.info("All Single values "); } for (temp = 0; temp < singleOptMap.size(); temp++) { log.info("variable:", singleOptMap.at(temp).description, "value:", singleValues.at(temp)); } if (dependencyOptMap.size() == 0) { log.info("Dependency parameteres absent"); } else { log.info("ALL Dependency values"); } /* TODO: see if this is useful for (unsigned int i = 0; i < dependencyOptMap.size(); i++) { dependencyOptParam *optData = lookupDataInDependencyMap(i); log.info("dependent parameter =", optData->variable_name, ";value = ", optData->operand1, " ", optData->op, " ", optData->operand2); } */ //exit(1); } bool opt_params::readParams(const std::map<string, map<string, string>> &optParams) { minValues.clear(); maxValues.clear(); stepValues.clear(); singleValues.clear(); setValues.clear(); //aditya did not do this rangeOptMap.clear(); setOptMap.clear(); singleOptMap.clear(); dependencyOptMap.clear(); solverOptMap.clear(); avgParam.clear(); avgParamName = ""; use_avgParam = false; numParticleSet.clear(); timeStepSet.clear(); int namedParamIndex = 0; std::string s1; log.debug("optParams size: ", optParams.size()); for (auto &itr : optParams) { string variable_name = itr.first; map<string, string> values = itr.second; log.debug("Current Parameter", variable_name); if (variable_name.compare("BaseProjectPath") == 0) { baseproj_inner_path = values["rval"]; log.debug("Using ", baseproj_inner_path, " as project source directory."); } else if (variable_name.compare("Solver") == 0 || variable_name.compare("SOLVER") == 0 || variable_name.compare("solver") == 0) ////TODO:make sure to write code for solvers { solver_name = values["rval"]; if (solver_name.compare("BruteForce") == 0 || solver_name.compare("bruteforce") == 0) use_BruteForceSolver = true; log.debug("the value of the solver is ", solver_name) ;//<< "\n" << "the flag for bf is :" << use_BruteForceSolver << "\n"; } else if (!useTimeStepSet && variable_name.compare("TimeStepSet") == 0) { //useTimeStepSet = readTimeStepSet(linebuf, timeStepSet); //did not handle timesteps yet do it!!! } else if (!useNumParticleSet && variable_name.compare("NumParticleSet") == 0) { log.debug("entered particle set"); //useNumParticleSet = readNumParticleSet(linebuf, numParticleSet); //did not handle timesteps yet do it!!! log.debug("exited particle set"); } else if (variable_name.substr(0, variable_name.find('.')).compare("solver") == 0) { std::string inner_var_name; inner_var_name = variable_name.substr(variable_name.find('.') + 1, variable_name.length() - (variable_name.find('.') + 1)); std::cout << "came across solver data" << std::endl; std::cout << variable_name << std::endl << "inner_var_name" << inner_var_name << "\n"; namedOptParam np; np.description = inner_var_name; np.idx = 999999; np.type = "solver"; np.value = values["rval"]; solverOptMap.push_back(np); } else if (variable_name.compare("seed") == 0) { int temp_test;//this for temporarily renaming the files : stringstream a; a.str(values["rval"]); //std::cerr << "this is the seed" << std::endl; //std::cin>>temp_test; a >> seednumber; // std::cin>>temp_test; // exit(1); } /**TODO: Guess we do not need this remove it else if (variable_name.compare("fitness") == 0 || variable_name.compare("Fitness") == 0) { fitness_function = values["rval"]; } **/ else if (variable_name.compare("population") == 0 || variable_name.compare("Population") == 0) { //set the flag , read the file name , Create the required population use_Population = true; //TODO: check this //populationFile = values["rval"]; // population filePopulation ; //population Generation function should be called and now make sure the the required minValues , max Values etc are set . //or defer this generation to the end of reading where we can check to see if there are any range params or etc. And once they are not there generate } else if (variable_name.compare("averaging_param ") == 0 || variable_name.compare("avgParam") == 0) { /* //ABSOLUTELY NO IDEA WHAT THIS CODE IS //set the flag to true //capture the avgParam Name //check to see if the parameter has already been evaluated and then make sure it is removed from all other dataStrucutres like optMaps, minValues , maxValues ,setValues; use_avgParam = true; avgParamName = value; int index_search = -10; ///better way to do it. for (unsigned int i = 0; i < minValues.size() + setValues.size(); i++) { namedOptParam *optParam = lookupDataInMapFromSampleIndex(i); std::cerr << "searching the variable " << optParam->description << std::endl; if (optParam->description.compare(avgParamName) == 0) { std::cerr << "match pound" << std::endl; index_search = i; break; } } if (index_search == -10) { std::cerr << "The avg Parameter has not already been parsed or wrong name " << std::endl; std::cerr << "Should not specify the averaging Parameter without specifying the value upfront" << std::endl; exit(1); } if (index_search < minValues.size()) { std::cerr << "This is a rangeValue " << std::endl; std::cerr << "The index being searched is " << index_search << std::endl; ///to convert the min max and step into a set values double value = minValues.at(index_search); std::cerr << "Trying to evaluate the rangevalue" << std::endl; while (value <= maxValues.at(index_search)) { avgParam.push_back(value); value += stepValues.at(index_search); } std::cerr << "Done with evaluating range Values" << std::endl; ///TODO::Problem with the below approcah can be solved replacing the vector index's with an actual iterator which would be awesome ///Problem with above approach would be we would need different iterators for different vectors which is difficult //temporary fix //if(index_search==0) // index_search=1; minValues.erase(minValues.begin() + index_search); ///all of this as begin points to the first element and index points to the position so -1 to compensate maxValues.erase(maxValues.begin() + index_search); stepValues.erase(stepValues.begin() + index_search); rangeOptMap.erase(rangeOptMap.begin() + index_search); std::cerr << "done with the erase of values:" << std::endl; } else if (index_search - minValues.size() < setValues.size()) { std::cerr << "This is a setValues " << std::endl; avgParam = setValues.at(index_search - minValues.size()); ///this should copy that value ///now to remove it from both setValues and setOpt ///this should get rid of the setValues and the name of the parameter setValues.erase(setValues.begin() + index_search - minValues.size()); setOptMap.erase(setOptMap.begin() + index_search - minValues.size()); } else { std::cerr << "The avg Parameter has not already been parsed or wrong name " << std::endl; std::cerr << "Should not specify the averaging Parameter without specifying the value upfront" << std::endl; exit(1); } for (unsigned int j = 0; j < avgParam.size(); j++) std::cout << avgParam.at(j) << "\t"; std::cerr << "done evaluating the avgParam" << std::endl; printOptimizationParams(); // exit(1); */ } else if (values["rval_type"] == "range") { namedOptParam np; np.description = variable_name; np.idx = 12345; np.type = "rangeValue"; minValues.push_back(atof(values["min"].c_str())); maxValues.push_back(atof(values["max"].c_str())); stepValues.push_back(atoi(values["step"].c_str())); rangeOptMap.push_back(np); namedParamIndex++; } else if (values["rval_type"] == "set") { vector<string> set_values; split(set_values, values["rval"], is_any_of(" \t")); if (set_values.size() == 1) ///a single value { namedOptParam np; np.description = variable_name; np.idx = 1111; np.type = "singleValue"; singleValues.push_back(set_values[0]); singleOptMap.push_back(np); } else { // std::cout<<"the set values"<<std::endl; // std::cout<<"the variable name: "<<variable_name<<std::endl; namedOptParam np; np.description = variable_name; np.idx = 149; np.type = "setValue"; std::vector<double> temp; for (auto &i : set_values) { temp.push_back(atof(i.c_str())); } ///these values should be sorted . That way when we search for them there would not be a problem std::sort(temp.begin(), temp.end()); setValues.push_back(temp); setOptMap.push_back(np); } } else if (values["rval_type"] == "number" || values["rval_type"] == "string") //single value { //if (is_number || (value[0] == '"' && value[value.length() - 1] == '"') ) // { // std::cout<<"this is a numberic || string single Value"<<std::endl; // std::cout<<"Non range value .i.e single value"<<std::endl; namedOptParam np; np.description = variable_name; np.idx = 1111; np.type = "singleValue"; if (values["rval"][0] == '"') { trim_if(values["rval"], is_any_of("'")); } singleValues.push_back(values["rval"]); singleOptMap.push_back(np); } //never end this with a else because there will be some control variables which // we do not take into cosideration like job_type else if (values["rval_type"].find("atomExp") != string::npos) { /// ///if string then should start and end with " " or consider it as a dependency /// then it would have a + - * or / in between and we would have two arguments. std::cout << "we have a dependency " << std::endl; std::string opr1 = values["left_opd"]; std::string opr2 = values["right_opd"]; char op = values["op"][0]; std::cout << "the opr1 op and opr2 " << opr1 << ":" << op << ":" << opr2 << std::endl; dependencyOptParam np; np.idx = 4444; np.variable_name = variable_name; np.operand1 = opr1; np.operand2 = opr2; np.op = op; dependencyOptMap.push_back(np); //exit(1); } } // if we made it to this location, no time step was specified; as // such we will use the default time steps in the qpParams, but we // do need at least one entry in our set to enter the sim loop if (useTimeStepSet == false) timeStepSet.push_back(-99); // add default value of -99 as default for using the sim data if (useNumParticleSet == false) numParticleSet.push_back(-99); // add default value of -99 as default for using the sim data log.debug("Range map values: ", rangeOptMap.size()); std::vector<namedOptParam>::iterator x; // for (unsigned int wIdx=0; wIdx<windAngle.size(); wIdx++) // std::cout << "Wind Angle: " << windAngle[wIdx] << std::endl; int temp1 = 0; for (x = rangeOptMap.begin(); x != rangeOptMap.end(); x++) { log.debug((*x).description); log.debug("min : step : max ", minValues[temp1], " ", stepValues[temp1], " ", maxValues[temp1]); temp1++; } log.debug("-------------------Solver Parameters -------------------"); if (solverOptMap.size() == 0) { log.debug("**NONE"); } for (x = solverOptMap.begin(); x != solverOptMap.end(); x++) { log.debug((*x).description, "\t=", (*x).value); } //std::cerr<<"want to see if it is working or not "<<std::endl; //printOptimizationParams( minValues,maxValues,stepValues,setValues,singleValues); ///write a function that will print everything with the correct names " /** might wan to look at this sometime in future **/ /**TODO check where to place this if (use_Population) { ///This means we have a population file and now range values and set values should be zero or else its an erro. if ((setValues.size() + minValues.size()) != 0) { std::cerr << "When ever a population file has been specified the optFile should not contain any range or set Value parameters other than a avgParam " << std::endl; exit(1); } populationGenerator filepop; filePopulation = filepop.generate_fromfile(populationFile, rangeOptMap); //To intialize the population into filePopulation and then changing one of the optMaps so that it is pushed into the list and all other functions can work } **/ // bool use_Population = false; //population filePopulation ; //std::string populationFile; //printOptimizationParams(); }<file_sep>/src/utils/include/directory.h #ifndef DIRECTORY_H #define DIRECTORY_H 1 ///:version1 working withougt including into the program directory : ///:adi expecting this to manage writing files to a temp direcotry and manage . This should be able to get me a new directory with a give sample. #include <vector> #include <iostream> #include <fstream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cassert> #include <algorithm> #include <signal.h> #include <math.h> #include <string> #include <limits> #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> #include "logger/logger.h" #include "namedOptParam.h" //class nameoptclass #include "quicutil/QUICProject.h" //#include "quqpdata.h" ///adi: rewrote the classes samples.h : now including population.h instead of that :D #include "population.h" //#include "population.h" using namespace std; struct file { std::string fileName; ///the name of the file bool isValid; ////dirty bit file() { /* std::cout<<"this should be called"<<std::endl<<"------------------------"; fileName="hello"; isValid=false; std::cout<<"the fineName is "<<fileName<<std::endl; */ } file(std::string file) { fileName = file; isValid = false; } }; class directory { private: logger log; public: std::vector<file*> dir; std::string outputDir; std::string projFileName; int counter; //see if its possible to compare two samples there by storing one here we can eliminate one of them :D using sample we can change the required dirty bits or else initially every data that needs to change is changed void intialRun(std::string outdir, std::string quicPath, sivelab::QUICProject &quqpData, std::string projfileName1); directory(); ~directory(); //directory(std::string,std::string,quqpdata &,std::string); void copyFile(const std::string &, const std::string &); // void augmentBuildingDataFromSample( const sample &s, quBuildings &bData ); // void validate_QU_buildings(const sample &, sivelab::QUICProject &); // void validate_sensor1(sivelab::QUICProject &, const float); // void validate_QP_source(sivelab::QUICProject &); // void validate_QP_params(sivelab::QUICProject &); // void validateDir(const sample &, sivelab::QUICProject &, const float); // void createOutputDir(const sample &, std::string outDirPath, sivelab::QUICProject &, std::string projFileName1, string QUICURB_EXE_PATH, string QUICPLUME_EXE_PATH, bool useNumParticleSet, bool useTimeStepSet, int numParticle, float timeStep); // void createOutputDirectory(float windAngle, std::vector<std::string> &dataStructureNames, sivelab::QUICProject &quqpData, string QUICURB_EXE_PATH, string QUICPLUME_EXE_PATH, bool useNumParticleSet, bool useTimeStepSet, int numParticle, float timeStep); void validateOutputDir(std::vector<std::string> &, sivelab::QUICProject &quqpData); /////TODO": Note the wind the number of particles and the time step are random . Think about which ones are needed }; #endif <file_sep>/tests/utils/test_population_gen.cpp #include "utils/population_gen.h" #include "utils/population.h" #include "gtest/gtest.h" #include "gmock/gmock.h" using namespace std; using namespace sivelab; using ::testing::ElementsAre; //populationGenerator use maxValues, minValues, stepValues, setValues to generate population //As of now it seems to ignore single values? TEST(PopulationGeneration, populationTest){ std::vector<double> minValues={1, 2.5, 1}; std::vector<double> maxValues={10, 10, 10}; std::vector<int> stepValues={1, 2, 7}; std::vector<std::vector<double> > setValues={{1, 2}, {3, 4, 5}}; populationGenerator popgen(minValues, maxValues, stepValues, setValues); population pop = popgen.generate_all_pop(); long expectedPopulationSize = (long)((10-1)/1 + 1) * (long)((10-2.5)/2 + 1) * (long)((10-1)/7 + 1) * 2 * //2 elemnts in set 1 3 ; //3 elements in set 2 ASSERT_EQ(expectedPopulationSize, pop.size()); //Please manually check if the population generated makes sense //cout<<pop; }<file_sep>/src/utils/FitnessCache.cpp #include "utils/FitnessCache.h" void FitnessCache::addToCache( const sample &s, double f ) { sampleFitness sf; sf.sample.resize(s.size()); std::cout << "FitnessCache: adding sample ("; for (unsigned int i=0; i<s.size(); i++) { sf.sample[i] = (int)s[i]; std::cout << (int)s[i]; if (i < s.size()-1) std::cout << ", "; } std::cout << ") to cache with fitness=" << f << std::endl; sf.fitness = f; m_cache.push_back(sf); } bool FitnessCache::inCache( const sample &s, double& fitness ) { for (unsigned int i=0; i<m_cache.size(); i++) { bool sampleResult = true; // assume we find it, reject if we don't for (unsigned int sIdx=0; sIdx<s.size(); sIdx++) { if (m_cache[i].sample[sIdx] != (int)s[sIdx]) { sampleResult = false; break; } } if (sampleResult) { fitness = m_cache[i].fitness; std::cout << "Cache Hit: cache size = " << m_cache.size() << ", found sample in cache, fitness = " << fitness << std::endl; std::cout << "\tCache Hit: Sample = ("; for (unsigned int sIdx=0; sIdx<s.size(); sIdx++) std::cout << s[sIdx] << ((sIdx==s.size()-1) ? "" : ", "); std::cout << ")" << std::endl; return true; } } return false; } void FitnessCache::clearCache() ////function to clear the cache { m_cache.clear(); }
8878af5b69547b4ff82e09556bd532be24333b12
[ "CMake", "Markdown", "Makefile", "C++", "Shell" ]
53
C++
UMD-SIVE-Lab/qesmpi
7076c8bdd8c3848a8a65078baba9a45b410299a1
211bf493c944199c41f93eac3124d567796f7872
refs/heads/master
<file_sep><?php $cabecalho_title = "Produto da Mirror Fashion"; include ("cabecalho.php"); /*incuir o cabeçario*/ ?> <section id="main"> <!-- Conteúdo principal --> <div class="container destaque"> <section class="busca"> <h2>Busca</h2> <form id="form-busca" action="#"> <input type="search" name="q" id="q"> <input type="image" src="imagem/busca.png"> </form> </section><!-- fim .busca --> <section class="menu-departamentos"> <h2>Departamentos</h2> <nav> <ul> <li> <a href="#">Blusas e Camisas</a> <ul> <li><a href="#">Manga curta</a></li> <li><a href="#">Manga comprida</a></li> <li><a href="#">Camisa social</a></li> <li><a href="#">Camisa casual</a></li> </ul> </li> <li><a href="#">Calças</a></li> <li><a href="#">Saias</a></li> <li><a href="#">Vestidos</a></li> <li><a href="#">Sapatos</a></li> <li><a href="#">Bolsas e Carteiras</a></li> <li><a href="#">Acessórios</a></li> </ul> </nav> </section><!-- fim .menu-departamentos --> <img src="imagem/destaque-home.png" alt="Promoção: Big City Night"> <a href="#" class="pause"></a> </div><!-- fim .container .destaque --> </section> <script type="text/javascript" src="js/home.js"></script><!-- link do java script --> <section id="destaques"> <!-- Painéis com destaques --> <div class="container paineis"> <!-- os paineis de novidades e mais vendidos entrarão aqui dentro --> <section class="painel novidades"> <h2>Novidades</h2> <ol> <!-- primeiro produto --> <li> <a href="produto.html"> <figure> <img src="imagem/produtos/miniatura1.png"> <figcaption>Fuzz Cardigan por R$ 129,90</figcaption> </figure> </a> </li> <li> <a href="produto.html"> <figure> <img src="imagem/produtos/miniatura1.png"> <figcaption>Fuzz Cardigan por R$ 129,90</figcaption> </figure> </a> </li> <li> <a href="produto.html"> <figure> <img src="imagem/produtos/miniatura1.png"> <figcaption>Fuzz Cardigan por R$ 129,90</figcaption> </figure> </a> </li> <li> <a href="produto.html"> <figure> <img src="imagem/produtos/miniatura1.png"> <figcaption>Fuzz Cardigan por R$ 129,90</figcaption> </figure> </a> </li> <!-- coloque mais produtos aqui! --> </ol> </section> <section class="painel mais-vendidos"> <h2>Mais Vendidos</h2> <ol> <!-- coloque vários produtos aqui --> <li> <a href="produto.html"> <figure> <img src="imagem/produtos/miniatura1.png"> <figcaption>Fuzz Cardigan por R$ 129,90</figcaption> </figure> </a> </li><li> <a href="produto.html"> <figure> <img src="imagem/produtos/miniatura1.png"> <figcaption>Fuzz Cardigan por R$ 129,90</figcaption> </figure> </a> </li><li> <a href="produto.html"> <figure> <img src="imagem/produtos/miniatura1.png"> <figcaption>Fuzz Cardigan por R$ 129,90</figcaption> </figure> </a> </li><li> <a href="produto.html"> <figure> <img src="imagem/produtos/miniatura1.png"> <figcaption>Fuzz Cardigan por R$ 129,90</figcaption> </figure> </a> </li> </ol> </section> </div> </section> <footer> <!-- Conteúdo do rodapé --> <div class="container"> <!-- logo rodape--> <img src="imagem/logo-rodape.png" alt="Logo Mirror Fashion"> <!-- link rede social --> <ul class="social"> <li><a href="http://facebook.com/mirrorfashion">Facebook</a></li> <li><a href="http://twitter.com/mirrorfashion">Twitter</a></li> <li><a href="http://plus.google.com/mirrorfashion">Google+</a></li> </ul> </div> </footer> </body> </html><file_sep># Estudos estudo de front-end, da apostila da caelum (http://www.caelum.com.br/apostila-html-css-javascript/). <file_sep><?php $cabecalho_css = '<link rel="stylesheet" href="css/produto.css">'; /*fazendo o include dinamico*/ $cabecalho_title = "Produto da Mirror Fashion"; include ("cabecalho.php"); /*incuir o cabešario*/ ?> <body> </body> <?php include 'rodape.php'; /* incluir rodape*/?> </html><file_sep><?php $cabecalho_css = '<link rel="stylesheet" href="css/sobre.css">'; /*fazendo o include dinamico*/ $cabecalho_title = "Sobre da Mirror Fashion"; include ("cabecalho.php"); /*incuir o cabeçario*/ ?> <body> <!-- cabeçario --> <p>Mais informações <a href="#info">aqui</a>.</p> <p>Conteúdo da página...</p> <section> <article> <p>A Mirror Fashion A <strong>Mirror Fashion</strong> é a maior empresa comércio eletrônico no segmento de moda em todo o mundo. Fundada em 1932 ha <?php print date("Y")-1932; ?> anos, possui filiais em 124 países, sendo líder de mercado com mais de 90% de participação em 118 deles.Conheça também nossa <a href="#historia">história</a> e nossos <a href="#diferenciais">diferenciais</a> Nosso centro de distribuição fica em Jacarezinho, no Paraná. De lá, saem 48 aviões que distribuem nossos produtos às casas do mundo todo. <em>Nosso centro de distribuição:</em> <figure> <img alt="" src="imagem/centro-distribuicao.png"> <figcaption>centro de distribuiçao Mirror Fashion</figcaption> </figure> Compre suas roupas e acessórios na Mirror Fashion. Acesse nossa loja ou entre em contato se tiver dúvidas. Conheça também nossa história e nossos diferenciai</p> <h2 id="historia">História</h2> <figure id="familia-pelho"> <img alt="" src="imagem/familia-pelho.jpg"> <figcaption>Familia pelho</figcaption> </figure> <p>A fundação em 1932 ocorreu no momento da descoberta econônica do interior do Paraná. A família Pelho, tradicional da região, investiu todas as suas economias nessa nova iniciativa, revolucionária para a época. O fundador <NAME>, dotado de particular visão administrativa, guiou os negócios da empresa durante mais de 50 anos, muitos deles ao lado de seu filho <NAME>, atual CEO. O nome da empresa é inspirado no nome da família. O crescimento da empresa foi praticamente instantâneo. Nos primeiros 5 anos, já atendia 18 países. Bateu a marca de 100 países em apenas 15 anos de existência. Até hoje, já atendeu 740 milhões de usuários diferentes, em bilhões de diferentes pedidos. O crescimento em número de funcionários é também assombroso. Hoje, é a maior empregadora do Brasil, mas mesmo após apenas 5 anos de sua existência, já possuía 30 mil funcionários. Fora do Brasil, há 240 mil funcionários, além dos 890 mil brasileiros nas instalações de Jacarezinho e nos escritórios em todo país. Dada a importância econômica da empresa para o Brasil, a família Pelho já recebeu diversos prêmios, homenagens e condecorações. Todos os presidentes do Brasil já visitaram as instalações da Mirror Fashion, além de presidentes da União Européia, Ã�sia e o secretário-geral da ONU.</p> <h2 id="diferenciais">Diferenciais</h2> <ul> <li>Menor preço do varejo, garantido</li> <li>Se você achar uma loja mais barata, leva o produto de graça</li> <li>Se você achar uma loja mais barata, leva o produto de graça</li> <li>Se você achar uma loja mais barata, leva o produto de graça</li> <li>Se você achar uma loja mais barata, leva o produto de graça</li> <li>Se você achar uma loja mais barata, leva o produto de graça</li> </ul> <h2 id="info">Mais informações sobre o assunto:</h2> <p>Informações...</p> </article> </section> Acesse <a href="index.html">nossa loja</a> <?php include 'rodape.php'; /* incluir rodape*/?> </body> </html>
598ae5779678c141e4ade2a80632fc4ab9bc2fc0
[ "Markdown", "PHP" ]
4
PHP
matheusCalaca/Estudos
86a08ddf3a972d68bb2d5b0334192697c39d76d4
f025421e08600c6fa95f45758533956aa5a879ea
refs/heads/master
<file_sep>KDDC="/data/deploy/recommender/shell/lib/kddc-1.0.0.jar" path="`dirname $0`" INPUT_PATH=$1 OUTPUT_PATH=$2 if [ ! -n "$INPUT_PATH" -o ! -n "$OUTPUT_PATH" ];then echo 'Usage: ./UserProfileJob.sh INPUT_PATH OUTPUT_PATH ' exit 0 else echo "INPUT_PATH: $INPUT_PATH, OUTPUT_PATH:$OUTPUT_PATH" fi $path/Job.sh com.snowballfinance.kddc.job.UserProfileJob --input "$1" --output "$2" <file_sep>package com.snowballfinance.kddc.job; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.FloatWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.util.ToolRunner; import org.apache.log4j.Logger; import org.apache.mahout.common.AbstractJob; public class UserProfileJob extends AbstractJob{ private static Logger logger = Logger.getLogger(UserProfileJob.class); public static void main(String[] args) { int res = 0; try { res = ToolRunner.run(new Configuration(), new ItemSimilarityJob(), args); } catch (Exception e) { logger.error("UserProfileJob Tool Runner Err.", e); } System.exit(res); } @Override public int run(String[] arg0) throws Exception { addInputOption(); addOutputOption(); Job simJob = prepareJob(getInputPath(), getOutputPath(), UserProfileMapper.class, LongWritable.class, Text.class, UserProfileSimReducer.class, Text.class, FloatWritable.class); simJob.setCombinerClass(UserProfileSimReducer.class); simJob.waitForCompletion(true); return 0; } private static class UserProfile { public long getUid() { return uid; } public void setUid(long uid) { this.uid = uid; } public long getBirthYear() { return birthYear; } public void setBirthYear(long birthYear) { this.birthYear = birthYear; } public int getSexuality() { return sexuality; } public void setSexuality(int sexuality) { this.sexuality = sexuality; } public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } public int getTweetCount() { return tweetCount; } public void setTweetCount(int count) { this.tweetCount = count; } private long uid; private long birthYear; private int sexuality; private int tweetCount; private String tags; } private static List<UserProfile> userProfileList = new LinkedList<UserProfile>(); public static class UserProfileMapper extends Mapper<LongWritable, Text, Text, FloatWritable> { private static float computeSocre(String srctags, String desttags) { float score = 0f; try { String[] srcTags = srctags.split(";"); String[] destTags = desttags.split(";"); Set<String> srcKeyWordSet = new HashSet<String>(Arrays.asList(srcTags)); Set<String> destKeyWordSet = new HashSet<String>(Arrays.asList(destTags)); int totalcount = srcKeyWordSet.size() + destKeyWordSet.size(); srcKeyWordSet.retainAll(destKeyWordSet); int commoncount = srcKeyWordSet.size(); return totalcount == 0 ? 0 : commoncount / (totalcount - commoncount); } catch (java.lang.ArrayIndexOutOfBoundsException e) { logger.error("UserProfileMapper computeSocre Error. SRC:" + srctags + ", DEST:" + desttags, e); } return score; } @Override protected void map(LongWritable ikey, Text ival, Context context) throws IOException, InterruptedException { String[] keyValues = ival.toString().split("\t"); String uid = keyValues[0]; String year = keyValues[1]; String sexuality = keyValues[2]; String tweetCount = keyValues[3]; String tags = keyValues[4]; for(UserProfile profile : userProfileList) { float score = computeSocre(tags, profile.getTags()); context.write(new Text(uid + " " + profile.getUid()), new FloatWritable(score)); } UserProfile curProfile = new UserProfile(); curProfile.setUid(Long.valueOf(uid)); curProfile.setTags(tags); userProfileList.add(curProfile); } } public static class UserProfileSimReducer extends Reducer<Text, FloatWritable, Text, FloatWritable> { @Override protected void reduce(Text key, Iterable<FloatWritable> scores, Context ctx) throws IOException, InterruptedException { Iterator<FloatWritable> iter = scores.iterator(); float score = iter.next().get(); ctx.write(key, new FloatWritable(score)); String[] keyPairs = key.toString().split(" "); ctx.write(new Text(keyPairs[1] + " " + keyPairs[0]), new FloatWritable(score)); } } } <file_sep>import os,sys def linecount_wc(filename): return int(os.popen('wc -l ' + filename).read().split()[0]) def split_file(outdir, filename): count = 0 linecount = linecount_wc(filename) lines = [] rawFile = open(filename, 'r') fileidx = 0 output = open(outdir +"/input"+ str(fileidx) , 'w') while 1: line = rawFile.readline() if line: count = count + 1 lines.append(line) if count < linecount / 8: output.write(line) elif count == linecount / 8: output.write(line) fileidx = fileidx + 1 count = 0 output.close() output = open(outdir + "/input"+ str(fileidx) , 'w') continue else: break rawFile.close() def main(): if len(sys.argv) < 2: print u'please input file name\n' else: outdir = os.path.dirname(sys.argv[0]) split_file(outdir, sys.argv[1]) main() <file_sep>KDDC_LIB_HOME="/data/deploy/kddc/webapp/WEB-INF/lib" KDDC_JOB="/data/deploy/kddc/shell/lib/kddc-1.0.0.jar" HADOOP_HOME="/data/hadoop" CLASS=$1 if [ ! -n "$KDDC_JOB" -o ! -n "$CLASS" ];then echo 'Usage: ./Job.sh JobName ClassName Params ' exit 0 else echo "JobName: $KDDC_JOB" fi KDDC_CLASSPATH="" for f in $KDDC_LIB_HOME/*.jar; do echo "Add Lib to ClassPath : $f" if [ "$KDDC_CLASSPATH" == "" ] ; then KDDC_CLASSPATH=$f else KDDC_CLASSPATH=${KDDC_CLASSPATH}:$f; fi done echo -e "KDDC_CLASSPATH:$KDDC_CLASSPATH" if [ "$HADOOP_CLASSPATH" != "" ] ; then HADOOP_CLASSPATH=${KDDC_CLASSPATH}:${HADOOP_CLASSPATH} else HADOOP_CLASSPATH=$KDDC_CLASSPATH fi echo -e "HADOOP_CLASSPATH:$HADOOP_CLASSPATH" export HADOOP_CLASSPATH exec "$HADOOP_HOME/bin/hadoop" jar $KDDC_JOB $CLASS "$@" <file_sep>package com.snowballfinance.kddc.job; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Comparator; import org.apache.hadoop.io.WritableComparable; @SuppressWarnings("rawtypes") public class StrFloatPair implements WritableComparable { private String candidate; private float score; // required methods public StrFloatPair() { candidate = ""; score = 0f; } public String getCandidate() { return candidate; } public void setCandidate(String candidate) { this.candidate = candidate; } public float getScore() { return score; } public void setScore(float score) { this.score = score; } public StrFloatPair(final String candidate, final float score) { this.candidate = candidate; this.score = score; } @Override public void readFields(DataInput in) throws IOException { candidate = in.readLine(); score = in.readFloat(); } @Override public void write(DataOutput out) throws IOException { out.writeChars(candidate + "\n"); // "/n" needed here so that the readLine() calls in readFields will // read the correct input out.writeFloat(score); } @Override public int compareTo(Object arg0) { StrFloatPair pair = (StrFloatPair) arg0; if(arg0 == null) return 1; else if(this.score == pair.score) return 0; else if(this.score > pair.score) return -1; else return 1; } static public class StrFloatPariComp implements Comparator<StrFloatPair> { @Override public int compare(StrFloatPair o1, StrFloatPair o2) { if(o1 != null && o2 == null) return 1; else if(o1 == null && o2 != null) return -1; else return o1.compareTo(o2); } } } <file_sep>xueqiu ====== Knowledge discovery<file_sep><?xml version="1.0" encoding="UTF-8"?> <project name="kddc" default="deploy" basedir="."> <property environment="env" /> <property name="deploy.base.dir" value="/data/deploy/${ant.project.name}" /> <property name="build.version" value="1.0.0" /> <property name="bin.dir" value="bin" /> <property name="lib.dir" value="lib" /> <property name="java.src.dir" value="src/main/java" /> <property name="java.test.dir" value="src/test/java" /> <!-- <property name="conf.src.dir" value="src/main/conf" /> --> <property name="shell.src.dir" value="shell" /> <property name="build.base.dir" value="build" /> <property name="build.bin.dir" value="${build.base.dir}/shell/bin" /> <property name="build.lib.dir" value="${build.base.dir}/shell/lib" /> <property name="build.log.dir" value="${build.base.dir}/log" /> <property name="build.view.web.dir" value="${build.base.dir}/webapp" /> <property name="build.inf.web.dir" value="${build.view.web.dir}/WEB-INF" /> <property name="build.bin.web.dir" value="${build.inf.web.dir}/classes" /> <property name="build.lib.web.dir" value="${build.inf.web.dir}/lib" /> <property name="branch.name" value="${branch}" /> <path id="classpath"> <fileset dir="${lib.dir}"> <include name="**/*.jar" /> </fileset> </path> <target name="init"> <mkdir dir="${build.bin.dir}" /> <mkdir dir="${build.lib.dir}" /> <mkdir dir="${build.log.dir}" /> <mkdir dir="${build.inf.web.dir}" /> <mkdir dir="${build.bin.web.dir}" /> <mkdir dir="${build.lib.web.dir}" /> </target> <target name="compile" depends="clean,init"> <javac debug="on" debuglevel="lines,vars,source" srcdir="${java.src.dir}" destdir="${build.bin.web.dir}" encoding="UTF-8" nowarn="true" source="1.6" target="1.6"> <classpath refid="classpath" /> </javac> <jar destfile="${build.lib.dir}/${ant.project.name}-${build.version}.jar"> <manifest> <attribute name="Built-By" value="<NAME>" /> <attribute name="Specification-Title" value="Snowball Community Platform" /> <attribute name="Specification-Vendor" value="Snowball Finance" /> <attribute name="Implementation-Version" value="${build.version}" /> <attribute name="Implementation-Vendor" value="Snowball Kddc" /> </manifest> <fileset dir="${build.bin.web.dir}"> <include name="com/**/*" /> </fileset> </jar> </target> <target name="build" depends="compile"> <mkdir dir="${bin.dir}" /> <copy todir="${build.bin.dir}"> <fileset dir="${bin.dir}"> <include name="**/*" /> </fileset> <fileset dir="${shell.src.dir}"> <include name="**/*" /> </fileset> </copy> <!-- <copy todir="${build.bin.web.dir}"> <fileset dir="${conf.src.dir}"> <include name="**/*" /> </fileset> </copy> --> <copy todir="${build.lib.web.dir}"> <fileset dir="${lib.dir}"> <include name="**/*" /> <exclude name="compile" /> <exclude name="compile/**/*" /> </fileset> </copy> </target> <target name="deploy" depends="build"> <delete dir="${deploy.base.dir}/shell" /> <delete dir="${deploy.base.dir}/webapp" /> <copy todir="${deploy.base.dir}"> <fileset dir="${build.base.dir}"> <include name="**/*" /> </fileset> </copy> <chmod dir="${deploy.base.dir}/shell/bin" perm="ugo+rx" includes="**/*" /> </target> <target name="clean"> <delete dir="${build.base.dir}" /> </target> <!-- JUnit --> <target name="test"> <delete dir="${test.dir}" /> <mkdir dir="${test.dir}" /> <javac debug="on" debuglevel="lines,vars,source" srcdir="${java.test.dir}" destdir="${test.dir}" encoding="UTF-8" nowarn="true" source="1.6" target="1.6"> <classpath refid="classpath" /> <classpath location="${build.bin.web.dir}" /> </javac> <junit printsummary="yes" haltonfailure="no"> <formatter type="xml" /> <classpath refid="classpath" /> <classpath> <pathelement location="${test.dir}" /> <pathelement location="${build.bin.web.dir}" /> </classpath> <batchtest fork="no" todir="${test.dir}"> <fileset dir="${java.test.dir}"> <include name="**/*Test*.java" /> </fileset> </batchtest> </junit> </target> </project>
d0d9ef47b450310880a5eb6054884b8636ff27c8
[ "Markdown", "Java", "Python", "Ant Build System", "Shell" ]
7
Shell
huobao36/xueqiu
f2f8f19d719ae04117660b1b757bc8df0746fe01
65d33cc5a5d3b828acba8255810aec2b999551d8
refs/heads/master
<repo_name>erhnml/React-Redux-Movie-Searcher<file_sep>/src/components/form/Alert.js import React from 'react' import { PropTypes } from 'prop-types'; const Alert = (props) => { const { message, bgColor, show } = props; if(!show) { return null } return ( <div className="alert" style={{background: `${bgColor}`}}> { message } </div> ) } Alert.propTypes = { message: PropTypes.string.isRequired, bgColor: PropTypes.string.isRequired, show: PropTypes.bool.isRequired } export default Alert;<file_sep>/src/views/MovieDetail.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import { firestoreConnect } from 'react-redux-firebase' import { getFirestore } from 'redux-firestore' import { compose } from 'redux'; import Header from '../components/layout/Header'; import Loading from '../components/Loading'; import Rating from '../components/Rating'; import noImage from '../images/no-image.png'; class MovieDetail extends Component { constructor(props) { super(props); this.state = { movie: null, loading: false, comment: '' } } componentDidMount() { this.setState({loading: true}) fetch(`https://api.themoviedb.org/3/movie/${this.props.match.params.id}?api_key=deace0e77639b6480a76cc82cbb9c226`) .then(res => res.json()) .then(movie => this.setState({movie, loading: false})) } handleClick = () => { const { comment } = this.state; const { auth, match } = this.props; const firestore = getFirestore(); const data = { comment, user: auth.email, movie: match.params.id, date: new Date().getTime() } firestore.collection("comments").add(data) this.setState({comment: ''}) } render() { const { movie, loading, comment } = this.state; const { auth, match, allComments } = this.props; const comments = allComments ? allComments.filter(comment => comment.movie === match.params.id) : null; const commentList = comments ? comments.sort(function(a, b){return b.date-a.date}).map((comment, index) => ( <div key={index} className="movie-detail__container__comment__list__item"> <p className="movie-detail__container__comment__list__item__text">{comment.comment}</p> <p className="movie-detail__container__comment__list__item__author">{[...comment.user].reduce((name, letter, index) => index < 5 ? name += letter : name += '*','')}</p> </div> )) : <Loading /> ; return ( <div className="movie-detail"> <Header /> { !loading && movie ? <div className="movie-detail__container"> <div className="movie-detail__container__wrapper"> <div className="movie-detail__container__wrapper__right"> <img src={movie.poster_path == null ? noImage : `https://image.tmdb.org/t/p/w500${movie.poster_path}`} alt="" className="movie-detail__container__wrapper__right__poster"/> </div> <div className="movie-detail__container__wrapper__left"> <h2 className="movie-detail__container__wrapper__left__title">{movie.original_title} ({ movie.release_date.split('-')[0] })</h2> <p className="movie-detail__container__wrapper__left__overview">{movie.overview}</p> <p className="movie-detail__container__wrapper__left__genres">Genres: {movie.genres.map((genre, index) => index !== (movie.genres.length - 1) ? genre.name + ', ' : genre.name )}</p> <p className="movie-detail__container__wrapper__left__time">Runtime: {movie.runtime}m</p> <div className="movie-detail__container__wrapper__left__bottom"> <Rating strokeWidth="10" sqSize="60" percentage={movie.vote_average} /> <div className="movie_detail__container__wrapper__left__bottom__fav"></div> </div> </div> </div> <div className="movie-detail__container__comment"> { auth.uid ? <div> <textarea name="" id="" cols="30" rows="5" className="movie-detail__container__comment__text" value={comment} onChange={(e) => this.setState({comment: e.target.value})} placeholder="Comment"></textarea> <button className="movie-detail__container__comment__add" onClick={this.handleClick}>Add Comment</button> </div> : null } <div className="movie-detail__container__comment__list"> <h3 className="movie-detail__container__comment__list__title"> { comments ? `Comments(${comments.length})` : null}</h3> { commentList } </div> </div> </div> : <Loading /> } </div> ) } } const mapStateToProps = (state, props) => { return { auth: state.firebase.auth, allComments: state.firestore.ordered.comments } } export default compose( firestoreConnect((props) => { return [ { collection: 'comments', } ] }), connect(mapStateToProps, '') )(MovieDetail)<file_sep>/src/views/SignUp.js import React, { Component } from 'react' import { connect } from 'react-redux'; import { Redirect } from 'react-router-dom'; import { signUp } from '../store/actions/auth'; import Header from '../components/layout/Header'; import FormInput from '../components/form/FormInput'; import Alert from '../components/form/Alert'; import SpinnerButton from '../components/form/SpinnerButton'; class SignUp extends Component { constructor(props) { super(props); this.state = { email: '', password: '' } } handleChange = (e) => { this.setState({ [e.target.type]: e.target.value }) } handleClik = () => { const { signUp } = this.props; signUp(this.state); } render() { const { email, password } = this.state; const { loading, AuthError } = this.props.auth; const { uid } = this.props.firebase.auth; if(uid) { return ( <Redirect to="/" /> ) } return ( <div className="sign-up"> <Header /> <div className="sign-up__container"> <h3 className="sign-up__container__title">Sign Up</h3> <FormInput type="email" placeholder="email" value={email} onChange={this.handleChange} /> <FormInput type="password" placeholder="<PASSWORD>" value={password} onChange={this.handleChange} onKeyPressEnter={this.handleClick}/> <SpinnerButton spinner={loading} title="SignUp" onClick={this.handleClik}/> <Alert message={AuthError !== null && AuthError.SignUpError ? AuthError.SignUpError.message : null} show={ AuthError !== null && AuthError.SignUpError ? true : false} bgColor="red"/> </div> </div> ) } } const mapStateToProps = (state) => { return { auth: state.auth, firebase: state.firebase } } const mapDispatchToProps = (dispatch) => { return { signUp: (user) => dispatch(signUp(user)) } } export default connect(mapStateToProps,mapDispatchToProps)(SignUp);<file_sep>/src/views/Home.js import React, { Component } from 'react'; //Components import Header from '../components//layout/Header'; import MovieCard from '../components/layout/MovieCard'; import SearchInput from '../components/SearchInput'; import Loading from '../components/Loading'; class App extends Component { constructor(props) { super(props); this.state = { query: '', movies: [], loading: false } } componentDidMount() { this.fetchDiscovery() .then((res) => res.json()) .then((data) => this.setState({movies: data.results, loading: false})); } handleChange = (e) => { const query = e.target.value; if(query === '' ) { this.fetchDiscovery() .then((res) => res.json()) .then(data => this.setState({movies: data.results, loading: false})) } else { this.setState({loading: true}) fetch(`https://api.themoviedb.org/3/search/movie?api_key=deace0e77639b6480a76cc82cbb9c226&query=${query}`) .then(res => res.json()) .then(data => this.setState({movies: data.results, loading: false})) } } fetchDiscovery = () => { this.setState({loading: true}) return fetch('https://api.themoviedb.org/3/discover/movie?api_key=deace0e77639b6480a76cc82cbb9c226&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1') } render() { const { movies, loading } = this.state; const movieList = movies.length > 0 ? movies.map( movie => <MovieCard key={movie.id} movie={movie} /> ) : "no results found"; return ( <div className="home"> <Header /> <SearchInput onChangeText={this.handleChange} /> { loading ? <Loading /> : <div className="card-wrapper"> {movieList} </div> } </div> ); } } export default App; <file_sep>/src/views/SignIn.js import React, { Component } from 'react' import { connect } from 'react-redux'; import { Redirect, Link } from "react-router-dom"; import { signIn } from '../store/actions/auth'; import Header from '../components/layout/Header'; import SpinnerButton from '../components/form/SpinnerButton'; import FormInput from '../components/form/FormInput'; import Alert from '../components/form/Alert'; class SignIn extends Component { constructor(props) { super(props); this.state = { email: '', password: '' } } handleChange = (e) => { this.setState({[e.target.type]: e.target.value}); } handleClick = () => { const { signIn } = this.props; signIn(this.state) } render() { const { auth, AuthError, loading } = this.props; const { email, password } = this.state; if(auth.uid) { return ( <Redirect to="/" /> ) } return ( <div className="sign-in"> <Header /> <div className="sign-in__container"> <h3 className="sign-in__container__title">Sign In</h3> <FormInput type="email" value={email} placeholder="email" onChange={this.handleChange} /> <FormInput type="password" value={password} placeholder="<PASSWORD>" onChange={this.handleChange} onKeyPressEnter={this.handleClick} /> <SpinnerButton title="Sign In" onClick={this.handleClick} spinner={loading}/> <p>Don't have an account? <Link to="/signup">Sign up</Link></p> <Alert message={AuthError !== null && AuthError.SignInError ? AuthError.SignInError.message : '' } show={AuthError !== null && AuthError.SignInError ? true : false} bgColor="red" /> </div> </div> ) } } const mapStateToPorps = (state) => { return { AuthError: state.auth.AuthError, auth: state.firebase.auth, loading: state.auth.loading } } const mapDispatchToProps = (dispatch) => { return { signIn: (user) => dispatch(signIn(user)) } } export default connect(mapStateToPorps, mapDispatchToProps)(SignIn); <file_sep>/src/components/layout/MovieCard.js import React from 'react' import { Link } from "react-router-dom"; import noImage from '../../images/no-image.png'; const MovieCard = (props) => { const { movie } = props; const poster = movie.poster_path == null ? noImage : `https://image.tmdb.org/t/p/w500${movie.poster_path}`; return ( <div className="card"> <h3 className="card__title">{ movie.original_title } <span className="card_lang"> | { movie.original_language }</span> ({ movie.release_date.split('-')[0] })</h3> <img className="card__poster" src={poster} alt=""/> <div className="card__bottom"> <div className="card__bottom__rating">{movie.vote_average}</div> <Link to={`/detail/${movie.id}`} className="card__bottom__movie-detail">Detail</Link> </div> </div> ) } export default MovieCard;<file_sep>/src/components/form/FormInput.js import React from 'react' import PropTypes from 'prop-types'; const FormInput = (props) => { const { placeholder, type, onChange, onKeyPressEnter,value } = props; return ( <input type={type} placeholder={placeholder} value={value} onChange={onChange} onKeyPress={(e) => e.key === 'Enter' ? onKeyPressEnter() : null} className="form-input" /> ) } FormInput.propTypes = { type: PropTypes.string.isRequired, placeholder:PropTypes.string, value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, onKeyPressEnter: PropTypes.func, className: PropTypes.string } export default FormInput;<file_sep>/src/components/layout/Header.js import React, { Component } from 'react'; import { Link } from "react-router-dom"; import { connect } from 'react-redux'; import { signOut } from '../../store/actions/auth'; import logo from '../../images/logo.png'; class Header extends Component { render() { const { auth, signOut } = this.props; return ( <div className="header"> <Link className="header__logo" to="/"> <img className="header__logo__img" src={logo} alt=""/> <h3 className="header__logo__text">Movie Searcher</h3> </Link> <div className="header__sign"> { auth.uid ? <div> <h4 className="header__sign__name">{auth.email}</h4> <button className="header__sign__button" onClick={signOut}>Sign Out</button> </div> : <Link to="/login" className="header__sign__button">Sign In</Link> } </div> </div> ) } } const mapStateToProps = (state) => { return { auth: state.firebase.auth } } const mapStateToDispatch = (dispatch) => { return { signOut: () => dispatch(signOut()) } } export default connect(mapStateToProps, mapStateToDispatch)(Header);<file_sep>/src/config/fbConfig.js import firebase from 'firebase'; import 'firebase/auth'; import 'firebase/firestore'; const config = { apiKey: "<KEY>", authDomain: "movies-search-e69c9.firebaseapp.com", databaseURL: "https://movies-search-e69c9.firebaseio.com", projectId: "movies-search-e69c9", storageBucket: "movies-search-e69c9.appspot.com", messagingSenderId: "619786290433" }; firebase.initializeApp(config); firebase.firestore(); export default firebase;<file_sep>/src/store/actions/auth.js export const signIn = (user) => { return (dispatch, getState, {getFirebase}) => { const firebase = getFirebase(); dispatch({type: 'LOADING_TRUE'}) firebase.auth().signInWithEmailAndPassword(user.email, user.password) .then(() => { dispatch({type: 'LOGIN_SUCCESS'}) }) .catch((err) => { dispatch({type: 'LOGIN_ERROR', err}) }) } } export const signOut = () => { return (dispatch, getState, {getFirebase}) => { const firebase = getFirebase(); firebase.auth().signOut() .then(() => { dispatch({type: 'LOGOUT_SUCCESS'}) }) } } export const signUp = (user) => { return (dispatch, getState, {getFirebase}) => { const firebase = getFirebase(); dispatch({type: 'LOADING_TRUE'}) firebase.auth().createUserWithEmailAndPassword(user.email, user.password) .then(() => { dispatch({type: 'SIGNUP_SUCCESS'}) }) .catch((err) => { dispatch({type: 'SIGNUP_ERROR', err}) }) } }
909910d70ab5f7260298000c1609db7e95e29431
[ "JavaScript" ]
10
JavaScript
erhnml/React-Redux-Movie-Searcher
9e0ab4179ef372c1209481889b3fdc08da4e61d1
493d3e21590d040230961e572740a2bb6280bb4e
refs/heads/master
<file_sep>package com.vuclip.premiumengg.automation.subscription_service.tests; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.common.RabbitMQConnection; import com.vuclip.premiumengg.automation.subscription_service.common.models.ConfirmSync; import com.vuclip.premiumengg.automation.subscription_service.common.models.ConfirmSyncData; import com.vuclip.premiumengg.automation.subscription_service.common.models.ConfirmSyncQueue; import com.vuclip.premiumengg.automation.subscription_service.common.models.GetUserStatusResponse; import com.vuclip.premiumengg.automation.subscription_service.common.models.StateTransitionResponse; import com.vuclip.premiumengg.automation.subscription_service.common.utils.SDBHelper; import com.vuclip.premiumengg.automation.subscription_service.common.utils.SHelper; import com.vuclip.premiumengg.automation.subscription_service.common.utils.SRabitMessageHelper; import com.vuclip.premiumengg.automation.subscription_service.common.utils.SRedisUtils; import com.vuclip.premiumengg.automation.subscription_service.common.utils.SUtils; import com.vuclip.premiumengg.automation.subscription_service.common.utils.SValidationHelper; import com.vuclip.premiumengg.automation.subscription_service.common.utils.TestDataCreator; import com.vuclip.premiumengg.automation.utils.AppAssert; import com.vuclip.premiumengg.automation.utils.DBUtils; import io.restassured.response.Response; public class ConfirmSyncTest { private static Logger logger = Log4J.getLogger("ConfirmSyncTest"); Map<String, String> query = new HashMap<String, String>(); @DataProvider(name = "confirmSyncSuccessData") public Iterator<Object[]> confirmSyncSuccessData() { List<ConfirmSyncData> confirmSuccess = new ArrayList<ConfirmSyncData>(); confirmSuccess.add(ConfirmSyncData.CONFIRMISNOTCLOSED); confirmSuccess.add(ConfirmSyncData.CONFIRMISCLOSED); confirmSuccess.add(ConfirmSyncData.CONFIRMCONSENTCHRGCLOSED); Collection<Object[]> dp = new ArrayList<Object[]>(); for (ConfirmSyncData sbData : confirmSuccess) { dp.add(new Object[] { sbData }); } return dp.iterator(); } @Test(dataProvider = "confirmSyncSuccessData", groups = { "positive" }) public void confirmSyncSuccessTest(ConfirmSyncData confirmSuccess) { try { logger.info("Starting================> Confirm Sync Success Tests"); ConfirmSync confirmSync = TestDataCreator.getConfirmSyncSuccessTest(confirmSuccess); Response response = SHelper.confirmApi(confirmSync); SValidationHelper.validate_ss_api_response(response); SValidationHelper.validate_ss_jsonBody(response, "userStatus.subscriptionStatus", confirmSuccess.getSubscriptionStatus()); StateTransitionResponse stateTransition = response.getBody().as(StateTransitionResponse.class); logger.info("DB Validation"); String userSubAuthKey = "USERID_" + confirmSync.getProductId() + "_" + confirmSync.getUserId(); SDBHelper.validateTable("user_subscription", confirmSync.getUserId(), confirmSync.getProductId(), confirmSync.getPartnerId(), confirmSync.getNextBillingDate(), userSubAuthKey, confirmSuccess.getSubscriptionStatus()); AppAssert.assertEqual( SDBHelper.validateDates("user_subscription", "user_id=" + confirmSync.getUserId(), "start_date", "end_date"), SDBHelper.getValidityDaysFromBillingPackage(confirmSuccess.getValidityColumn(), confirmSuccess.getSubscriptionBillingCode()), confirmSuccess.getValidityColumn() + " days is added to the required user"); logger.info("Redis Validation"); query.put("userid", confirmSync.getUserId()); Response getUserResponse = SHelper.getUserStatus(query); SValidationHelper.validate_ss_api_response(getUserResponse); GetUserStatusResponse getUserStatusResponse = getUserResponse.getBody().as(GetUserStatusResponse.class); SValidationHelper.validateGetUserStatusGeneric(getUserStatusResponse, stateTransition.getUserStatus().getStartDate(), stateTransition.getUserStatus().getEndDate(), confirmSync.getNextBillingDate(), confirmSync.getChargedPrice(), stateTransition.getUserStatus().getActivationDate(), null, stateTransition.getUserStatus().getSummary(), confirmSuccess.getSubscriptionStatus(), confirmSuccess.getSubscriptionBillingCode(), confirmSuccess.getChargedBillingCode(), stateTransition.getUserStatus().getCountry(), confirmSuccess.getUserSource(), confirmSuccess.getMode(), stateTransition.getUserStatus().isPaid()); } catch (Exception e) { e.printStackTrace(); AppAssert.assertTrue(false); } } @DataProvider(name = "confirmSyncNotSuccessData") public Iterator<Object[]> confirmSyncNotSuccessData() { List<ConfirmSyncData> confirmNotSuccess = new ArrayList<ConfirmSyncData>(); confirmNotSuccess.add(ConfirmSyncData.CONFIRMFAILURE); confirmNotSuccess.add(ConfirmSyncData.CONFIRMERROR); confirmNotSuccess.add(ConfirmSyncData.CONFIRMCANCELED); Collection<Object[]> dp = new ArrayList<Object[]>(); for (ConfirmSyncData sbData : confirmNotSuccess) { dp.add(new Object[] { sbData }); } return dp.iterator(); } @Test(dataProvider = "confirmSyncNotSuccessData", groups = { "positive" }) public void confirmSyncNotSuccessTest(ConfirmSyncData confirmSuccess) { try { logger.info("Starting================> Confirm Sync Not Success Tests"); ConfirmSyncQueue confirmSync = TestDataCreator.getConfirmSyncQueueData(confirmSuccess); RabbitMQConnection.getRabbitTemplate().convertAndSend("core_subscription", confirmSync); SRabitMessageHelper.addMessageToQueue(confirmSync); logger.info("Redis Validation"); String userSubAuthKey = "USERID_" + confirmSync.getProductId() + "_" + confirmSync.getUserId(); logger.info("Check Key Not Present in Redis"); AppAssert.assertTrue(!SRedisUtils.checkKey(userSubAuthKey)); logger.info("DB Validation"); SDBHelper.verifyNoActivityRecordPresent("user_subscription", SUtils.productId, SUtils.productId, confirmSuccess.getUserId()); } catch (Exception e) { e.printStackTrace(); AppAssert.assertTrue(false); } } @BeforeClass(alwaysRun = true) public void cleanUp() { DBUtils.cleanTable("user_subscription", "product_id =" + SUtils.productId + " and partner_id =" + SUtils.productId); } } <file_sep>package com.vuclip.premiumengg.automation.schedular_service.common.utils; import com.vuclip.premiumengg.automation.schedular_service.common.models.SchedulerSaveProductRequest; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.models.PublishConfigRequest; import com.vuclip.premiumengg.automation.utils.ObjectMapperUtils; public class SSUtils { public static String jobName = "job"; public static String groupName = "auto-job"; public static PublishConfigRequest productConfig = null; /** * @param JsonFileName * @param type * @return */ public static <T> T loadJson(String JsonFileName, Class<T> type) { return ObjectMapperUtils .readValue("src/test/resources/configurations/schedular-service/request/" + JsonFileName, type); } public static SchedulerSaveProductRequest getConfigurationMessage(String activityType, int productId, int partnerId, int freInMinute) { SchedulerSaveProductRequest configurationMessage = loadJson("configurationMessage.json", SchedulerSaveProductRequest.class); configurationMessage.getRetry().get(0).setActivityType(activityType); configurationMessage.getRetry().get(0).setProductId(productId); configurationMessage.getRetry().get(0).setPartnerId(partnerId); configurationMessage.getRetry().get(0).setSchedulingFrequencyInMinutes(freInMinute); return configurationMessage; } public static SchedulerSaveProductRequest getConfigurationMessage(String activityType, int productId, int partnerId, int freInMinute, String country) { SchedulerSaveProductRequest configurationMessage = loadJson("configurationMessage.json", SchedulerSaveProductRequest.class); configurationMessage.getRetry().get(0).setActivityType(activityType); configurationMessage.getRetry().get(0).setProductId(productId); configurationMessage.getRetry().get(0).setPartnerId(partnerId); configurationMessage.getRetry().get(0).setSchedulingFrequencyInMinutes(freInMinute); configurationMessage.getRetry().get(0).setCountryCode(country); return configurationMessage; } public static SchedulerSaveProductRequest getConfigurationMessage(String activityType) { SchedulerSaveProductRequest configurationMessage = loadJson("configurationMessage.json", SchedulerSaveProductRequest.class); configurationMessage.getRetry().get(0).setActivityType(activityType); return configurationMessage; } } <file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.*; import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"productId", "countries"}) @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString public class ProductCountryMapping { @JsonProperty("productId") private Integer productId; @JsonProperty("countries") private List<Country> countries = null; } <file_sep>csServer=http://10.11.100.8:8084/configuration-service dbServer=10.11.100.8 dbPort=3306 dbName=configuration_service dbUser=root dbPassword=<PASSWORD> rabbitMQServer=10.11.100.8 rabbitMQPort=5672 rabbitMQUser=jenkins rabbitMQPassword=<PASSWORD> uBSMockURL=10.11.100.8:7007/ubs-mock-services <file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.common.RabbitMQConnection; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.models.*; import com.vuclip.premiumengg.automation.utils.AppAssert; import com.vuclip.premiumengg.automation.utils.DBUtils; import com.vuclip.premiumengg.automation.utils.ObjectMapperUtils; import org.apache.commons.lang3.RandomUtils; import org.apache.log4j.Logger; import org.springframework.amqp.core.Message; import java.util.HashMap; import java.util.Map; import java.util.Random; public class SASUtils { public static int productId; public static int partnerId; public static String countryCode; public static PublishConfigRequest productConfig = null; public static String billingCode = null; /** * @param JsonFileName * @param type * @return */ public static <T> T loadJson(String JsonFileName, Class<T> type) { return ObjectMapperUtils.readValue( "src/test/resources/configurations/scheduled-activity-service/request/" + JsonFileName, type); } public static PublishConfigRequest generateSaveProductConfig(Integer productId, Integer partnerId, String activityType) { PublishConfigRequest publishConfigRequest = loadJson("publishConfig.json", PublishConfigRequest.class); publishConfigRequest.getProduct().setProductId(productId); publishConfigRequest.getProductPartnerMappings().get(0).setProductId(productId); publishConfigRequest.getProductPartnerMappings().get(0).setPartnerId(partnerId); publishConfigRequest.getProductCountryMapping().setProductId(productId); publishConfigRequest.getAdNetworkNotifications().get(0).setPartnerId(partnerId); publishConfigRequest.getAdNetworkNotifications().get(0).setProductId(productId); publishConfigRequest.getActivityFlows().get(0).setPartnerId(partnerId); publishConfigRequest.getPricePoints().get(0).setProductId(productId); publishConfigRequest.getPricePoints().get(0).setPartnerId(partnerId); publishConfigRequest.getRetry().get(0).setProductId(productId); publishConfigRequest.getRetry().get(0).setPartnerId(partnerId); publishConfigRequest.getBlackouts().get(0).setPartnerId(partnerId); publishConfigRequest.getBlackouts().get(0).setProductId(productId); publishConfigRequest.getRetry().get(0).setActivityType(activityType); return publishConfigRequest; } public static SchedulerRequest generateSchedulerRequest(Integer productId, Integer partnerId, String actionTable) { SchedulerRequest schedulerRequest = loadJson("scheduler.json", SchedulerRequest.class); schedulerRequest.setActivityType(actionTable.toUpperCase()); schedulerRequest.setProductId(productId); schedulerRequest.setPartnerId(partnerId); return schedulerRequest; } public static UserSubscriptionRequest generateUserSubscriptionRequest(Integer productId, Integer partnerId, String activityType, String previousSubscriptionState, String currentSubscriptionState, String transactionState, String actionType, long subscriptionId) { UserSubscriptionRequest userSubscriptionRequest = loadJson("userSubscription.json", UserSubscriptionRequest.class); // userSubscriptionRequest.getActivityInfo().setActivityType(activityType); // userSubscriptionRequest.getActivityInfo().setPreviousSubscriptionState(previousSubscriptionState); // userSubscriptionRequest.getActivityInfo().setCurrentSubscriptionState(currentSubscriptionState); // userSubscriptionRequest.getActivityEvent().setTransactionState(transactionState); // userSubscriptionRequest.getActivityInfo().setActionType(actionType); // userSubscriptionRequest.getSubscriptionInfo().setSubscriptionId(subscriptionId); // userSubscriptionRequest.getActivityEvent().setSubscriptionId(subscriptionId); // userSubscriptionRequest.getSubscriptionInfo().setProductId(productId); // userSubscriptionRequest.getSubscriptionInfo().setPartnerId(partnerId); // userSubscriptionRequest.getActivityEvent().setPartnerId(partnerId); // userSubscriptionRequest.getActivityEvent().setProductId(productId); // userSubscriptionRequest.getSubscriptionInfo().setChargedBillingCode(billingCode); // userSubscriptionRequest.getSubscriptionInfo().setSubscriptionBillingCode(billingCode); // userSubscriptionRequest.getActivityEvent().setAttemptedBillingCode(billingCode); // userSubscriptionRequest.getActivityEvent().setChargedBillingCode(billingCode); // userSubscriptionRequest.getActivityEvent().setRequestedBillingCode(billingCode); String r=String.valueOf(RandomUtils.nextLong(1000000000L, 9000000000L)); userSubscriptionRequest.getUserInfo().setMsisdn(r); userSubscriptionRequest.getUserInfo().setUserId(r); userSubscriptionRequest.getActivityEvent().setMsisdn(r); userSubscriptionRequest.getActivityEvent().setUserId(r); userSubscriptionRequest.getActivityInfo().setActivityType(activityType); userSubscriptionRequest.getActivityInfo().setCurrentSubscriptionState(currentSubscriptionState); userSubscriptionRequest.getActivityInfo().setActionType(actionType); userSubscriptionRequest.getSubscriptionInfo().setSubscriptionId(subscriptionId); userSubscriptionRequest.getSubscriptionInfo().setProductId(productId); userSubscriptionRequest.getSubscriptionInfo().setPartnerId(partnerId); userSubscriptionRequest.getSubscriptionInfo().setCountry("IN"); userSubscriptionRequest.getSubscriptionInfo().setChargedBillingCode(billingCode); userSubscriptionRequest.getSubscriptionInfo().setSubscriptionBillingCode(billingCode); userSubscriptionRequest.getActivityEvent().setSubscriptionId(subscriptionId); userSubscriptionRequest.getActivityEvent().setPartnerId(partnerId); userSubscriptionRequest.getActivityEvent().setProductId(productId); userSubscriptionRequest.getActivityEvent().setTransactionState(transactionState); userSubscriptionRequest.getActivityEvent().setAttemptedBillingCode(billingCode); userSubscriptionRequest.getActivityEvent().setChargedBillingCode(billingCode); userSubscriptionRequest.getActivityEvent().setRequestedBillingCode(billingCode); DateTimeUtil.getDateByAddingValidity(userSubscriptionRequest.getSubscriptionInfo().getNextBillingDate(), 1, TimeUnitEnum.DAY.name()); return userSubscriptionRequest; } public static UserSubscriptionRequest generateUserSubscriptionRequest(Integer productId, Integer partnerId, String activityType, String currentSubscriptionState, String transactionState, String actionType, long subscriptionId) { UserSubscriptionRequest userSubscriptionRequest = loadJson("userSubscription.json", UserSubscriptionRequest.class); // userSubscriptionRequest.getActivityInfo().setActivityType(activityType); // // userSubscriptionRequest.getActivityInfo().setPreviousSubscriptionState(previousSubscriptionState); // userSubscriptionRequest.getActivityInfo().setCurrentSubscriptionState(currentSubscriptionState); // userSubscriptionRequest.getActivityEvent().setTransactionState(transactionState); // userSubscriptionRequest.getActivityInfo().setActionType(actionType); // userSubscriptionRequest.getSubscriptionInfo().setSubscriptionId(subscriptionId); // userSubscriptionRequest.getActivityEvent().setSubscriptionId(subscriptionId); // userSubscriptionRequest.getSubscriptionInfo().setProductId(productId); // userSubscriptionRequest.getSubscriptionInfo().setPartnerId(partnerId); // userSubscriptionRequest.getActivityEvent().setPartnerId(partnerId); // userSubscriptionRequest.getActivityEvent().setProductId(productId); // userSubscriptionRequest.getSubscriptionInfo().setChargedBillingCode(billingCode); //// userSubscriptionRequest.getSubscriptionInfo().setFallbackBillingCode(billingCode); // userSubscriptionRequest.getSubscriptionInfo().setSubscriptionBillingCode(billingCode); // userSubscriptionRequest.getActivityEvent().setAttemptedBillingCode(billingCode); // userSubscriptionRequest.getActivityEvent().setChargedBillingCode(billingCode); // userSubscriptionRequest.getActivityEvent().setRequestedBillingCode(billingCode); String r=String.valueOf(RandomUtils.nextLong(1000000000L, 9000000000L)); userSubscriptionRequest.getUserInfo().setMsisdn(r); userSubscriptionRequest.getUserInfo().setUserId(r); userSubscriptionRequest.getActivityEvent().setMsisdn(r); userSubscriptionRequest.getActivityEvent().setUserId(r); userSubscriptionRequest.getActivityInfo().setActivityType(activityType); userSubscriptionRequest.getActivityInfo().setCurrentSubscriptionState(currentSubscriptionState); userSubscriptionRequest.getActivityInfo().setActionType(actionType); userSubscriptionRequest.getSubscriptionInfo().setSubscriptionId(subscriptionId); userSubscriptionRequest.getSubscriptionInfo().setProductId(productId); userSubscriptionRequest.getSubscriptionInfo().setPartnerId(partnerId); userSubscriptionRequest.getSubscriptionInfo().setCountry("IN"); userSubscriptionRequest.getSubscriptionInfo().setChargedBillingCode(billingCode); userSubscriptionRequest.getSubscriptionInfo().setSubscriptionBillingCode(billingCode); userSubscriptionRequest.getActivityEvent().setSubscriptionId(subscriptionId); userSubscriptionRequest.getActivityEvent().setPartnerId(partnerId); userSubscriptionRequest.getActivityEvent().setProductId(productId); userSubscriptionRequest.getActivityEvent().setTransactionState(transactionState); userSubscriptionRequest.getActivityEvent().setAttemptedBillingCode(billingCode); userSubscriptionRequest.getActivityEvent().setChargedBillingCode(billingCode); userSubscriptionRequest.getActivityEvent().setRequestedBillingCode(billingCode); DateTimeUtil.getDateByAddingValidity(userSubscriptionRequest.getSubscriptionInfo().getNextBillingDate(), 1, TimeUnitEnum.DAY.name()); return userSubscriptionRequest; } public static UserSubscriptionRequest generateUserSubscriptionRequest(Integer productId, Integer partnerId, String activityType, String currentSubscriptionState, String transactionState, String actionType, long subscriptionId, long nextBillingDate) { UserSubscriptionRequest userSubscriptionRequest = loadJson("userSubscription.json", UserSubscriptionRequest.class); // userSubscriptionRequest.getSubscriptionInfo().getPartnerId(); // userSubscriptionRequest.getSubscriptionInfo().getCountry(); // userSubscriptionRequest.getSubscriptionInfo().getSubscriptionId(); // userSubscriptionRequest.getSubscriptionInfo().getEndDate(); // userSubscriptionRequest.getSubscriptionInfo().getNextBillingDate(); // userSubscriptionRequest.getSubscriptionInfo().getSubscriptionBillingCode(); // // // userSubscriptionRequest.getActivityInfo().getActivityType(); // userSubscriptionRequest.getActivityInfo().getCurrentSubscriptionState(); // // userSubscriptionRequest.getActivityEvent().getTransactionState(); // // userSubscriptionRequest.getUserInfo().isFreeTrialUser(); // userSubscriptionRequest.getEventInfo().getLogTime().getTime(); // userSubscriptionRequest.getUserInfo().getUserId(); String r=String.valueOf(RandomUtils.nextLong(1000000000L, 9000000000L)); userSubscriptionRequest.getUserInfo().setMsisdn(r); userSubscriptionRequest.getUserInfo().setUserId(r); userSubscriptionRequest.getActivityEvent().setMsisdn(r); userSubscriptionRequest.getActivityEvent().setUserId(r); userSubscriptionRequest.getActivityInfo().setActivityType(activityType); userSubscriptionRequest.getActivityInfo().setCurrentSubscriptionState(currentSubscriptionState); userSubscriptionRequest.getActivityInfo().setActionType(actionType); userSubscriptionRequest.getSubscriptionInfo().setSubscriptionId(subscriptionId); userSubscriptionRequest.getSubscriptionInfo().setProductId(productId); userSubscriptionRequest.getSubscriptionInfo().setPartnerId(partnerId); userSubscriptionRequest.getSubscriptionInfo().setCountry("IN"); userSubscriptionRequest.getSubscriptionInfo().setChargedBillingCode(billingCode); userSubscriptionRequest.getSubscriptionInfo().setSubscriptionBillingCode(billingCode); userSubscriptionRequest.getSubscriptionInfo().setNextBillingDate(nextBillingDate); // userSubscriptionRequest.getSubscriptionInfo().setEndDate(); userSubscriptionRequest.getActivityEvent().setSubscriptionId(subscriptionId); userSubscriptionRequest.getActivityEvent().setPartnerId(partnerId); userSubscriptionRequest.getActivityEvent().setProductId(productId); userSubscriptionRequest.getActivityEvent().setTransactionState(transactionState); userSubscriptionRequest.getActivityEvent().setAttemptedBillingCode(billingCode); userSubscriptionRequest.getActivityEvent().setChargedBillingCode(billingCode); userSubscriptionRequest.getActivityEvent().setRequestedBillingCode(billingCode); DateTimeUtil.getDateByAddingValidity(userSubscriptionRequest.getSubscriptionInfo().getNextBillingDate(), 1, TimeUnitEnum.DAY.name()); userSubscriptionRequest.getSubscriptionInfo().setNextBillingDate(nextBillingDate); userSubscriptionRequest.getActivityEvent().setNextBillingDate(nextBillingDate); return userSubscriptionRequest; } public static Object[][] getALLActivityType() { return new Object[][]{{ActivityType.ACTIVATION_TYPE}, {ActivityType.ACTIVATION_RETRY_TYPE}, {ActivityType.DEACTIVATION}, {ActivityType.DEACTIVATION_RETRY_TYPE}, {ActivityType.FREETRIAL_RENEWAL_TYPE}, {ActivityType.RENEWAL_TYPE}, {ActivityType.SYSTEM_CHURN_TYPE}, {ActivityType.WINBACK_TYPE}, {ActivityType.RENEWAL_RETRY_TYPE}}; } public static PublishConfigRequest changeBatchSize(PublishConfigRequest publishConfigRequest, int batchSize) { for (int i = 0; i < publishConfigRequest.getRetry().size(); i++) { publishConfigRequest.getRetry().get(i).setBatchSize(batchSize); } return publishConfigRequest; } public static PublishConfigRequest changeActionDefaultEiligible(PublishConfigRequest publishConfigRequest, Boolean isActionDefaultEiligible) { for (int i = 0; i < publishConfigRequest.getRetry().size(); i++) { publishConfigRequest.getRetry().get(i).setActionDefaultEiligible(isActionDefaultEiligible); } return publishConfigRequest; } public static PublishConfigRequest changeRetryCount(PublishConfigRequest publishConfigRequest, int maxRetryCount) { for (int i = 0; i < publishConfigRequest.getRetry().size(); i++) { publishConfigRequest.getRetry().get(i).setMaxRetryCount(maxRetryCount); } return publishConfigRequest; } public static void executeActivityFlows(Integer productId, Integer partnerId, int subscriptionId, String countryCode, String eventActionType, String activityType, String currentSubscriptionState, String transactionState, String actionTable, String beforeSchedularStatus, String afterSchedularStatus, String afteNewEventStatus, String queueName, String newEventActionType, String newActivityType, String newCurrentSubscriptionState, String newTransactionState, String newActionTable, String newBeforeSchedularStatus, String newAfterSchedularStatus, String newQueueName) throws Exception { SASHelper sasHelper = new SASHelper(); Logger logger = Log4J.getLogger("SAS FLOW"); logger.info("=========>First time user subscription event getting trigger"); UserSubscriptionRequest uSRequest = SASUtils.generateUserSubscriptionRequest(productId, partnerId, activityType, "", currentSubscriptionState, transactionState, eventActionType, subscriptionId); SASValidationHelper.validate_sas_api_response(sasHelper.userSubscription(uSRequest)); SASDBHelper.showAllActivityTableData("first", String.valueOf(subscriptionId)); // String expectedActivityType = SASDBHelper.showAllActivityTableData("FIRST ", // String.valueOf(subscriptionId)); logger.info("=========>First event: Verify DB after event trigger"); Map<String, String> expectedRecords = new HashMap<String, String>(); expectedRecords.put("status", beforeSchedularStatus); expectedRecords.put("product_id", String.valueOf(productId)); expectedRecords.put("partner_id", String.valueOf(partnerId)); expectedRecords.put("subscription_id", String.valueOf(subscriptionId)); expectedRecords.put("country_code", countryCode); expectedRecords.put("date", String.valueOf(uSRequest.getSubscriptionInfo().getNextBillingDate())); SASValidationHelper.validateTableRecord(DBUtils .getRecord(actionTable, "subscription_id = " + subscriptionId + " and product_id = " + productId + " and partner_id=" + partnerId + " and date=" + uSRequest.getSubscriptionInfo().getNextBillingDate()) .get(0), expectedRecords); logger.info("=========>First Event: scheduale call "); SASValidationHelper.validate_schedular_api_response( sasHelper.scheduler(SASUtils.generateSchedulerRequest(productId, partnerId, actionTable))); SASDBHelper.showAllActivityTableData("second", String.valueOf(subscriptionId)); logger.info("=========>First Event: Vefiry DB After Schedular Call "); expectedRecords.put("status", afterSchedularStatus); SASValidationHelper.validateTableRecord(DBUtils.getRecord(actionTable, "subscription_id = " + subscriptionId + " and product_id=" + productId + " and partner_id=" + partnerId) .get(0), expectedRecords); logger.info("=========>First Event: Queue verification Name: " + RabbitUtil.getQueueName(productId, partnerId, countryCode, queueName)); Message message = RabbitUtil.receive(RabbitMQConnection.getRabbitTemplate(), RabbitUtil.getQueueName(productId, partnerId, countryCode, queueName), 10000); // RabbitMQConnection.getRabbitTemplate() // .receive(productId + "_" + partnerId + "_" + queueName.toUpperCase() + // "cccc", 25000); SASValidationHelper.validateQueueMessage( ObjectMapperUtils.readValueFromString(new String(message.getBody()), SASQueueResponse.class), productId, partnerId, subscriptionId, countryCode, actionTable.toUpperCase()); logger.info("=========>Second time user subscription event getting trigger"); UserSubscriptionRequest newSubscriptionRequest = SASUtils.generateUserSubscriptionRequest(productId, partnerId, newActivityType.toUpperCase(), currentSubscriptionState, newCurrentSubscriptionState, newTransactionState, newEventActionType, subscriptionId); newSubscriptionRequest.getSubscriptionInfo().setNextBillingDate(DateTimeUtil.getDateByAddingValidity( newSubscriptionRequest.getSubscriptionInfo().getNextBillingDate(), 1, TimeUnitEnum.DAY.name())); newSubscriptionRequest.getActivityEvent().setNextBillingDate(DateTimeUtil.getDateByAddingValidity( newSubscriptionRequest.getActivityEvent().getNextBillingDate(), 1, TimeUnitEnum.DAY.name())); SASValidationHelper.validate_sas_api_response(sasHelper.userSubscription(newSubscriptionRequest)); SASDBHelper.showAllActivityTableData("THIRD", String.valueOf(subscriptionId)); logger.info("=========>Second event: previous Event's DB verification"); expectedRecords.put("status", afteNewEventStatus); SASValidationHelper.validateTableRecord(DBUtils .getRecord(actionTable, "subscription_id = " + subscriptionId + " and product_id=" + productId + " and partner_id=" + partnerId + " and date=" + uSRequest.getSubscriptionInfo().getNextBillingDate()) .get(0), expectedRecords); logger.info("=========>Second event: DB verification before schedular call"); expectedRecords.put("status", newBeforeSchedularStatus); expectedRecords.put("date", String.valueOf(newSubscriptionRequest.getSubscriptionInfo().getNextBillingDate())); SASValidationHelper.validateTableRecord(DBUtils.getRecord(newActionTable, "subscription_id = " + subscriptionId + " and product_id=" + productId + " and partner_id=" + partnerId + " and date=" + newSubscriptionRequest.getSubscriptionInfo().getNextBillingDate()) .get(0), expectedRecords); logger.info("=========>Second event: Schedular call"); SASValidationHelper.validate_schedular_api_response( sasHelper.scheduler(SASUtils.generateSchedulerRequest(productId, partnerId, newQueueName))); SASDBHelper.showAllActivityTableData("FOURTH", String.valueOf(subscriptionId)); logger.info("=========>Second event: DB verification after schedular call"); expectedRecords.put("status", newAfterSchedularStatus); SASValidationHelper.validateTableRecord(DBUtils.getRecord(newActionTable, "subscription_id = " + subscriptionId + " and product_id=" + productId + " and partner_id=" + partnerId + " and date=" + newSubscriptionRequest.getSubscriptionInfo().getNextBillingDate()) .get(0), expectedRecords); logger.info("=========>Second event: Queue verification " + RabbitUtil.getQueueName(productId, partnerId, countryCode, queueName)); message = RabbitUtil.receive(RabbitMQConnection.getRabbitTemplate(), RabbitUtil.getQueueName(productId, partnerId, countryCode, newQueueName), 10000); // message = RabbitMQConnection.getRabbitTemplate() // .receive(productId + "_" + partnerId + "_" + newQueueName.toUpperCase() + // "ccc", 25000); SASValidationHelper.validateQueueMessage( ObjectMapperUtils.readValueFromString(new String(message.getBody()), SASQueueResponse.class), productId, partnerId, subscriptionId, countryCode, newActionTable.toUpperCase()); } public static void executeActivityFlow(Integer productId, Integer partnerId, int subscriptionId, String countryCode, String eventActionType, String activityType, String currentSubscriptionState, String transactionState, String actionTable, String schedulerActivity, String beforeSchedularStatus, String afterSchedularStatus, String queueName) throws Exception { SASHelper sasHelper = new SASHelper(); SASValidationHelper.validate_sas_api_response( sasHelper.userSubscription(SASUtils.generateUserSubscriptionRequest(productId, partnerId, activityType, "", currentSubscriptionState, transactionState, eventActionType, subscriptionId))); SASDBHelper.showAllActivityTableData("first", String.valueOf(subscriptionId)); Map<String, String> expectedRecords = new HashMap<String, String>(); expectedRecords.put("status", beforeSchedularStatus); expectedRecords.put("product_id", String.valueOf(productId)); expectedRecords.put("partner_id", String.valueOf(partnerId)); expectedRecords.put("subscription_id", String.valueOf(subscriptionId)); expectedRecords.put("country_code", countryCode); SASDBHelper.showAllActivityTableData("first", String.valueOf(subscriptionId)); SASValidationHelper.validateTableRecord(DBUtils.getRecord(actionTable, "subscription_id = " + subscriptionId + " and product_id = " + productId + " and partner_id=" + partnerId).get(0), expectedRecords); SASValidationHelper.validate_schedular_api_response( sasHelper.scheduler(SASUtils.generateSchedulerRequest(productId, partnerId, schedulerActivity))); expectedRecords.put("status", afterSchedularStatus); SASValidationHelper.validateTableRecord(DBUtils.getRecord(actionTable, "subscription_id = " + subscriptionId + " and product_id=" + productId + " and partner_id=" + partnerId) .get(0), expectedRecords); Message message = RabbitUtil.receive(RabbitMQConnection.getRabbitTemplate(), RabbitUtil.getQueueName(productId, partnerId, countryCode, queueName), 10000); // Message message = RabbitMQConnection.getRabbitTemplate() // .receive(productId + "_" + partnerId + "_" + queueName + "ccc", 25000); SASValidationHelper.validateQueueMessage( ObjectMapperUtils.readValueFromString(new String(message.getBody()), SASQueueResponse.class), productId, partnerId, subscriptionId, countryCode, actionTable.toUpperCase()); } public static String getTestLogMessage(Integer productId, long subscriptionId, String actionType, String activityType, String currentSubscriptionState, String transactionState) { return "Product ID: " + productId + ", subscription ID: " + subscriptionId + ", Activity Type: " + activityType + ", CSS: " + currentSubscriptionState + ", Transaction State: " + transactionState + ", Event Type: " + actionType; } public static void executeUserSubscription(Integer productId, Integer partnerId, long subscriptionId, String countryCode, String eventActionType, String activityType, String currentSubscriptionState, String transactionState, long endDate, long nBD, String actionTable, String status) throws Exception { SASHelper sasHelper = new SASHelper(); UserSubscriptionRequest userSubscriptionRequest = SASUtils.generateUserSubscriptionRequest(productId, partnerId, activityType, "", currentSubscriptionState, transactionState, eventActionType, subscriptionId); userSubscriptionRequest.getSubscriptionInfo().setEndDate(endDate); userSubscriptionRequest.getSubscriptionInfo().setNextBillingDate(nBD); SASValidationHelper.validate_sas_api_response(sasHelper.userSubscription(userSubscriptionRequest)); Map<String, String> expectedRecords = new HashMap<String, String>(); expectedRecords.put("status", status); expectedRecords.put("product_id", String.valueOf(productId)); expectedRecords.put("partner_id", String.valueOf(partnerId)); expectedRecords.put("subscription_id", String.valueOf(subscriptionId)); expectedRecords.put("country_code", countryCode); expectedRecords.put("date", countryCode); AppAssert .assertEqual( DBUtils.getRecords(actionTable, "subscription_id = " + subscriptionId + " and product_id = " + productId + " and partner_id=" + partnerId + " and country_code='" + countryCode + "' and date=" + nBD + " and status='" + status + "'") .size(), 1, "Verify record exists"); } public static void executescheduler(Integer productId, Integer partnerId, String schedulerActivity) throws Exception { SASHelper sasHelper = new SASHelper(); SASValidationHelper.validate_schedular_api_response( sasHelper.scheduler(SASUtils.generateSchedulerRequest(productId, partnerId, schedulerActivity))); } /** * @param productId * @param partnerId * @param countryCode * @param subscriptionId * @param eventActionType * @param activityType * @param currentSubscriptionState * @param transactionState * @param actionTable * @param beforeSchedularStatus * @param afterSchedularStatus * @param afteNewEventStatus * @param schedularActivityType * @param queueName * @param queueActivity * @param newEventActionType * @param newActivityType * @param newCurrentSubscriptionState * @param newTransactionState * @param newActionTable * @param newBeforeSchedularStatus * @param newAfterSchedularStatus * @param newSchedularActivityType * @param newQueueName * @param newQueueActivityType * @throws Exception */ public static void executeActivityFlows(int subscriptionId, int productId, int partnerId, String countryCode, String eventActionType, String activityType, String currentSubscriptionState, String transactionState, String actionTable, String beforeSchedularStatus, String afterSchedularStatus, String afteNewEventStatus, String schedularActivityType, String queueName, String queueActivity, String newEventActionType, String newActivityType, String newCurrentSubscriptionState, String newTransactionState, String newActionTable, String newBeforeSchedularStatus, String newAfterSchedularStatus, String newSchedularActivityType, String newQueueName, String newQueueActivityType) throws Exception { SASHelper sasHelper = new SASHelper(); Logger logger = Log4J.getLogger("SAS FLOW"); logger.info("=========>First time user subscription event getting trigger"); UserSubscriptionRequest firstUserSubscriptionRequest = SASUtils.generateUserSubscriptionRequest(productId, partnerId, activityType, currentSubscriptionState, transactionState, eventActionType, subscriptionId); SASValidationHelper.validate_sas_api_response(sasHelper.userSubscription(firstUserSubscriptionRequest)); SASDBHelper.showAllActivityTableData("FIRST ", String.valueOf(subscriptionId)); logger.info("=========>First event: Verify DB after event trigger"); SASValidationHelper.verifyEventTable(actionTable, subscriptionId, productId, partnerId, firstUserSubscriptionRequest.getSubscriptionInfo().getNextBillingDate(), beforeSchedularStatus, countryCode); logger.info("=========>First Event: scheduale call "); SASValidationHelper.validate_schedular_api_response( sasHelper.scheduler(SASUtils.generateSchedulerRequest(productId, partnerId, actionTable))); SASDBHelper.showAllActivityTableData("second", String.valueOf(subscriptionId)); logger.info("=========>First Event: Vefiry DB After Schedular Call "); Thread.sleep(5000); SASValidationHelper.verifyEventTable(actionTable, subscriptionId, productId, partnerId, firstUserSubscriptionRequest.getSubscriptionInfo().getNextBillingDate(), afterSchedularStatus, countryCode); logger.info("=========>First Event: Queue verification : "); SASValidationHelper.validateQueue(queueName, queueActivity, productId, partnerId, subscriptionId, countryCode); logger.info("=========>Second time user subscription event getting trigger"); UserSubscriptionRequest newSubscriptionRequest = SASUtils.generateUserSubscriptionRequest(productId, partnerId, newActivityType.toUpperCase(), newCurrentSubscriptionState, newTransactionState, newEventActionType, subscriptionId, DateTimeUtil.getDateByAddingValidity( firstUserSubscriptionRequest.getSubscriptionInfo().getNextBillingDate(), 1, TimeUnitEnum.DAY.name())); SASValidationHelper.validate_sas_api_response(sasHelper.userSubscription(newSubscriptionRequest)); SASDBHelper.showAllActivityTableData("THIRD", String.valueOf(subscriptionId)); logger.info("=========>Second event: previous Event's DB verification"); SASValidationHelper.verifyEventTable(actionTable, subscriptionId, productId, partnerId, firstUserSubscriptionRequest.getSubscriptionInfo().getNextBillingDate(), afteNewEventStatus, countryCode); logger.info("=========>Second event: DB verification before schedular call"); SASValidationHelper.verifyEventTable(newActionTable, subscriptionId, productId, partnerId, newSubscriptionRequest.getSubscriptionInfo().getNextBillingDate(), newBeforeSchedularStatus, countryCode); logger.info("=========>Second event: Schedular call"); SASValidationHelper.validate_schedular_api_response( sasHelper.scheduler(SASUtils.generateSchedulerRequest(productId, partnerId, newQueueName))); SASDBHelper.showAllActivityTableData("FOURTH", String.valueOf(subscriptionId)); logger.info("=========>Second event: DB verification after schedular call"); SASValidationHelper.verifyEventTable(newActionTable, subscriptionId, productId, partnerId, newSubscriptionRequest.getSubscriptionInfo().getNextBillingDate(), newAfterSchedularStatus, countryCode); logger.info("=========>Second event: Queue verification " + RabbitUtil.getQueueName(productId, partnerId, countryCode, queueName)); SASValidationHelper.validateQueue(newQueueName, newQueueActivityType, productId, partnerId, subscriptionId, countryCode); } public static void executeActivityFlow(Integer productId, Integer partnerId, int subscriptionId, String countryCode, String eventActionType, String activityType, String currentSubscriptionState, String transactionState, String actionTable, String schedulerActivity, String beforeSchedularStatus, String afterSchedularStatus, String queueName, String queueActivityType) throws Exception { SASHelper sasHelper = new SASHelper(); SASValidationHelper.validate_sas_api_response( sasHelper.userSubscription(SASUtils.generateUserSubscriptionRequest(productId, partnerId, activityType, "", currentSubscriptionState, transactionState, eventActionType, subscriptionId))); SASDBHelper.showAllActivityTableData("first", String.valueOf(subscriptionId)); Map<String, String> expectedRecords = new HashMap<String, String>(); expectedRecords.put("status", beforeSchedularStatus); expectedRecords.put("product_id", String.valueOf(productId)); expectedRecords.put("partner_id", String.valueOf(partnerId)); expectedRecords.put("subscription_id", String.valueOf(subscriptionId)); expectedRecords.put("country_code", countryCode); SASDBHelper.showAllActivityTableData("first", String.valueOf(subscriptionId)); SASValidationHelper.validateTableRecord(DBUtils.getRecord(actionTable, "subscription_id = " + subscriptionId + " and product_id = " + productId + " and partner_id=" + partnerId).get(0), expectedRecords); SASValidationHelper.validate_schedular_api_response( sasHelper.scheduler(SASUtils.generateSchedulerRequest(productId, partnerId, schedulerActivity))); expectedRecords.put("status", afterSchedularStatus); SASValidationHelper.validateTableRecord(DBUtils.getRecord(actionTable, "subscription_id = " + subscriptionId + " and product_id=" + productId + " and partner_id=" + partnerId) .get(0), expectedRecords); Message message = RabbitUtil.receive(RabbitMQConnection.getRabbitTemplate(), RabbitUtil.getQueueName(productId, partnerId, countryCode, queueName), 10000); // Message message = RabbitMQConnection.getRabbitTemplate() // .receive(productId + "_" + partnerId + "_" + queueName + "ccc", 25000); SASValidationHelper.validateQueueMessage( ObjectMapperUtils.readValueFromString(new String(message.getBody()), SASQueueResponse.class), productId, partnerId, subscriptionId, countryCode, queueActivityType); } } <file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"dateComputationCriterionId", "name", "operator", "value", "unit"}) @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString public class DateCoumputationCriterion { @JsonProperty("dateComputationCriterionId") private Integer dateComputationCriterionId; @JsonProperty("name") private String name; @JsonProperty("operator") private String operator; @JsonProperty("value") private String value; @JsonProperty("unit") private String unit; } <file_sep>billingPackageServer=http://10.11.100.8:8090 dbServer=10.11.100.8 dbPort=3306 dbName=billing_package dbUser=root dbPassword=<PASSWORD><file_sep> package com.vuclip.premiumengg.automation.subscription_service.common.models; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Builder @Getter @Setter @AllArgsConstructor @NoArgsConstructor @ToString public class ActivityEvent { private EventInfo eventInfo; private Long eventTimeStamp; private String userId; private String msisdn; private int productId; private String productName; private int partnerId; private String partnerName; private String requestedBillingCode; private String requestedPrice; private String attemptedBillingCode; private String attemptedPrice; private String chargedBillingCode; private double chargedPrice; private String currency; private String mode; private String action; private String activity; private String transactionId; private String transactionState; private String partnerTransactionId; private Integer itemId; private Integer itemTypeId; private String actionResult; private String serviceId; private Long subscriptionId; private String circleCode; private String countryCode; private String errorCode; private String errorDesc; private boolean delayed; private boolean closed; private String customerTransactionId; private String userPreferredLanguage; private String userSource; private Long nextBillingDate; private String adNetworkParams; private String churnNotificationParam; private Long activationDate; } <file_sep> package com.vuclip.premiumengg.automation.subscription_service.common.models; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "criterionId", "name", "operator", "value", "groupingOperator" }) public class Criterion { @JsonProperty("criterionId") private Integer criterionId; @JsonProperty("name") private String name; @JsonProperty("operator") private String operator; @JsonProperty("value") private String value; @JsonProperty("groupingOperator") private String groupingOperator; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("criterionId") public Integer getCriterionId() { return criterionId; } @JsonProperty("criterionId") public void setCriterionId(Integer criterionId) { this.criterionId = criterionId; } @JsonProperty("name") public String getName() { return name; } @JsonProperty("name") public void setName(String name) { this.name = name; } @JsonProperty("operator") public String getOperator() { return operator; } @JsonProperty("operator") public void setOperator(String operator) { this.operator = operator; } @JsonProperty("value") public String getValue() { return value; } @JsonProperty("value") public void setValue(String value) { this.value = value; } @JsonProperty("groupingOperator") public String getGroupingOperator() { return groupingOperator; } @JsonProperty("groupingOperator") public void setGroupingOperator(String groupingOperator) { this.groupingOperator = groupingOperator; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.utils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.vuclip.premiumengg.automation.configuration_service.common.models.ActionType; import com.vuclip.premiumengg.automation.configuration_service.common.models.ActionVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.ActivityFlowRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.ActivityFlowVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.ActivityType; import com.vuclip.premiumengg.automation.configuration_service.common.models.AdNetworkNotificationRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.AdNetworkNotificationVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.BlackoutRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.BlackoutVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.ChurnNotificationRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.ChurnNotificationVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.ConfigRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.ConfigResponseVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.ConfigVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.CriteriaRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.CriteriaVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.CriterionRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.CriterionVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.DateCoumputationCriterionRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.DateCoumputationCriterionVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.FlowType; import com.vuclip.premiumengg.automation.configuration_service.common.models.ItemTypeId; import com.vuclip.premiumengg.automation.configuration_service.common.models.JobType; import com.vuclip.premiumengg.automation.configuration_service.common.models.Mode; import com.vuclip.premiumengg.automation.configuration_service.common.models.PricePointRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.PricePointVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.ProductCountryMappingRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.ProductCountryMappingVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.ProductPartnerMappingRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.ProductPartnerMappingVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.ProductRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.ProductVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.RetryRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.RetryVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.SmsConfigRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.SmsConfigVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.SmsType; import com.vuclip.premiumengg.automation.configuration_service.common.models.StateConfigRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.StateConfigVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.Status; import com.vuclip.premiumengg.automation.configuration_service.common.models.TimeUnit; import com.vuclip.premiumengg.automation.configuration_service.common.models.TypeOfChurn; import com.vuclip.premiumengg.automation.configuration_service.common.models.TypeOfCycle; public class ConfigUtil { // private static Logger logger = Log4J.getLogger("ConfigUtil"); public static ConfigVO getMockConfigVO(ConfigRequestVO request) throws Exception { ProductVO product = getMockProductVO(request.getProduct()); ProductPartnerMappingVO productPartnerMapping = getMockProductPartnerMappingVO( request.getProductPartnerMappings().get(0)); ProductCountryMappingVO productCountryMapping = getMockProductCountryMappingVO( request.getProductCountryMapping()); PricePointVO pricePoint = getMockPricePointVO(request.getPricePoints().get(0)); AdNetworkNotificationVO adNetworkNotification = getMockAdNetworkNotificationVO( request.getAdNetworkNotifications().get(0)); BlackoutVO blockout = getMockBlockoutVO(request.getBlockouts().get(0)); ChurnNotificationVO churnNotification = getMockChurnNotificationVO(request.getChurnNotifications().get(0)); RetryVO retry = getMockRetryVO(request.getRetry().get(0)); StateConfigVO stateConfig = getMockStateConfigVO(request.getStateConfigs().get(0)); SmsConfigVO smsConfig = getMockSmsConfigVO(request.getSmsConfigs().get(0)); ActivityFlowVO activityFlowRequestVO = getMockActivityFlowRequestVO(request.getActivityFlows().get(0)); return ConfigVO.builder().product(product).productPartnerMappings(Arrays.asList(productPartnerMapping)) .productCountryMapping(productCountryMapping).pricePoints(Arrays.asList(pricePoint)) .adNetworkNotifications(Arrays.asList(adNetworkNotification)).blockouts(Arrays.asList(blockout)) .churnNotifications(Arrays.asList(churnNotification)).retry(Arrays.asList(retry)) .stateConfigs(Arrays.asList(stateConfig)).smsConfigs(Arrays.asList(smsConfig)) .activityFlows(Arrays.asList(activityFlowRequestVO)).build(); } public static ConfigRequestVO createMockRequestVO(Object... params) { ProductRequestVO product = createMockProductRequestVO(params); ProductPartnerMappingRequestVO productPartnerMapping = createMockProductPartnerMappingRequestVO(params); ProductCountryMappingRequestVO productCountryMapping = createMockProductCountryMappingRequestVO(params); PricePointRequestVO pricePoint = createMockPricePointRequestVO(params); AdNetworkNotificationRequestVO adNetworkNotification = createMockAdNetworkRequestVO(params); BlackoutRequestVO blockout = createMockBlockoutRequestVO(params); ChurnNotificationRequestVO churnNotificatoin = createMockChurnNotificationRequestVO(params); StateConfigRequestVO stateConfig = createMockStateConfigRequestVO(params); RetryRequestVO retry = createMockRetryRequestVO(params); SmsConfigRequestVO smsConfig = createMockSmsConfigRequestVO(params); ActivityFlowRequestVO activityFlowRequestVO = createMockActivityFlowRequestVO(params); return ConfigRequestVO.builder().product(product).productPartnerMappings(Arrays.asList(productPartnerMapping)) .productCountryMapping(productCountryMapping).pricePoints(Arrays.asList(pricePoint)) .adNetworkNotifications(Arrays.asList(adNetworkNotification)).blockouts(Arrays.asList(blockout)) .churnNotifications(Arrays.asList(churnNotificatoin)).stateConfigs(Arrays.asList(stateConfig)) .retry(Arrays.asList(retry)).smsConfigs(Arrays.asList(smsConfig)) .activityFlows(Arrays.asList(activityFlowRequestVO)).build(); } public static ProductRequestVO createMockProductRequestVO(Object... params) { return ProductRequestVO.builder().productId(10).productName((String) params[0]).productType((String) params[1]) .storeType("SUBSCRIPTION_STORE").url((String) params[3]).context((String) params[4]) .cassId((long) params[5]).encryptionEnable((boolean) params[6]) .encryptionValidityInMinutes((int) params[7]).callbackUrl((String) params[8]) .consentCancelUrl((String) params[9]).errorUrl((String) params[10]).description((String) params[11]) .status((String) params[12]).build(); } public static ProductPartnerMappingRequestVO createMockProductPartnerMappingRequestVO(Object... params) { return ProductPartnerMappingRequestVO.builder().productName((String) params[0]).partnerName((String) params[13]) .chargingDependOnSmsDelivery((boolean) params[14]).optOutSmsEnabled((boolean) params[15]) .preRenewalSmsEnabled((boolean) params[16]).partnerConsentParserEndpoint((String) params[17]) .partnerConsentUrlGenerationEndpoint((String) params[18]).dateFormat((String) params[19]) .timeUnit(TimeUnit.HOUR).build(); } public static ActivityFlowRequestVO createMockActivityFlowRequestVO(Object... params) { String billingCode = "1-1-IN-2236-06072018162944124"; return ActivityFlowRequestVO.builder().activityFlowId(10).productName((String) params[0]) .partnerName((String) params[13]).name(ActivityType.ACTIVATION).countryName((String) params[20]) .billingCode(billingCode).actions((Arrays.asList(ActionVO.builder().action(ActionType.CONSENT) .actionId(10).flowType(FlowType.VUCLIP_CONSENT).build()))) .mode(Mode.WAP).build(); } public static ProductCountryMappingRequestVO createMockProductCountryMappingRequestVO(Object... params) { return ProductCountryMappingRequestVO.builder().productName((String) params[0]) .countries(Arrays.asList((String) params[20])).build(); } public static PricePointRequestVO createMockPricePointRequestVO(Object... params) { return PricePointRequestVO.builder().productName((String) params[0]).partnerName((String) params[13]) .countryName((String) params[20]).price((Double) params[22]).validity((int) params[23]) .noOfCredits((int) params[24]).serviceId((String) params[25]).appId((int) params[26]) .ujId((int) params[27]).itemId((int) params[28]).itemTypeId((ItemTypeId) params[29]) .balanceCheckRequired((boolean) params[30]).description((String) params[31]) .fallbackApplicable((boolean) params[32]).freeTrialApplicable((boolean) params[34]) .isFreeTrial((boolean) params[36]).exclusionPeriod((int) params[37]) .autoRenewalApplicable((boolean) params[38]).status((String) params[39]) .contentAccessPostDeactivation((boolean) params[40]) .noOfDaysContentAccessAllowInParking((int) params[41]) .noOfDaysContentAccessAllowInSuspend((int) params[42]).parkingPeriod((int) params[43]) .suspendPeriod((int) params[44]).activationCoolDownPeriod((int) params[45]).timeUnit(TimeUnit.HOUR) .build(); } public static AdNetworkNotificationRequestVO createMockAdNetworkRequestVO(Object... params) { return AdNetworkNotificationRequestVO.builder().adNetworkNotificationId(10).productName((String) params[0]) .partnerName((String) params[13]).countryName((String) params[20]).pricePoint((String) params[21]) .name((String) params[46]).paidPercentage((int) params[47]).freePercentage((int) params[48]) .winbackPercentage((int) params[49]).build(); } public static BlackoutRequestVO createMockBlockoutRequestVO(Object... params) { return BlackoutRequestVO.builder().blackoutId(10).productName((String) params[0]) .partnerName((String) params[13]).countryName((String) params[20]).build(); } public static ChurnNotificationRequestVO createMockChurnNotificationRequestVO(Object... params) { return ChurnNotificationRequestVO.builder().churnNotificationId(10).productName((String) params[0]) .partnerName((String) params[13]).countryName((String) params[20]) .typeOfChurn(TypeOfChurn.valueOf((String) params[51])).period((String) params[52]).build(); } public static RetryRequestVO createMockRetryRequestVO(Object... params) { return RetryRequestVO.builder().retryId(10).productName((String) params[0]).partnerName((String) params[13]) .countryName((String) params[20]).activityType(JobType.valueOf((String) params[53])) .maxRetryCount((int) params[54]).retryIntervalInMinutes((int) params[55]) .attemptWindow((String) params[56]).typeOfCycle(TypeOfCycle.valueOf((String) params[57])) .batchSize((int) params[58]).schedulingFrequencyInMinutes((int) params[59]).status(Status.active) .build(); } public static StateConfigRequestVO createMockStateConfigRequestVO(Object... params) { return StateConfigRequestVO.builder().stateConfigId(10).productName((String) params[0]) .partnerName((String) params[13]).countryName((String) params[20]).pricePoint((String) params[21]) .actInitDuration((int) params[60]).activeDuration((int) params[61]).parkingDuration((int) params[62]) .graceDuration((int) params[63]).suspendDuration((int) params[64]).blacklistDuration((int) params[65]) .build(); } @SuppressWarnings("unchecked") public static SmsConfigRequestVO createMockSmsConfigRequestVO(Object... params) { return SmsConfigRequestVO.builder().smsConfigId(10).productName((String) params[0]) .partnerName((String) params[13]).countryName((String) params[20]) .type(SmsType.valueOf((String) params[66])).redirectionContext((String) params[67]) .defaultSmsLanguageId((int) params[68]).batchSize((int) params[69]).smsLength((int) params[70]) .isAutoPlay((boolean) params[71]).status((String) params[72]) .criterias((List<CriteriaRequestVO>) params[73]).build(); } public static ProductVO getMockProductVO(ProductRequestVO request) throws Exception { return ProductVO.builder().productId(1).productName(request.getProductName()) .productType(request.getProductType()).storeType(request.getStoreType()).url(request.getUrl()) .context(request.getContext()).cassId(request.getCassId()) .encryptionEnable(request.isEncryptionEnable()) .encryptionValidityInMinutes(request.getEncryptionValidityInMinutes()) .callbackUrl(request.getCallbackUrl()).consentCancelUrl(request.getConsentCancelUrl()) .errorUrl(request.getErrorUrl()).description(request.getDescription()) .status(Status.permissiveValueOf(request.getStatus()).toString()).build(); } public static ProductPartnerMappingVO getMockProductPartnerMappingVO(ProductPartnerMappingRequestVO request) { return ProductPartnerMappingVO.builder().productName(request.getProductName()) .partnerName(request.getPartnerName()) .chargingDependOnSmsDelivery(request.isChargingDependOnSmsDelivery()) .optOutSmsEnabled(request.isOptOutSmsEnabled()).preRenewalSmsEnabled(request.isPreRenewalSmsEnabled()) .partnerConsentParserEndpoint(request.getPartnerConsentParserEndpoint()) .partnerConsentUrlGenerationEndpoint(request.getPartnerConsentUrlGenerationEndpoint()) .dateFormat(request.getDateFormat()).build(); } public static ProductCountryMappingVO getMockProductCountryMappingVO(ProductCountryMappingRequestVO request) { return ProductCountryMappingVO.builder().productName("VIU").countries(Arrays.asList("India")).build(); } public static PricePointVO getMockPricePointVO(PricePointRequestVO request) { String billingCode = "1-1-IN-2236-06072018162944124"; return PricePointVO.builder().billingCode(billingCode).price(request.getPrice()).validity(request.getValidity()) .noOfCredits(request.getNoOfCredits()).serviceId(request.getServiceId()).appId(request.getAppId()) .ujId(request.getUjId()).itemId(request.getItemId()).itemTypeId(request.getItemTypeId()) .balanceCheckRequired(request.isBalanceCheckRequired()).description(request.getDescription()) .fallbackApplicable(request.isFallbackApplicable()).fallbackPpBillingCode(billingCode) .freeTrialApplicable(request.isFreeTrialApplicable()).freeTrialBillingCode(billingCode) .isFreeTrial(request.isFreeTrial()).exclusionPeriod(request.getExclusionPeriod()) .autoRenewalApplicable(request.isAutoRenewalApplicable()).status(request.getStatus()) .contentAccessPostDeactivation(request.isContentAccessPostDeactivation()) .noOfDaysContentAccessAllowInParking(request.getNoOfDaysContentAccessAllowInParking()) .noOfDaysContentAccessAllowInSuspend(request.getNoOfDaysContentAccessAllowInSuspend()) .parkingPeriod(request.getParkingPeriod()).suspendPeriod(request.getSuspendPeriod()) .activationCoolDownPeriod(request.getActivationCoolDownPeriod()).build(); } public static AdNetworkNotificationVO getMockAdNetworkNotificationVO(AdNetworkNotificationRequestVO request) { return AdNetworkNotificationVO.builder().adNetworkNotificationId(1).name(request.getName()) .paidPercentage(request.getPaidPercentage()).freePercentage(request.getFreePercentage()) .pricePoint(request.getPricePoint()).winbackPercentage(request.getWinbackPercentage()).build(); } public static BlackoutVO getMockBlockoutVO(BlackoutRequestVO request) { return BlackoutVO.builder().blackoutId(1).productName(request.getProductName()) .partnerName(request.getPartnerName()).countryName("India").build(); } public static ChurnNotificationVO getMockChurnNotificationVO(ChurnNotificationRequestVO request) { return ChurnNotificationVO.builder().churnNotificationId(1).typeOfChurn(request.getTypeOfChurn()) .period(request.getPeriod()).build(); } public static RetryVO getMockRetryVO(RetryRequestVO request) { return RetryVO.builder().retryId(1).activityType(request.getActivityType()) .maxRetryCount(request.getMaxRetryCount()).retryIntervalInMinutes(request.getRetryIntervalInMinutes()) .attemptWindow(request.getAttemptWindow()).typeOfCycle(request.getTypeOfCycle()) .batchSize(request.getBatchSize()) .schedulingFrequencyInMinutes(request.getSchedulingFrequencyInMinutes()).build(); } public static StateConfigVO getMockStateConfigVO(StateConfigRequestVO request) { return StateConfigVO.builder().stateConfigId(1).actInitDuration(request.getActInitDuration()) .activeDuration(request.getActiveDuration()).parkingDuration(request.getParkingDuration()) .graceDuration(request.getGraceDuration()).suspendDuration(request.getSuspendDuration()) .blacklistDuration(request.getBlacklistDuration()).build(); } public static ActivityFlowVO getMockActivityFlowRequestVO(ActivityFlowRequestVO activityFlowRequestVO) { String billingCode = "1-1-IN-2236-06072018162944124"; return ActivityFlowVO.builder().productName(activityFlowRequestVO.getProductName()).activityFlowId(10) .partnerName(activityFlowRequestVO.getPartnerName()).name(ActivityType.ACTIVATION).countryName("India") .billingCode(billingCode) .actions((Arrays.asList( ActionVO.builder().action(ActionType.CONSENT).flowType(FlowType.VUCLIP_CONSENT).build()))) .mode(Mode.WAP).build(); } public static SmsConfigVO getMockSmsConfigVO(SmsConfigRequestVO request) { List<CriteriaVO> criterias = convertToCriteria(request.getCriterias()); return SmsConfigVO.builder().smsConfigId(1).type(request.getType()) .redirectionContext(request.getRedirectionContext()) .defaultSmsLanguageId(request.getDefaultSmsLanguageId()).batchSize(request.getBatchSize()) .smsLength(request.getSmsLength()).autoPlay(request.isAutoPlay()).status(request.getStatus()) .criterias(criterias).build(); } public static List<CriteriaVO> convertToCriteria(List<CriteriaRequestVO> criterias) { List<CriteriaVO> criteriaResponseVOs = new ArrayList<>(); criterias.forEach(criteria -> { DateCoumputationCriterionVO dateCoumputationCriterion = covertToDateCoumputationCriterion( criteria.getDateCoumputationCriterion()); List<CriterionVO> criterions = convertToCriterion(criteria.getCriterions()); CriteriaVO responseVO = CriteriaVO.builder().criteriaId(1).smsText(criteria.getSmsText()) .dateCoumputationCriterion(dateCoumputationCriterion).criterions(criterions).build(); criteriaResponseVOs.add(responseVO); }); return criteriaResponseVOs; } public static List<CriterionVO> convertToCriterion(List<CriterionRequestVO> criterions) { List<CriterionVO> criterionResponseVOs = new ArrayList<>(); criterions.forEach(criterion -> { CriterionVO responseVO = CriterionVO.builder().criterionId(1).name(criterion.getName()) .value(criterion.getValue()).operator(criterion.getOperator()) .groupingOperator(criterion.getGroupingOperator()).build(); criterionResponseVOs.add(responseVO); }); return criterionResponseVOs; } public static DateCoumputationCriterionVO covertToDateCoumputationCriterion( DateCoumputationCriterionRequestVO dateCoumputationCriterion) { return DateCoumputationCriterionVO.builder().dateComputationCriterionId(1) .name(dateCoumputationCriterion.getName()).value(dateCoumputationCriterion.getValue()) .unit(dateCoumputationCriterion.getUnit()).build(); } public static ConfigResponseVO createUpdateConfigData(ConfigResponseVO updateConfig) { updateConfig.getConfig().getProduct().setConsentCancelUrl("www.test.com"); updateConfig.getConfig().getProduct().setOperationType(null); updateConfig.getConfig().getProductPartnerMappings().get(0).setOperationType(null); updateConfig.getConfig().getProductCountryMapping().setOperationType(null); updateConfig.getConfig().getSmsConfigs().get(0).setOperationType(null); updateConfig.getConfig().getChurnNotifications().get(0).setOperationType(null); updateConfig.getConfig().getAdNetworkNotifications().get(0).setOperationType(null); updateConfig.getConfig().getPricePoints().get(0).setOperationType(null); updateConfig.getConfig().getRetry().get(0).setOperationType(null); updateConfig.getConfig().getStateConfigs().get(0).setOperationType(null); updateConfig.getConfig().getBlockouts().get(0).setOperationType(null); updateConfig.getConfig().getActivityFlows().get(0).setOperationType(null); return updateConfig; } } <file_sep>package com.vuclip.premiumengg.automation.billing_package_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"productId", "partnerId", "countryCode", "activitType", "subscriptionId", "attemptNumber"}) public class QueueResponse { @JsonProperty("productId") private Object productId; @JsonProperty("partnerId") private Object partnerId; @JsonProperty("countryCode") private String countryCode; @JsonProperty("activitType") private String activitType; @JsonProperty("subscriptionId") private Object subscriptionId; @JsonProperty("attemptNumber") private Object attemptNumber; /** * No args constructor for use in serialization */ public QueueResponse() { } /** * @param countryCode * @param partnerId * @param activitType * @param attemptNumber * @param subscriptionId * @param productId */ public QueueResponse(Object productId, Object partnerId, String countryCode, String activitType, Object subscriptionId, Object attemptNumber) { super(); this.productId = productId; this.partnerId = partnerId; this.countryCode = countryCode; this.activitType = activitType; this.subscriptionId = subscriptionId; this.attemptNumber = attemptNumber; } @JsonProperty("productId") public Object getProductId() { return productId; } @JsonProperty("productId") public void setProductId(Object productId) { this.productId = productId; } @JsonProperty("partnerId") public Object getPartnerId() { return partnerId; } @JsonProperty("partnerId") public void setPartnerId(Object partnerId) { this.partnerId = partnerId; } @JsonProperty("countryCode") public String getCountryCode() { return countryCode; } @JsonProperty("countryCode") public void setCountryCode(String countryCode) { this.countryCode = countryCode; } @JsonProperty("activitType") public String getActivitType() { return activitType; } @JsonProperty("activitType") public void setActivitType(String activitType) { this.activitType = activitType; } @JsonProperty("subscriptionId") public Object getSubscriptionId() { return subscriptionId; } @JsonProperty("subscriptionId") public void setSubscriptionId(Object subscriptionId) { this.subscriptionId = subscriptionId; } @JsonProperty("attemptNumber") public Object getAttemptNumber() { return attemptNumber; } @JsonProperty("attemptNumber") public void setAttemptNumber(Object attemptNumber) { this.attemptNumber = attemptNumber; } @Override public String toString() { return "QueueResponse [productId=" + productId + ", partnerId=" + partnerId + ", countryCode=" + countryCode + ", activitType=" + activitType + ", subscriptionId=" + subscriptionId + ", attemptNumber=" + attemptNumber + "]"; } }<file_sep>package com.vuclip.premiumengg.automation.utils; import com.vuclip.premiumengg.automation.common.Configuration; import com.vuclip.premiumengg.automation.common.RabbitMQConnection; import org.springframework.amqp.core.Message; import java.nio.charset.StandardCharsets; /** * @author <NAME> */ public class RabbitMQUtil { public static void sendMessageToQueueByExchange(String exchange, String message) { RabbitMQConnection.getRabbitTemplate().convertAndSend(exchange, "", message); } public static Message getMessageFromQueue(String queueName) { return getMessageFromQueue(queueName, Configuration.defaultTimeOutMillisForQueue); } public static String getMessageBody(Message message) { return new String(message.getBody(), StandardCharsets.UTF_8); } public static Message getMessageFromQueue(String queueName, long timeoutMillis) { return getMessageFromQueue(queueName, timeoutMillis, false); } public static Message getMessageFromQueue(String queueName, long timeoutMillis, boolean isNeedToCaps) { if (isNeedToCaps) queueName = queueName.toUpperCase(); return RabbitMQConnection.getRabbitTemplate().receive(queueName, timeoutMillis); } } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.utils; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import com.vuclip.premiumengg.automation.utils.AppAssert; import com.vuclip.premiumengg.automation.utils.DBUtils; public class PartnerDBHelper { public static void insertRecordIntoPartner(String partnerName, int partnerId) { Map<String, Object> insertRecord = new HashMap<String, Object>(); insertRecord.put("has_mo_activations", 0); insertRecord.put("has_mo_deactivations", 0); insertRecord.put("is_auto_renewal_applicable", 0); insertRecord.put("is_balance_check_required", 1); insertRecord.put("step_up_charging", 1); insertRecord.put("user_identifier", CSDBHelper.dbReadableFormat("user4")); insertRecord.put("type", CSDBHelper.dbReadableFormat("type")); insertRecord.put("activation_managed_by", CSDBHelper.dbReadableFormat("ActivationManagedBy")); insertRecord.put("deactivation_managed_by", CSDBHelper.dbReadableFormat("DeActivationManagedBy")); insertRecord.put("description", CSDBHelper.dbReadableFormat("Description")); insertRecord.put("partner_activation_consent_initiation_url", CSDBHelper.dbReadableFormat("url")); insertRecord.put("partner_name", CSDBHelper.dbReadableFormat(partnerName)); insertRecord.put("partner_id", partnerId); insertRecord.put("renewal_managed_by", CSDBHelper.dbReadableFormat("renewalManagedBy")); insertRecord.put("status", CSDBHelper.dbReadableFormat("ACTIVE")); insertRecord.put("partner_activation_consent_initiation_url", CSDBHelper.dbReadableFormat("Vuclip Url")); insertRecord.put("partner_activation_consent_parser_url", CSDBHelper.dbReadableFormat("Vuclip url")); insertRecord.put("partner_deactivation_consent_initiation_url", CSDBHelper.dbReadableFormat("Vuclip url")); insertRecord.put("partner_deactivation_consent_parser_url", CSDBHelper.dbReadableFormat("Vuclip url")); CSDBHelper.addRecordInTable("partner", insertRecord); } public static void verifyNoActivityRecordPresent(String tableName, String partnerName) throws SQLException { AppAssert.assertTrue(DBUtils.getRecord(tableName, "partner_name =" + partnerName).size() == 0, "verify no entry in " + tableName); } } <file_sep> package com.vuclip.premiumengg.automation.subscription_service.common.models; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "stateConfigId", "productId", "partnerId", "countryCode", "operationType", "pricePoint", "actInitDuration", "activeDuration", "parkingDuration", "graceDuration", "suspendDuration", "blacklistDuration" }) public class StateConfig { @JsonProperty("stateConfigId") private Integer stateConfigId; @JsonProperty("productId") private Integer productId; @JsonProperty("partnerId") private Integer partnerId; @JsonProperty("countryCode") private String countryCode; @JsonProperty("operationType") private String operationType; @JsonProperty("pricePoint") private String pricePoint; @JsonProperty("actInitDuration") private Integer actInitDuration; @JsonProperty("activeDuration") private Integer activeDuration; @JsonProperty("parkingDuration") private Integer parkingDuration; @JsonProperty("graceDuration") private Integer graceDuration; @JsonProperty("suspendDuration") private Integer suspendDuration; @JsonProperty("blacklistDuration") private Integer blacklistDuration; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("stateConfigId") public Integer getStateConfigId() { return stateConfigId; } @JsonProperty("stateConfigId") public void setStateConfigId(Integer stateConfigId) { this.stateConfigId = stateConfigId; } @JsonProperty("productId") public Integer getProductId() { return productId; } @JsonProperty("productId") public void setProductId(Integer productId) { this.productId = productId; } @JsonProperty("partnerId") public Integer getPartnerId() { return partnerId; } @JsonProperty("partnerId") public void setPartnerId(Integer partnerId) { this.partnerId = partnerId; } @JsonProperty("countryCode") public String getCountryCode() { return countryCode; } @JsonProperty("countryCode") public void setCountryCode(String countryCode) { this.countryCode = countryCode; } @JsonProperty("operationType") public String getOperationType() { return operationType; } @JsonProperty("operationType") public void setOperationType(String operationType) { this.operationType = operationType; } @JsonProperty("pricePoint") public String getPricePoint() { return pricePoint; } @JsonProperty("pricePoint") public void setPricePoint(String pricePoint) { this.pricePoint = pricePoint; } @JsonProperty("actInitDuration") public Integer getActInitDuration() { return actInitDuration; } @JsonProperty("actInitDuration") public void setActInitDuration(Integer actInitDuration) { this.actInitDuration = actInitDuration; } @JsonProperty("activeDuration") public Integer getActiveDuration() { return activeDuration; } @JsonProperty("activeDuration") public void setActiveDuration(Integer activeDuration) { this.activeDuration = activeDuration; } @JsonProperty("parkingDuration") public Integer getParkingDuration() { return parkingDuration; } @JsonProperty("parkingDuration") public void setParkingDuration(Integer parkingDuration) { this.parkingDuration = parkingDuration; } @JsonProperty("graceDuration") public Integer getGraceDuration() { return graceDuration; } @JsonProperty("graceDuration") public void setGraceDuration(Integer graceDuration) { this.graceDuration = graceDuration; } @JsonProperty("suspendDuration") public Integer getSuspendDuration() { return suspendDuration; } @JsonProperty("suspendDuration") public void setSuspendDuration(Integer suspendDuration) { this.suspendDuration = suspendDuration; } @JsonProperty("blacklistDuration") public Integer getBlacklistDuration() { return blacklistDuration; } @JsonProperty("blacklistDuration") public void setBlacklistDuration(Integer blacklistDuration) { this.blacklistDuration = blacklistDuration; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } } <file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.common.models; import lombok.*; /** * @author shreyash */ @Builder @Getter @Setter @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode @ToString public class EventInfo { private long logTime; private String eventId; private String eventType; } <file_sep> package com.vuclip.premiumengg.automation.subscription_service.common.models; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "churnNotificationId", "typeOfChurn", "period", "productId", "partnerId", "countryCode", "operationType" }) public class ChurnNotification { @JsonProperty("churnNotificationId") private Integer churnNotificationId; @JsonProperty("typeOfChurn") private String typeOfChurn; @JsonProperty("period") private String period; @JsonProperty("productId") private Integer productId; @JsonProperty("partnerId") private Integer partnerId; @JsonProperty("countryCode") private String countryCode; @JsonProperty("operationType") private String operationType; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("churnNotificationId") public Integer getChurnNotificationId() { return churnNotificationId; } @JsonProperty("churnNotificationId") public void setChurnNotificationId(Integer churnNotificationId) { this.churnNotificationId = churnNotificationId; } @JsonProperty("typeOfChurn") public String getTypeOfChurn() { return typeOfChurn; } @JsonProperty("typeOfChurn") public void setTypeOfChurn(String typeOfChurn) { this.typeOfChurn = typeOfChurn; } @JsonProperty("period") public String getPeriod() { return period; } @JsonProperty("period") public void setPeriod(String period) { this.period = period; } @JsonProperty("productId") public Integer getProductId() { return productId; } @JsonProperty("productId") public void setProductId(Integer productId) { this.productId = productId; } @JsonProperty("partnerId") public Integer getPartnerId() { return partnerId; } @JsonProperty("partnerId") public void setPartnerId(Integer partnerId) { this.partnerId = partnerId; } @JsonProperty("countryCode") public String getCountryCode() { return countryCode; } @JsonProperty("countryCode") public void setCountryCode(String countryCode) { this.countryCode = countryCode; } @JsonProperty("operationType") public String getOperationType() { return operationType; } @JsonProperty("operationType") public void setOperationType(String operationType) { this.operationType = operationType; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } } <file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.tests; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils.RabbitUtil; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils.SASUtils; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils.SASValidationHelper; import com.vuclip.premiumengg.automation.utils.AppAssert; import org.apache.commons.lang3.RandomUtils; import org.apache.log4j.Logger; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * @author mayank.bharshiv */ public class SASActivationTests { private static Logger logger = Log4J.getLogger("SASActivationTests"); int productId; int partnerId; private String countryCode = "IN"; @BeforeClass(alwaysRun = true) public void setup() throws Exception { productId = SASUtils.productId; partnerId = productId; } @DataProvider(name = "activationPostiveDataProvider") public Object[][] activationPostiveDataProvider() { return new Object[][]{ // covered in sasTest{ "ACTIVATION", "ACT_INIT", "ACTIVATED", "SUCCESS", // "CHARGING", 101, "renewal", "OPEN" }, // covered in sasTest{ "ACTIVATION", "ACT_INIT", "ACT_INIT", "FAILURE", // "CHARGING", 107, "activation", "OPEN" }, {"ACTIVATION", "ACT_INIT", "ACT_INIT", "ERROR", "CHARGING", 108, "activation", "OPEN", "ACTIVATION_RETRY"}, // covered in sasTest { "ACTIVATION", "ACT_INIT", "PARKING", "LOW_BALANCE", // "CHARGING", 111, "winback", "OPEN" }, // Fail{ "ACTIVATION", "ACT_INIT", "ACT_INIT", "IN_PROGRESS", "CHARGING", 106, // "winback", "OPEN" }, // Fail{ "ACTIVATION", "ACT_INIT", "ACT_INIT", "NOTIFICATION_WAIT", "CHARGING", // 106, "winback", "OPEN" } }; } @Test(dataProvider = "activationPostiveDataProvider", groups = {"positive"}) public void activationPositiveTest(String activityType, String previousSubscriptionState, String currentSubscriptionState, String transactionState, String eventActionType, Integer subscriptionId, String actionTable, String status, String queueName) throws Exception { subscriptionId = RandomUtils.nextInt(31000, 32000); logger.info("==================>Starting activation Positive Test [ " + SASUtils.getTestLogMessage(productId, subscriptionId, eventActionType, activityType, currentSubscriptionState, transactionState) + " ]"); RabbitUtil.purgeAllActivityQueue(productId, partnerId, countryCode); try { String schedulerActivity = actionTable; SASUtils.executeActivityFlow(productId, partnerId, subscriptionId, countryCode, eventActionType, activityType, currentSubscriptionState, transactionState, actionTable, schedulerActivity, "OPEN", "IN_PROGRESS", queueName, queueName); } catch (Exception e) { logger.error("activationPositiveTest Failed"); e.printStackTrace(); AppAssert.assertTrue(false); } } @DataProvider(name = "activationNegativeDataProvider") public Object[][] activationNegativeDataProvider() { return new Object[][]{ {"ACTIVATION", "ACT_INIT", "ACTIVATED", "LOW_BALANCE", "CHARGING", 102, "renewal", "OPEN"}, {"ACTIVATION", "ACT_INIT", "ACTIVATED", "FAILURE", "CHARGING", 103, "renewal", "OPEN"}, {"ACTIVATION", "ACT_INIT", "ACTIVATED", "ERROR", "CHARGING", 104, "renewal", "OPEN"}, {"ACTIVATION", "ACT_INIT", "ACT_INIT", "SUCCESS", "CHARGING", 105, "activation", "OPEN"}, {"ACTIVATION", "ACT_INIT", "PARKING", "SUCCESS", "CHARGING", 109, "winback", "OPEN"}, {"ACTIVATION", "ACT_INIT", "PARKING", "FAILURE", "CHARGING", 110, "winback", "OPEN"}, {"ACTIVATION", "ACT_INIT", "ACT_INIT", "LOW_BALANCE", "CHARGING", 106, "winback", "OPEN"}, {"ACTIVATION", "ACT_INIT", "PARKING", "ERROR", "CHARGING", 112, "winback", "OPEN"} }; } @Test(dataProvider = "activationNegativeDataProvider", groups = {"positive"}) public void activationNegativeTest(String activityType, String previousSubscriptionState, String currentSubscriptionState, String transactionState, String actionType, Integer subscriptionId, String actionTable, String status) throws Exception { subscriptionId = RandomUtils.nextInt(53000, 54000); logger.info("==================>Starting activation Negative Data Provider [ " + SASUtils.getTestLogMessage(productId, subscriptionId, actionType, activityType, currentSubscriptionState, transactionState) + " ]"); SASValidationHelper.negativeFlow(productId, partnerId, activityType, currentSubscriptionState, transactionState, actionType, subscriptionId); } } <file_sep>package com.vuclip.premiumengg.automation.schedular_service.tests; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.schedular_service.common.models.ActivityType; import com.vuclip.premiumengg.automation.schedular_service.common.models.SchedulerSaveProductRequest; import com.vuclip.premiumengg.automation.schedular_service.common.utils.SSDBHelper; import com.vuclip.premiumengg.automation.schedular_service.common.utils.SSHelper; import com.vuclip.premiumengg.automation.schedular_service.common.utils.SSUtils; import com.vuclip.premiumengg.automation.schedular_service.common.utils.SSValidationHelper; import com.vuclip.premiumengg.automation.utils.AppAssert; import org.apache.log4j.Logger; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.Map; /** * @author <NAME> */ public class VerifyActivityTypeTest { private static Logger logger = Log4J.getLogger("GetJobTests"); @DataProvider(name = "dp") public Object[][] activationDeactivationPostiveDataProvider() { return new Object[][]{{ActivityType.ACTIVATION_RETRY.name()}, {ActivityType.CONTENT_SMS.name()}, {ActivityType.DEACTIVATION_RETRY.name()}, {ActivityType.ENGAGEMENT_SMS.name()}, {ActivityType.FREETRIAL_RENEWAL.name()}, {ActivityType.OPTOUT_SMS.name()}, {ActivityType.PRE_RENEWAL_SMS.name()}, {ActivityType.RENEWAL.name()}, {ActivityType.RENEWAL_RETRY.name()}, {ActivityType.SYSTEM_CHURN.name()}, {ActivityType.WINBACK.name()} }; } @Test(dataProvider = "dp", groups = {"positive"}) public void VerifyActivityTypeTests(String activityType) { try { logger.info("=======>VerifyActivityTypeTests Test"); int p = 6000; String country = "XX"; SSDBHelper.cleanTestData(p, p, country); SchedulerSaveProductRequest configurationMessage = SSUtils.getConfigurationMessage(activityType, p, p, 100, country); // QueueMessage queueMessage = SSUtils.getQueueMessage(configurationMessage); logger.info("sending this to queue" + configurationMessage.toString()); SSHelper.sendMessage(configurationMessage); // validate job_rules and job_rules_window table // adding this as on CI it is failing due to fastness of getting data from Db // after performing operation Map<String, Object> jobRuleRecord = SSDBHelper.getJobRules(p, p, country); SSValidationHelper.verifyJobRulesRecord(jobRuleRecord, configurationMessage); Map<String, Object> jobRuleTimeWindowRecord = SSDBHelper .getJobRuleTimeWindow((long) jobRuleRecord.get("id")); SSValidationHelper.verifyJobRuleTimeWindowRecord(jobRuleTimeWindowRecord, configurationMessage); SSDBHelper.cleanTestData(p, p, country); } catch (Exception e) { e.printStackTrace(); AppAssert.assertTrue(false, "Test case failed due to exception " + e.getMessage()); } } } <file_sep>ssServer=http://10.11.100.8:8087/subscription-service dbServer=10.11.100.8 dbPort=3306 dbName=subscription_service dbUser=root dbPassword=<PASSWORD> rabbitMQServer=10.11.100.8 rabbitMQPort=5672 rabbitMQUser=jenkins rabbitMQPassword=<PASSWORD> ss.redis.clusters=10.11.100.8:6380 <file_sep>package com.vuclip.premiumengg.automation.common; import redis.clients.jedis.Jedis; /** * Created by Kohitij_Das on 10/04/17. */ public class RedisConnectionSingleNode { private static Jedis redisConnectionSingleNode; private RedisConnectionSingleNode() { } static String host; static String port; public static Jedis getRedisConnection() { if (redisConnectionSingleNode == null) { String redisHosts = Configuration.redisServers; System.out.println("Redis Hosts: " + redisHosts); String[] servers = redisHosts.split(","); for (String server : servers) { String[] hosts = server.split(":"); host = hosts[0]; port = hosts[1]; } RedisConnectionSingleNode.redisConnectionSingleNode = new Jedis(host,Integer.parseInt(port)); } return redisConnectionSingleNode; } } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; @Getter @ToString @Builder @AllArgsConstructor @NoArgsConstructor public class AdNetworkNotificationRequestVO { private int adNetworkNotificationId; private String productName; private String partnerName; private String countryName; private String pricePoint; private String name; private int paidPercentage; private int freePercentage; private int winbackPercentage; } <file_sep>package com.vuclip.premiumengg.automation.ad_network_service.common.models; public enum EventType { INITIAL_REQUEST, PERSIST_REQUEST, ADNOTIFICATION_REQUEST, CHURN_NOTIFICATION_REQUEST; }<file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.utils; import java.math.BigInteger; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.log4j.Logger; import com.vuclip.premiumengg.automation.billing_package_service.common.models.QueueResponse; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.models.SASTables; import com.vuclip.premiumengg.automation.utils.AppAssert; import com.vuclip.premiumengg.automation.utils.DBUtils; import io.restassured.response.Response; public class CSValidationHelper { private static Logger logger = Log4J.getLogger("CSValidationHelper"); public static void validate_cs_api_response(Response sasApiResponse) { AppAssert.assertEqual(sasApiResponse.statusCode(), 200, "Vefiry that response status code is 200 "); } public static void validate_sas_invalid_api_response(Response sasApiResponse) { AppAssert.assertEqual(sasApiResponse.statusCode(), 500, "Vefiry that response status code is 500 "); } public static void validate_schedular_invalid_api_response(Response schedularApiResponse) { AppAssert.assertEqual(schedularApiResponse.statusCode(), 500, "Validate that response status code is 500 "); AppAssert.assertEqual(schedularApiResponse.getBody().asString(), "FAILURE", "verify scheduler api call"); } public static void validateTableRecord(List<Map<String, Object>> list, Map<String, Object> expectedRecord) { for (String key : expectedRecord.keySet()) { if (list.get(0).get(key) != null) AppAssert.assertEqual(list.get(0).get(key).toString().toLowerCase(), expectedRecord.get(key).toString().toLowerCase(), "Verify table fields"); } } public static void validateQueueMessage(QueueResponse queueResponse, int productId, int partnerId, int subscriptionId, String countryCode, String actionTable) throws InterruptedException { logger.info("verification for RabbitMQ"); AppAssert.assertEqual(queueResponse.getProductId().toString().toUpperCase(), String.valueOf(productId).toUpperCase(), "Verify product ID"); AppAssert.assertEqual(queueResponse.getPartnerId().toString().toUpperCase(), String.valueOf(partnerId).toUpperCase(), "Verify partner ID"); AppAssert.assertEqual(queueResponse.getSubscriptionId().toString(), String.valueOf(subscriptionId), "Verify subscription ID"); AppAssert.assertEqual(queueResponse.getCountryCode().toUpperCase(), countryCode.toUpperCase(), "Verify country"); if (actionTable.toUpperCase().equalsIgnoreCase("RENEWAL_RETRY")) AppAssert.assertEqual(queueResponse.getActivitType().toString().toUpperCase(), "RENEWAL", "Verify activity type"); else AppAssert.assertEqual(queueResponse.getActivitType().toString().toUpperCase(), actionTable.toUpperCase(), "Verify activity type"); } public static void verifyNoActivityRecordPresent(int productId, int partnerId, Integer subscriptionId, BigInteger date) { List<String> tables = Stream.of(SASTables.values()).map(Enum::name).collect(Collectors.toList()); for (String tableName : tables) { try { AppAssert.assertTrue( DBUtils.getRecord(tableName, " subscription_id =" + String.valueOf(subscriptionId) + " and product_id =" + String.valueOf(productId) + " and partner_id=" + String.valueOf(partnerId) + " and date=" + String.valueOf(date)) .size() == 0, "verify no entry in " + tableName); } catch (SQLException e) { AppAssert.assertTrue(false, "Error occoured while fetching data from DB " + tableName + " error message" + e.getMessage()); } } } } <file_sep>package com.vuclip.premiumengg.automation.schedular_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.*; import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"retry"}) @ToString @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class SchedulerSaveProductRequest { @JsonProperty("retry") private List<Retry> retry = null; }<file_sep>package com.vuclip.premiumengg.automation.subscription_service.common.utils; import java.math.BigInteger; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.TimeZone; public class DateTimeUtil { public static BigInteger getDateByAddingValidity(BigInteger dateInMillis, int validity, String timeUnit) { TimeUnitEnum timeUnitEnum = TimeUnitEnum.valueOf(TimeUnitEnum.class, timeUnit); long validityInMillis = timeUnitEnum.toSeconds() * validity * 1000; return dateInMillis.add(BigInteger.valueOf(validityInMillis)); } public static BigInteger getDateBySubtractingValidity(BigInteger dateInMillis, int validity, String timeUnit) { TimeUnitEnum timeUnitEnum = TimeUnitEnum.valueOf(TimeUnitEnum.class, timeUnit); long validityInMillis = timeUnitEnum.toSeconds() * validity * 1000; return dateInMillis.subtract(BigInteger.valueOf(validityInMillis)); } public static BigInteger getCurrentDateInGMT() { return BigInteger.valueOf(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis()); } public static long getTimeInMillis(String dd, String mm, String yyyy, String HH, String MM, String SS) { LocalDateTime localDateTime = LocalDateTime.parse(yyyy + "/" + mm + "/" + dd + " " + HH + ":" + MM + ":" + SS, DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")); return localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); } public static long getTimeInMillisAddDays(int days) { LocalDateTime s = LocalDateTime.now().plusDays(days); return s.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); } public static long getTimeInMillisMinusDays(int days) { LocalDateTime s = LocalDateTime.now().minusDays(days); return s.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); } public static String getTime(String yyyy,String mm,String dd , String HH, String MM, String SS) { /* LocalDateTime localDateTime = LocalDateTime.parse(yyyy + "-" + mm + "-" + dd + HH + ":" + MM + ":" + SS, DateTimeFormatter.ofPattern("yyyy-MM-ddHH:mm:ss"));*/ DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-ddHH:mm:ss"); LocalDateTime dateTime = LocalDateTime.parse(yyyy + "-" + mm + "-" + dd + HH + ":" + MM + ":" + SS); String formattedDateTime = dateTime.format(formatter); return formattedDateTime; } } <file_sep>sasServer=http://10.11.100.8:8083/scheduled-activity-service dbServer=10.11.100.8 dbPort=3306 dbName=scheduled_activity_service dbUser=root dbPassword=<PASSWORD> rabbitMQServer=10.11.100.8 rabbitMQPort=5672 rabbitMQUser=jenkins rabbitMQPassword=<PASSWORD> <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; import javaslang.collection.Array; public enum Status { active, INACTIVE; public static Status permissiveValueOf(String status) throws Exception { return Array.of(values()).filter(s -> s.toString().equalsIgnoreCase(status)) .getOrElseThrow(() -> new Exception("No Status enum found for status : " + status)); } } <file_sep>package com.vuclip.premiumengg.automation.billing_package_service.common.utils; import com.vuclip.premiumengg.automation.billing_package_service.common.models.BPSSaveCountryRequest; import com.vuclip.premiumengg.automation.billing_package_service.common.models.BPSSavePartnerRequest; import com.vuclip.premiumengg.automation.billing_package_service.common.models.BPSSaveProductRequest; import com.vuclip.premiumengg.automation.billing_package_service.common.models.BillingPackage; /** * Created by <NAME> */ public class BPSContext { public static BPSSaveCountryRequest saveCountryRequest; public static BPSSaveProductRequest saveProductRequest; public static BPSSavePartnerRequest savePartnerRequest; public static BillingPackage billingPackage; } <file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.tests; import org.apache.commons.lang3.RandomUtils; import org.apache.log4j.Logger; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.vuclip.premiumengg.automation.common.JDBCTemplate; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils.RabbitUtil; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils.SASUtils; /** * @author rahul.sahu */ public class SASWinBackFlowTest { private static Logger logger = Log4J.getLogger("SASActivationDeactivationSuccessTest"); int productId; int partnerId; private String countryCode = "IN"; @BeforeClass(alwaysRun = true) public void setup() throws Exception { productId = SASUtils.productId; partnerId = productId; } @DataProvider(name = "SASWinBackFlowTestdp") public Object[][] activationDeactivationPostiveDataProvider() { return new Object[][]{ /* SECONDTIMEFIX */{"CHARGING", "WINBACK", "ACTIVATED", "SUCCESS", "renewal", "OPEN", "IN_PROGRESS", "SUCCESS", "RENEWAL", "RENEWAL", "RENEWAL", "CHARGING", "RENEWAL", "ACTIVATED", "SUCCESS", "renewal", "OPEN", "IN_PROGRESS", "RENEWAL", "RENEWAL", "RENEWAL"}, // /* SECONDTIMEFIX */ {"CHARGING", "WINBACK", "ACTIVATED", "SUCCESS", "renewal", "OPEN", "IN_PROGRESS", // "FAILURE", "RENEWAL", "RENEWAL", "RENEWAL", "CHARGING", "RENEWAL", "ACTIVATED", "FAILURE", // "renewal", "OPEN", "IN_PROGRESS", "RENEWAL", "RENEWAL", "RENEWAL"}, // // /* SECONDTIMEFIX */{"CHARGING", "WINBACK", "ACTIVATED", "SUCCESS", "renewal", "OPEN", "IN_PROGRESS", // "ERROR", "RENEWAL", "RENEWAL", "RENEWAL", "CHARGING", "RENEWAL", "ACTIVATED", "ERROR", // "renewal", "OPEN", "IN_PROGRESS", "RENEWAL", "RENEWAL", "RENEWAL"}, // // /* SECONDTIMEFIX */{"CHARGING", "WINBACK", "ACTIVATED", "SUCCESS", "renewal", "OPEN", "IN_PROGRESS", // "ERROR", "RENEWAL", "RENEWAL", "RENEWAL", "CHARGING", "RENEWAL", "SUSPEND", "ERROR", "renewal", // "OPEN", "IN_PROGRESS", "RENEWAL", "RENEWAL", "RENEWAL"}, // // /* SECONDTIMEFIX */ {"CHARGING", "WINBACK", "ACTIVATED", "SUCCESS", "renewal", "OPEN", "IN_PROGRESS", // "FAILURE", "RENEWAL", "RENEWAL", "RENEWAL", "CHARGING", "RENEWAL", "SUSPEND", "FAILURE", // "renewal", "OPEN", "IN_PROGRESS", "RENEWAL", "RENEWAL", "RENEWAL"}, /* SECONDTIMEFIX */{"CHARGING", "WINBACK", "PARKING", "LOW_BALANCE", "winback", "OPEN", "IN_PROGRESS", "SUCCESS", "WINBACK", "WINBACK", "WINBACK", "CHARGING", "WINBACK", "ACTIVATED", "SUCCESS", "renewal", "OPEN", "IN_PROGRESS", "RENEWAL", "RENEWAL", "RENEWAL"}, /* SECONDTIMEFIX */{"CHARGING", "WINBACK", "PARKING", "LOW_BALANCE", "winback", "OPEN", "IN_PROGRESS", "ERROR", "WINBACK", "WINBACK", "WINBACK", "CHARGING", "WINBACK", "PARKING", "ERROR", "winback", "OPEN", "IN_PROGRESS", "WINBACK", "WINBACK", "WINBACK"}, /* SECONDTIMEFIX */{"CHARGING", "WINBACK", "PARKING", "LOW_BALANCE", "winback", "OPEN", "IN_PROGRESS", "LOW_BALANCE", "WINBACK", "WINBACK", "WINBACK", "CHARGING", "WINBACK", "PARKING", "LOW_BALANCE", "winback", "OPEN", "IN_PROGRESS", "WINBACK", "WINBACK", "WINBACK"}, }; } @Test(dataProvider = "SASWinBackFlowTestdp", groups = {"bug"}) public void SASWinBackFlowTests(String eventActionType, String activityType, String currentSubscriptionState, String transactionState, String actionTable, String beforeSchedularStatus, String afterSchedularStatus, String afteNewEventStatus, String schedularActivityType, String queueName, String queueActivity, String newEventActionType, String newActivityType, String newCurrentSubscriptionState, String newTransactionState, String newActionTable, String newBeforeSchedularStatus, String newAfterSchedularStatus, String newSchedularActivityType, String newQueueName, String newQueueActivityType) { Integer subscriptionId = RandomUtils.nextInt(58000, 59000); String testMessage = subscriptionId + " " + activityType + " " + currentSubscriptionState + " " + transactionState + " " + actionTable + " " + newCurrentSubscriptionState + " " + newTransactionState + " " + newActionTable; logger.info("***************Starting SASWinBackFlowTest [ " + testMessage + " ]"); RabbitUtil.purgeAllActivityQueue(productId, partnerId, countryCode); try { JDBCTemplate.getDbConnection().update( "INSERT INTO `scheduled_activity_service`.`winback` (`product_id`, `partner_id`, `country_code`, `date`, `subscription_id`, `attempt_number`, `is_eligible`, `status`, `user_id`) VALUES" + " ('" + productId + "', '" + partnerId + "', '" + countryCode + "', '1522849806000', '" + subscriptionId + "', '2', '1', 'IN_PROGRESS', 'u-23xyz');"); SASUtils.executeActivityFlows(subscriptionId, productId, partnerId, countryCode, eventActionType, activityType, currentSubscriptionState, transactionState, actionTable, beforeSchedularStatus, afterSchedularStatus, afteNewEventStatus, schedularActivityType, queueName, queueActivity, newEventActionType, newActivityType, newCurrentSubscriptionState, newTransactionState, newActionTable, newBeforeSchedularStatus, newAfterSchedularStatus, newSchedularActivityType, newQueueName, newQueueActivityType); } catch (Exception e) { e.printStackTrace(); logger.info("=========>ERROR due to exception"); Assert.fail(e.getMessage()); } } } <file_sep>package com.vuclip.premiumengg.automation.subscription_service.common.models; import lombok.AllArgsConstructor; import lombok.Getter; @AllArgsConstructor @Getter public enum StateTransitionData { ACTIVATION_LOWBALANCE(0, "MY", "D_KIM_87348", "WAP", 69232L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1111111122", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACT_INIT", 30, "1111111122", "ACTIVE", 4, 1, 7, "CHARGING", "ACTIVATION", "LOW_BALANCE", true, "SUCCESS", "PARKING", "end_date", "start_date", "subscription_status", "parking_validity"), ACTIVATION_FAILURE(0, "MY", "D_KIM_87348", "WAP", 69226L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1544034600000L, "1111111116", 1535520606000L, 0, 8181, 8181, 1543602600000L, null, 0, "BC03", "ACT_INIT", 30, "1111111116", "ACTIVATION_IN_PROGRESS", 4, 1, 6, "CHARGING", "ACTIVATION", "FAILURE", true, "SUCCESS", "ACT_INIT", "end_date", "start_date", "subscription_status", "act_init_validity"), ACTIVATION_ERROR(0, "MY", "D_KIM_87348", "WAP", 69227L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1111111117", 1535520606000L, 0, 8181, 8181, 1929724200000L, null, 0, "BC03", "ACT_INIT", 30, "1111111117", "ACTIVATION_IN_PROGRESS", 4, 1, 7, "CHARGING", "ACTIVATION", "ERROR", true, "SUCCESS", "ACT_INIT", "end_date", "start_date", "subscription_status", "act_init_validity"), ACTIVATION_SUCESS(0, "MY", "D_KIM_87348", "WAP", 69225L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1111111115", 1535520606000L, 0, 8181, 8181, 1929724200000L, null, 0, "BC03", "ACT_INIT", 30, "1111111115", "ACTIVE", 4, 1, 5, "CHARGING", "ACTIVATION", "SUCCESS", true, "SUCCESS", "ACTIVATED", "end_date", "start_date", "subscription_status", "validity"), ACTIVATION_CONSENT_OPEN(0, "MY", "D_KIM_87348", "WAP", 69225L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1111111115", 1935520606000L, 0, 8181, 8181, 1835520606000L, null, 0, "BC03", "ACT_INIT", 30, "1111111115", "ACTIVE", 4, 1, 5, "CONSENT", "ACTIVATION", "CONFIRMED", true, "SUCCESS", "ACTIVATED", "end_date", "start_date", "subscription_status", "validity"), ACTIVATION_CONSENT_CLOSE(0, "MY", "D_KIM_87348", "WAP", 69225L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1111111115", 1935520606000L, 0, 8181, 8181, 1835520606000L, null, 0, "BC03", "ACT_INIT", 30, "1111111115", "ACTIVE", 4, 1, 5, "CONSENT", "ACTIVATION", "CONFIRMED", false, "SUCCESS", "ACTIVATED", "end_date", "start_date", "subscription_status", "validity"), ACTIVATION_PARKING_NOVALIDITY(0, "MY", "D_KIM_87348", "WAP", 69234L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC01", "BC01", 0, null, 0.0, 1930253086000L, "1111111124", 1544077086000L, 0, 8181, 8181, 1544077086000L, null, 0, "BC01", "ACT_INIT", 30, "1111111124", "ACTIVE_NO_VALIDITY", 4, 1, 7, "CHARGING", "ACTIVATION", "LOW_BALANCE", true, "SUCCESS", "PARKING", "end_date", "start_date", "subscription_status", "parking_validity"), ACTIVATION_REGISTRATION_CLOSED(0, "MY", "D_KIM_87348", "WAP", 69228L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1544077086000L, "1111111118", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACT_INIT", 30, "1111111118", "ACTIVE", 4, 1, 7, "REGISTRATION", "ACTIVATION", "SUCCESS", true, "SUCCESS", "ACTIVATED", "end_date", "start_date", "subscription_status", "act_init_validity"), ACTIVATION_REGISTRATION_OPEN(0, "MY", "D_KIM_87348", "WAP", 69229L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1544077086000L, "1111111119", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACT_INIT", 30, "1111111119", "ACTIVATION_IN_PROGRESS", 4, 1, 7, "REGISTRATION", "ACTIVATION", "SUCCESS", false, "SUCCESS", "ACT_INIT", "end_date", "start_date", "subscription_status", "act_init_validity"), ACTIVATION_REGISTRATION_ERROR(0, "MY", "D_KIM_87348", "WAP", 69230L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1544077086000L, "1111111120", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACT_INIT", 30, "1111111120", "ACTIVATION_IN_PROGRESS", 4, 1, 7, "REGISTRATION", "ACTIVATION", "ERROR", true, "SUCCESS", "ACT_INIT", "end_date", "start_date", "subscription_status", "act_init_validity"), ACTIVATION_REGISTRATION_FAILURE(0, "MY", "D_KIM_87348", "WAP", 69231L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1544077086000L, "1111111121", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACT_INIT", 30, "1111111121", "ACTIVATION_IN_PROGRESS", 4, 1, 7, "REGISTRATION", "ACTIVATION", "FAILURE", true, "SUCCESS", "ACT_INIT", "end_date", "start_date", "subscription_status", "act_init_validity"), RETRYACTIVATIONSUCESS(0, "MY", "D_KIM_87348", "WAP", 79225L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "7111111115", 1535520606000L, 0, 8181, 8181, 1530253086000L, null, 0, "BC03", "ACT_INIT", 30, "7111111115", "ACTIVE", 4, 1, 5, "CHARGING", "ACTIVATION_RETRY", "SUCCESS", true, "SUCCESS", "ACTIVATED", "end_date", "start_date", "subscription_status", "validity"), RETRYACTIVATIONFAILURE(0, "MY", "D_KIM_87348", "WAP", 79226L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "7111111116", 1535520606000L, 0, 8181, 8181, 1530253086000L, null, 0, "BC03", "ACT_INIT", 30, "7111111116", "ACTIVATION_IN_PROGRESS", 4, 1, 6, "CHARGING", "ACTIVATION_RETRY", "FAILURE", true, "SUCCESS", "ACT_INIT", "end_date", "start_date", "subscription_status", "act_init_validity"), RETRYACTIVATIONERROR(0, "MY", "D_KIM_87348", "WAP", 79227L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "7111111117", 1535520606000L, 0, 8181, 8181, 1530253086000L, null, 0, "BC03", "ACT_INIT", 30, "7111111117", "ACTIVATION_IN_PROGRESS", 4, 1, 7, "CHARGING", "ACTIVATION_RETRY", "ERROR", true, "SUCCESS", "ACT_INIT", "end_date", "start_date", "subscription_status", "act_init_validity"), RETRYACTIVATIONREGISTRATION(0, "MY", "D_KIM_87348", "WAP", 79228L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1544077086000L, "7111111118", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACT_INIT", 30, "7111111118", "ACTIVE", 4, 1, 7, "REGISTRATION", "ACTIVATION_RETRY", "SUCCESS", true, "SUCCESS", "ACTIVATED", "end_date", "start_date", "subscription_status", "act_init_validity"), RETRYACTIVATIONREGISTRATIONOPEN(0, "MY", "D_KIM_87348", "WAP", 79229L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1544077086000L, "7111111119", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACT_INIT", 30, "7111111119", "ACTIVATION_IN_PROGRESS", 4, 1, 7, "REGISTRATION", "ACTIVATION_RETRY", "SUCCESS", false, "SUCCESS", "ACT_INIT", "end_date", "start_date", "subscription_status", "act_init_validity"), RETRYREGISTRATIONERROR(0, "MY", "D_KIM_87348", "WAP", 79230L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1544077086000L, "7111111120", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACT_INIT", 30, "7111111120", "ACTIVATION_IN_PROGRESS", 4, 1, 7, "REGISTRATION", "ACTIVATION_RETRY", "ERROR", true, "SUCCESS", "ACT_INIT", "end_date", "start_date", "subscription_status", "act_init_validity"), RETRYACTIVATIONPARKING(0, "MY", "D_KIM_87348", "WAP", 79232L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "7111111122", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACT_INIT", 30, "7111111122", "ACTIVE", 4, 1, 7, "CHARGING", "ACTIVATION_RETRY", "LOW_BALANCE", true, "SUCCESS", "PARKING", "end_date", "start_date", "subscription_status", "parking_validity"), RETRYACTIVATIONPARKINGWOVALIDITY(0, "MY", "D_KIM_87348", "WAP", 79234L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC01", "BC01", 0, null, 0.0, 1944077086000L, "7111111124", 1544077086000L, 0, 8181, 8181, 1544077086000L, null, 0, "BC01", "ACT_INIT", 30, "7111111124", "ACTIVE_NO_VALIDITY", 4, 1, 7, "CHARGING", "ACTIVATION_RETRY", "LOW_BALANCE", true, "SUCCESS", "PARKING", "end_date", "start_date", "subscription_status", "parking_validity"), RETRYREGISTRATIONFAILURE(0, "MY", "D_KIM_87348", "WAP", 79231L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1544077086000L, "7111111121", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACT_INIT", 30, "7111111121", "ACTIVATION_IN_PROGRESS", 4, 1, 7, "REGISTRATION", "ACTIVATION_RETRY", "FAILURE", true, "SUCCESS", "ACT_INIT", "end_date", "start_date", "subscription_status", "act_init_validity"), WINBACKSUCESS(0, "MY", "D_KIM_87348", "WAP", 74448L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1944077086000L, "8111111115", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "PARKING", 30, "8111111115", "ACTIVE", 4, 1, 5, "CHARGING", "WINBACK", "SUCCESS", true, "SUCCESS", "ACTIVATED", "end_date", "start_date", "subscription_status", "validity"), WINBACKLOWBAL(0, "MY", "D_KIM_87348", "WAP", 748728L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1944077086000L, "8111111116", 1530253086000L, 0, 8181, 8181, 1530253086000L, null, 0, "BC03", "PARKING", 30, "8111111116", "ACTIVE", 4, 1, 5, "CHARGING", "WINBACK", "LOW_BALANCE", true, "SUCCESS", "PARKING", "end_date", "start_date", "subscription_status", "parking_validity"), WINBACKLOWERROR(0, "MY", "D_KIM_87348", "WAP", 798728L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1944077086000L, "8111111117", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "PARKING", 30, "8111111117", "ACTIVE", 4, 1, 5, "CHARGING", "WINBACK", "ERROR", true, "SUCCESS", "PARKING", "end_date", "start_date", "subscription_status", "parking_validity"), RENEWALINITSUCCESS(0, "MY", "D_KIM_87348", "WAP", 99228L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1944077086000L, "9111111118", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACT_INIT", 30, "9111111118", "ACTIVE", 4, 1, 7, "CHARGING", "RENEWAL", "SUCCESS", true, "SUCCESS", "ACTIVATED", "end_date", "start_date", "subscription_status", "validity"), RENEWALINITLOWB(0, "MY", "D_KIM_87348", "WAP", 99229L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1944077086000L, "9111111119", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACT_INIT", 30, "9111111119", "ACTIVE", 4, 1, 7, "CHARGING", "RENEWAL", "LOW_BALANCE", true, "SUCCESS", "SUSPEND", "end_date", "start_date", "subscription_status", "suspend_validity"), RENEWALINITERROR(0, "MY", "D_KIM_87348", "WAP", 99226L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1944077086000L, "9111131117", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACT_INIT", 30, "9113111117", "ACTIVATION_IN_PROGRESS", 4, 1, 7, "CHARGING", "RENEWAL", "ERROR", true, "SUCCESS", "ACT_INIT", "end_date", "start_date", "subscription_status", "act_init_validity"), RENEWALINITFAILURE(0, "MY", "D_KIM_87348", "WAP", 99227L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "9411111117", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACT_INIT", 30, "9411111117", "ACTIVE", 4, 1, 7, "CHARGING", "RENEWAL", "FAILURE", true, "FAILURE", "SUSPEND", "end_date", "start_date", "subscription_status", "suspend_validity"), RENEWALACTSUCCESS(0, "MY", "D_KIM_87348", "WAP", 92228L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1944077086000L, "9211111118", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACTIVATED", 30, "9211111118", "ACTIVE", 4, 1, 7, "CHARGING", "RENEWAL", "SUCCESS", true, "SUCCESS", "ACTIVATED", "end_date", "start_date", "subscription_status", "validity"), RENEWALACTERRSUCCESS(0, "MY", "D_KIM_87348", "WAP", 93228L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1944077086000L, "9311111118", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACTIVATED", 30, "9311111118", "ACTIVE", 4, 1, 7, "CHARGING", "RENEWAL", "ERROR", true, "SUCCESS", "ACTIVATED", "end_date", "start_date", "subscription_status", "validity"), RENEWALACTSUSPENDLOWB(0, "MY", "D_KIM_87348", "WAP", 95228L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1944077086000L, "9511111118", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACTIVATED", 30, "9511111118", "ACTIVE", 4, 1, 7, "CHARGING", "RENEWAL", "LOW_BALANCE", true, "SUCCESS", "SUSPEND", "end_date", "start_date", "subscription_status", "suspend_validity"), RENEWALACTSUSPENDFAIL(0, "MY", "D_KIM_87348", "WAP", 96228L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1944077086000L, "9611111118", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "ACTIVATED", 30, "9611111118", "ACTIVE", 4, 1, 7, "CHARGING", "RENEWAL", "FAILURE", true, "SUCCESS", "SUSPEND", "end_date", "start_date", "subscription_status", "suspend_validity"), RENEWALSUSPENDFAIL(0, "MY", "D_KIM_87348", "WAP", 97228L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1944077086000L, "9711111118", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "SUSPEND", 30, "9711111118", "ACTIVE", 4, 1, 7, "CHARGING", "RENEWAL", "FAILURE", true, "SUCCESS", "SUSPEND", "end_date", "start_date", "subscription_status", "suspend_validity"), RENEWALSUSPENDERR(0, "MY", "D_KIM_87348", "WAP", 98228L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1944077086000L, "9681111118", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "SUSPEND", 30, "9681111118", "ACTIVE", 4, 1, 7, "CHARGING", "RENEWAL", "ERROR", true, "SUCCESS", "SUSPEND", "end_date", "start_date", "subscription_status", "suspend_validity"), RENEWALSUSPENDLOWB(0, "MY", "D_KIM_87348", "WAP", 992289L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1944077086000L, "9911111118", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "SUSPEND", 30, "9911111118", "ACTIVE", 4, 1, 7, "CHARGING", "RENEWAL", "LOW_BALANCE", true, "SUCCESS", "SUSPEND", "end_date", "start_date", "subscription_status", "suspend_validity"), RENEWALSUSSUCCESS(0, "MY", "D_KIM_87348", "WAP", 94228L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1944077086000L, "9411111118", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "SUSPEND", 30, "9411111118", "ACTIVE", 4, 1, 7, "CHARGING", "RENEWAL", "SUCCESS", true, "SUCCESS", "ACTIVATED", "end_date", "start_date", "subscription_status", "validity"), DEACTIVATIONRETRYERR(0, "MY", "D_KIM_87348", "WAP", 9090L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1544077086000L, "9421111117", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "DCT_INIT", 30, "9421111117", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION_RETRY", "ERROR", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONRETRYFAIL(0, "MY", "D_KIM_87348", "WAP", 9091L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1544077086000L, "9421111111", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "DCT_INIT", 30, "9421111111", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION_RETRY", "FAILURE", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONRETRYSUCCESS(0, "MY", "D_KIM_87348", "WAP", 9092L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1544077086000L, "9421111112", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "DCT_INIT", 30, "9421111112", "INACTIVE_WITH_VALIDITY", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION_RETRY", "SUCCESS", true, "SUCCESS", "DEACTIVATED", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONRETRYPROCESSBLACKLISTSUCCESS(0, "MY", "D_KIM_87348", "WAP", 90920L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1544077086000L, "9421221112", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "DCT_INIT", 30, "9421221112", "INACTIVE_WITH_VALIDITY", 4, 1, 7, "PROCESS_BLACKLIST", "DEACTIVATION_RETRY", "SUCCESS", true, "SUCCESS", "DEACTIVATED", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONRETRYPROCESSBLACKLISTFAIL(0, "MY", "D_KIM_87348", "WAP", 90910L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1544077086000L, "9421331112", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "DCT_INIT", 30, "9421331112", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_BLACKLIST", "DEACTIVATION_RETRY", "FAILURE", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONRETRYPROCESSBLACKLISTERR(0, "MY", "D_KIM_87348", "WAP", 909122L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1544077086000L, "9421441112", 1545805086000L, 0, 8181, 8181, 1543645086000L, null, 0, "BC03", "DCT_INIT", 30, "9421441112", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_BLACKLIST", "DEACTIVATION_RETRY", "ERROR", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), CHURNINITSUCCESS(0, "MY", "D_KIM_87348", "WAP", 1237L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1234567893", 1530253086000L, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACT_INIT", 30, "1234567893", "INACTIVE_WITH_VALIDITY", 4, 1, 7, "PROCESS_DEACTIVATE", "SYSTEM_CHURN", "SUCCESS", true, "SUCCESS", "DEACTIVATED", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), CHURNINITFAIL(0, "MY", "D_KIM_87348", "WAP", 1234L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1234567890", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACT_INIT", 30, "1234567890", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "SYSTEM_CHURN", "FAILURE", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), CHURNINITNPROGRESS(0, "MY", "D_KIM_87348", "WAP", 1236L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1234567892", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACT_INIT", 30, "1234567892", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "SYSTEM_CHURN", "IN_PROGRESS", false, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), CHURNINITERR(0, "MY", "D_KIM_87348", "WAP", 1235L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1234567891", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACT_INIT", 30, "1234567891", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "SYSTEM_CHURN", "ERROR", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), CHURNSUSSUCCESS(0, "MY", "D_KIM_87348", "WAP", 1238L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1234567894", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "SUSPEND", 30, "1234567894", "INACTIVE_WITH_VALIDITY", 4, 1, 7, "PROCESS_DEACTIVATE", "SYSTEM_CHURN", "SUCCESS", true, "SUCCESS", "DEACTIVATED", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), CHURNSUSFAIL(0, "MY", "D_KIM_87348", "WAP", 1239L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1234567895", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "SUSPEND", 30, "1234567895", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "SYSTEM_CHURN", "FAILURE", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), CHURNSUSNPROGRESS(0, "MY", "D_KIM_87348", "WAP", 1240L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1234567896", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "SUSPEND", 30, "1234567896", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "SYSTEM_CHURN", "IN_PROGRESS", false, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), CHURNSUSERR(0, "MY", "D_KIM_87348", "WAP", 1241L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1234567897", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "SUSPEND", 30, "1234567897", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "SYSTEM_CHURN", "ERROR", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), CHURNPRKSUCCESS(0, "MY", "D_KIM_87348", "WAP", 1242L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1234567814", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "PARKING", 30, "1234567814", "INACTIVE_WITH_VALIDITY", 4, 1, 7, "PROCESS_DEACTIVATE", "SYSTEM_CHURN", "SUCCESS", true, "SUCCESS", "DEACTIVATED", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), CHURNPRKFAIL(0, "MY", "D_KIM_87348", "WAP", 1243L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1234567815", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "PARKING", 30, "1234567815", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "SYSTEM_CHURN", "FAILURE", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), CHURNPRKINPROGRESS(0, "MY", "D_KIM_87348", "WAP", 1244L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1234567816", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "PARKING", 30, "1234567816", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "SYSTEM_CHURN", "IN_PROGRESS", false, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), CHURNPRKERR(0, "MY", "D_KIM_87348", "WAP", 1245L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1234567817", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "PARKING", 30, "1234567817", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "SYSTEM_CHURN", "ERROR", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), CHURNACTSUCCESS(0, "MY", "D_KIM_87348", "WAP", 1228L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1234567824", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACTIVATED", 30, "1234567824", "INACTIVE_WITH_VALIDITY", 4, 1, 7, "PROCESS_DEACTIVATE", "SYSTEM_CHURN", "SUCCESS", true, "SUCCESS", "DEACTIVATED", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), CHURNACTFAIL(0, "MY", "D_KIM_87348", "WAP", 1229L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1234567825", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACTIVATED", 30, "1234567825", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "SYSTEM_CHURN", "FAILURE", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), CHURNACTNPROGRESS(0, "MY", "D_KIM_87348", "WAP", 1220L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1234567826", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACTIVATED", 30, "1234567826", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "SYSTEM_CHURN", "IN_PROGRESS", false, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), CHURNACTERR(0, "MY", "D_KIM_87348", "WAP", 1221L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "1234567827", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACT_INIT", 30, "1234567827", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "SYSTEM_CHURN", "ERROR", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONINITCNFFALSE(0, "MY", "D_KIM_87348", "WAP", 2230L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "2123456789", 1530253086000L, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACT_INIT", 30, "2123456789", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "DEACTIVATE_CONSENT", "DEACTIVATION", "CONFIRMED", false, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONINITCNFTRUE(0, "MY", "D_KIM_87348", "WAP", 2231L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "2234567891", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACT_INIT", 30, "2234567891", "INACTIVE_WITH_VALIDITY", 4, 1, 7, "DEACTIVATE_CONSENT", "DEACTIVATION", "CONFIRMED", true, "SUCCESS", "DEACTIVATED", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONINITSUCCESS(0, "MY", "D_KIM_87348", "WAP", 2233L, "2018-06-29 11:47:54", 1930253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "2234567892", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACT_INIT", 30, "2234567892", "INACTIVE_WITH_VALIDITY", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "SUCCESS", true, "SUCCESS", "DEACTIVATED", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONINITPROGRESS(0, "MY", "D_KIM_87348", "WAP", 2234L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "2234567893", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACT_INIT", 30, "2234567893", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "IN_PROGRESS", false, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONINITFAIL(0, "MY", "D_KIM_87348", "WAP", 2235L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "2234567894", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACT_INIT", 30, "2234567894", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "FAILURE", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONINITERR(0, "MY", "D_KIM_87348", "WAP", 2236L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "2234567895", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACT_INIT", 30, "2234567895", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "ERROR", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONSUSCNFFALSE(0, "MY", "D_KIM_87348", "WAP", 3230L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "3234567890", 1530253086000L, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "SUSPEND", 30, "3234567893", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "DEACTIVATE_CONSENT", "DEACTIVATION", "CONFIRMED", false, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONSUSCNFTRUE(0, "MY", "D_KIM_87348", "WAP", 3231L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "3234567891", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "SUSPEND", 30, "3234567891", "INACTIVE_WITH_VALIDITY", 4, 1, 7, "DEACTIVATE_CONSENT", "DEACTIVATION", "CONFIRMED", true, "SUCCESS", "DEACTIVATED", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONSUSSUCCESS(0, "MY", "D_KIM_87348", "WAP", 3233L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "3234567892", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "SUSPEND", 30, "3234567892", "INACTIVE_WITH_VALIDITY", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "SUCCESS", true, "SUCCESS", "DEACTIVATED", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONSUSPROGRESS(0, "MY", "D_KIM_87348", "WAP", 3234L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "32345678931", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "SUSPEND", 30, "32345678931", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "IN_PROGRESS", false, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONSUSFAIL(0, "MY", "D_KIM_87348", "WAP", 3235L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "3234567894", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "SUSPEND", 30, "3234567894", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "FAILURE", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONSUSERR(0, "MY", "D_KIM_87348", "WAP", 3236L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "3234567895", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "SUSPEND", 30, "3234567895", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "ERROR", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONPRKCNFFALSE(0, "MY", "D_KIM_87348", "WAP", 4230L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "4234567890", 1530253086000L, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "PARKING", 30, "4234567893", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "DEACTIVATE_CONSENT", "DEACTIVATION", "CONFIRMED", false, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONPRKCNFTRUE(0, "MY", "D_KIM_87348", "WAP", 4231L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "4234567891", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "PARKING", 30, "4234567891", "INACTIVE_WITH_VALIDITY", 4, 1, 7, "DEACTIVATE_CONSENT", "DEACTIVATION", "CONFIRMED", true, "SUCCESS", "DEACTIVATED", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONPRKSUCCESS(0, "MY", "D_KIM_87348", "WAP", 4233L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "4234567892", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "PARKING", 30, "4234567892", "INACTIVE_WITH_VALIDITY", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "SUCCESS", true, "SUCCESS", "DEACTIVATED", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONPRKPROGRESS(0, "MY", "D_KIM_87348", "WAP", 4234L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "42345678932", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "PARKING", 30, "42345678932", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "IN_PROGRESS", false, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONPRKFAIL(0, "MY", "D_KIM_87348", "WAP", 4235L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "4234567894", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "PARKING", 30, "4234567894", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "FAILURE", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONPRKERR(0, "MY", "D_KIM_87348", "WAP", 4236L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "4234567895", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "PARKING", 30, "4234567895", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "ERROR", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONACTCNFFALSE(0, "MY", "D_KIM_87348", "WAP", 5230L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "5234567890", 1530253086000L, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACTIVATED", 30, "5234567893", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "DEACTIVATE_CONSENT", "DEACTIVATION", "CONFIRMED", false, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONACTCNFTRUE(0, "MY", "D_KIM_87348", "WAP", 5231L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "5234567891", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACTIVATED", 30, "5234567891", "INACTIVE_WITH_VALIDITY", 4, 1, 7, "DEACTIVATE_CONSENT", "DEACTIVATION", "CONFIRMED", true, "SUCCESS", "DEACTIVATED", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONACTSUCCESS(0, "MY", "D_KIM_87348", "WAP", 5233L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "5234567892", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACTIVATED", 30, "5234567892", "INACTIVE_WITH_VALIDITY", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "SUCCESS", true, "SUCCESS", "DEACTIVATED", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONACTPROGRESS(0, "MY", "D_KIM_87348", "WAP", 5234L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "52345678935", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACTIVATED", 30, "52345678935", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "IN_PROGRESS", false, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONACTFAIL(0, "MY", "D_KIM_87348", "WAP", 5235L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "5234567894", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACTIVATED", 30, "5234567894", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "FAILURE", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONACTERR(0, "MY", "D_KIM_87348", "WAP", 5236L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "5234567895", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "ACTIVATED", 30, "5234567895", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "ERROR", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONDNITSUCCESS(0, "MY", "D_KIM_87348", "WAP", 6233L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "6234567892", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "DCT_INIT", 30, "6234567892", "INACTIVE_WITH_VALIDITY", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "SUCCESS", true, "SUCCESS", "DEACTIVATED", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONDINITFAIL(0, "MY", "D_KIM_87348", "WAP", 6235L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "6234567894", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "DCT_INIT", 30, "6234567894", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "FAILURE", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"), DEACTIVATIONDINITERR(0, "MY", "D_KIM_87348", "WAP", 6236L, "2018-06-29 11:47:54", 1530253086000L, 0, "BC03", "BC03", 0, null, 0.0, 1930253086000L, "6234567895", null, 0, 8181, 8181, 1929810600000L, null, 0, "BC03", "DCT_INIT", 30, "6234567895", "DEACTIVATION_IN_PROGRESS", 4, 1, 7, "PROCESS_DEACTIVATE", "DEACTIVATION", "ERROR", true, "SUCCESS", "DCT_INIT", "end_date", "start_date", "subscription_status", "deactivation_retry_validity"); int renewalAllowed; String country; String userSource; String mode; Long subscription_id; String created_on; Long activation_date; int blacklisted; String charged_billing_code; String fallbackBillingCode; int cooldowned; Long deactivation_date; Double chargedPrice; Long end_date; String msisdn; Long next_billing_date; int paid; int partner_id; int product_id; Long start_date; String sub_type; int subscribable; String subscription_billing_code; String subscription_status; int validity_days; String user_id; String summary; Integer actionId; Integer activityId; Integer transactionStateId; String action_Id; String activity_Id; String transaction_StateId; Boolean closed; String actionResult; String subscriptionStatusNew; String endDateColumn; String startUpdateColumn; String statusColumn; String validityColumn; } <file_sep> package com.vuclip.premiumengg.automation.subscription_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.Getter; import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "successful", "message", "responseCode", "status" }) @Getter @Setter public class GetUserStatusResponse { @JsonProperty("successful") private Boolean successful; @JsonProperty("message") private String message; @JsonProperty("responseCode") private String responseCode; @JsonProperty("status") private Status status; } <file_sep>package com.vuclip.premiumengg.automation.billing_package_service.common.models; /** * Created by Kohitij_Das on 22/03/18. */ public enum BillingResponse { SUCCESS(true, 200, "Success"), NOTFOUND(false, 404, "No billing packages found"), BADREQUEST(false, 400, "productId : cannot be null"); private final boolean successful; private final int responseCode; private final String message; BillingResponse(boolean successful, int responseCode, String message) { this.successful = successful; this.responseCode = responseCode; this.message = message; } public boolean isSuccessful() { return successful; } public int getResponseCode() { return responseCode; } public String getMessage() { return message; } } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.utils; import org.apache.log4j.Logger; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.configuration_service.common.models.PartnerRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.PartnerResponseVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.PartnerVO; public class PartnerUtil { public static int productId; private static Logger logger = Log4J.getLogger("PartnerUtil"); public static PartnerRequestVO createMockRequestVO(Object... params) { logger.info("Create mock reqeust for partner"); return PartnerRequestVO.builder().partnerName((String) params[0]).description((String) params[1]) .status((String) params[2]).autoRenewalApplicable((boolean) params[3]).type((String) params[4]) .stepUpCharging((boolean) params[5]).userIdentifier((String) params[6]) .balanceCheckRequired((boolean) params[7]).activationManagedBy((String) params[8]) .renewalManagedBy((String) params[9]).deactivationManagedBy((String) params[10]) .hasMoActivations((boolean) params[11]).hasMoDeactivations((boolean) params[12]) .partnerActivationConsentParserUrl((String) params[13]) .partnerDeactivationConsentParserUrl((String) params[14]) .partnerActivationConsentInitiationUrl((String) params[15]) .partnerDeactivationConsentInitiationUrl((String) params[16]).build(); } public static PartnerResponseVO getMockPartnerVO(PartnerRequestVO request, String operationType, boolean isSuccessful, int responseCode, String message) { logger.info("Get mock reqeust for partner"); return PartnerResponseVO.builder() .partner(new PartnerVO(0, request.getPartnerName(), request.getDescription(), request.getStatus(), request.isAutoRenewalApplicable(), request.getType(), request.isStepUpCharging(), request.getUserIdentifier(), request.isBalanceCheckRequired(), request.getActivationManagedBy(), request.getRenewalManagedBy(), request.getDeactivationManagedBy(), request.isHasMoActivations(), request.isHasMoDeactivations(), operationType,request.getPartnerActivationConsentParserUrl(), request.getPartnerDeactivationConsentParserUrl(), request.getPartnerActivationConsentInitiationUrl(), request.getPartnerDeactivationConsentInitiationUrl() )) .successful(isSuccessful).responseCode(responseCode).message(message).build(); } public static int boolToInt(boolean b) { return Boolean.compare(b, false); } } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "countryId", "countryName", "countryCode", "timezone", "currency", "operationType" }) public class CountryVO { @JsonProperty("countryId") private int countryId; @JsonProperty("countryName") private String countryName; @JsonProperty("countryCode") private String countryCode; @JsonProperty("timezone") private String timezone; @JsonProperty("currency") private String currency; @JsonProperty("operationType") private String operationType; /** * No args constructor for use in serialization * */ public CountryVO() { } /** * * @param countryId * @param timezone * @param countryName * @param operationType * @param countryCode * @param currency */ public CountryVO(Integer countryId, String countryName, String countryCode, String timezone, String currency, String operationType) { super(); this.countryId = countryId; this.countryName = countryName; this.countryCode = countryCode; this.timezone = timezone; this.currency = currency; this.operationType = operationType; } @JsonProperty("countryId") public Integer getCountryId() { return countryId; } @JsonProperty("countryId") public void setCountryId(Integer countryId) { this.countryId = countryId; } @JsonProperty("countryName") public String getCountryName() { return countryName; } @JsonProperty("countryName") public void setCountryName(String countryName) { this.countryName = countryName; } @JsonProperty("countryCode") public String getCountryCode() { return countryCode; } @JsonProperty("countryCode") public void setCountryCode(String countryCode) { this.countryCode = countryCode; } @JsonProperty("timezone") public String getTimezone() { return timezone; } @JsonProperty("timezone") public void setTimezone(String timezone) { this.timezone = timezone; } @JsonProperty("currency") public String getCurrency() { return currency; } @JsonProperty("currency") public void setCurrency(String currency) { this.currency = currency; } @JsonProperty("operationType") public String getOperationType() { return operationType; } @JsonProperty("operationType") public void setOperationType(String operationType) { this.operationType = operationType; } }<file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.common.RabbitAdminConnection; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.core.RabbitAdmin; import org.springframework.amqp.rabbit.core.RabbitTemplate; public class RabbitUtil { public static void deleteQueue(RabbitAdmin rabbitAdminConnection, String queueName) { rabbitAdminConnection.deleteQueue(queueName); } public static void purgeQueue(RabbitAdmin rabbitAdminConnection, String queueName) { rabbitAdminConnection.purgeQueue(queueName, false); } public static void deleteAllActivityQueue(Integer productId, Integer partnerId, String country) { try { deleteQueue(RabbitAdminConnection.getRabbitAdminConnection(), getQueueNames(productId, partnerId, country, "ACTIVATION")); deleteQueue(RabbitAdminConnection.getRabbitAdminConnection(), getQueueNames(productId, partnerId, country, "ACTIVATION_RETRY")); deleteQueue(RabbitAdminConnection.getRabbitAdminConnection(), getQueueNames(productId, partnerId, country, "DEACTIVATION")); deleteQueue(RabbitAdminConnection.getRabbitAdminConnection(), getQueueNames(productId, partnerId, country, "DEACTIVATION_RETRY")); deleteQueue(RabbitAdminConnection.getRabbitAdminConnection(), getQueueNames(productId, partnerId, country, "RENEWAL")); deleteQueue(RabbitAdminConnection.getRabbitAdminConnection(), getQueueNames(productId, partnerId, country, "SYSTEM_CHURN")); deleteQueue(RabbitAdminConnection.getRabbitAdminConnection(), getQueueNames(productId, partnerId, country, "WINBACK")); deleteQueue(RabbitAdminConnection.getRabbitAdminConnection(), getQueueNames(productId, partnerId, country, "FREETRIAL_RENEWAL")); } catch (Exception e) { Log4J.getLogger().info("Some error deleting queue before suite "); } } public static void purgeAllActivityQueue(Integer productId, Integer partnerId, String country) { try { purgeQueue(RabbitAdminConnection.getRabbitAdminConnection(), getQueueNames(productId, partnerId, country, "ACTIVATION")); purgeQueue(RabbitAdminConnection.getRabbitAdminConnection(), getQueueNames(productId, partnerId, country, "ACTIVATION_RETRY")); purgeQueue(RabbitAdminConnection.getRabbitAdminConnection(), getQueueNames(productId, partnerId, country, "DEACTIVATION")); purgeQueue(RabbitAdminConnection.getRabbitAdminConnection(), getQueueNames(productId, partnerId, country, "DEACTIVATION_RETRY")); purgeQueue(RabbitAdminConnection.getRabbitAdminConnection(), getQueueNames(productId, partnerId, country, "RENEWAL")); purgeQueue(RabbitAdminConnection.getRabbitAdminConnection(), getQueueNames(productId, partnerId, country, "SYSTEM_CHURN")); purgeQueue(RabbitAdminConnection.getRabbitAdminConnection(), getQueueNames(productId, partnerId, country, "WINBACK")); purgeQueue(RabbitAdminConnection.getRabbitAdminConnection(), getQueueNames(productId, partnerId, country, "FREETRIAL_RENEWAL")); } catch (Exception e) { Log4J.getLogger().info("Some error deleting queue before suite "); } } public static String getQueueName(Integer productId, Integer partnerId, String country, String activity) { Log4J.getLogger().info("activity type"+activity); String activityType = ""; switch (activity) { case "ACTIVATION": activityType = "ACTIVATION"; case "ACTIVATION_RETRY": case "WINBACK": activityType = "ACTIVATION"; case "DEACTIVATION": activityType = "DEACTIVATION"; case "DEACTIVATION_RETRY": activityType = "DEACTIVATION"; case "FREETRIAL_RENEWAL": case "RENEWAL": activityType = "RENEWAL"; case "SYSTEM_CHURN": activityType = "DEACTIVATION"; } Log4J.getLogger().info("new activity type"+activityType); return "" + productId + "_" + partnerId + "_" + country + "_" + activityType + "_SCHEDULEDACTIVITY_COREACTIVITY"; } public static String getQueueNames(Integer productId, Integer partnerId, String country, String activity) { return "" + productId + "_" + partnerId + "_" + country + "_" + activity + "_SCHEDULEDACTIVITY_COREACTIVITY"; } public static Message receive(RabbitTemplate rabbitTemplate, String queueName, long timeInMilli) { timeInMilli = 20; // if (queueName.contains("ACTIVATION_SCHE")) // queueName = queueName.replaceAll("ACTIVATION", "ACTIVATION_RETRY"); // if (queueName.contains("DEACTIVATION_SCHE")) // queueName = queueName.replaceAll("DEACTIVATION", "DEACTIVATION_RETRY"); Log4J.getLogger().info("QUEUE NAME TO FETCH " + queueName); Message message = rabbitTemplate.receive(queueName, timeInMilli); if (message == null) { Log4J.getLogger().info("RabbitMQ: Message is null not able to fetch "); } else return message; String[] qs = queueName.split("_"); Integer productId = Integer.parseInt(qs[0]); Integer partnerId = Integer.parseInt(qs[1]); String country = qs[2]; Log4J.getLogger().info(productId + "_" + partnerId + "_" + country + "ACTIVATION"); message = rabbitTemplate.receive(getQueueNames(productId, partnerId, country, "ACTIVATION"), 10); if (message != null) { Log4J.getLogger().info(new String(message.getBody())); return message; } Log4J.getLogger().info(productId + "_" + partnerId + "_" + country + "ACTIVATION_RETRY"); message = rabbitTemplate.receive(getQueueNames(productId, partnerId, country, "ACTIVATION_RETRY"), 10); if (message != null) { Log4J.getLogger().info(new String(message.getBody())); return message; } Log4J.getLogger().info(productId + "_" + partnerId + "_" + country + "DEACTIVATION"); message = rabbitTemplate.receive(getQueueNames(productId, partnerId, country, "DEACTIVATION"), 10); if (message != null) { Log4J.getLogger().info(new String(message.getBody())); return message; } Log4J.getLogger().info(productId + "_" + partnerId + "_" + country + "DEACTIVATION_RETRY"); message = rabbitTemplate.receive(getQueueNames(productId, partnerId, country, "DEACTIVATION_RETRY"), 10); if (message != null) { Log4J.getLogger().info(new String(message.getBody())); return message; } Log4J.getLogger().info(productId + "_" + partnerId + "_" + country + "RENEWAL"); message = rabbitTemplate.receive(getQueueNames(productId, partnerId, country, "RENEWAL"), 10); if (message != null) { Log4J.getLogger().info(new String(message.getBody())); return message; } Log4J.getLogger().info(productId + "_" + partnerId + "_" + country + "SYSTEM_CHURN"); message = rabbitTemplate.receive(getQueueNames(productId, partnerId, country, "SYSTEM_CHURN"), 10); if (message != null) { Log4J.getLogger().info(new String(message.getBody())); return message; } Log4J.getLogger().info(productId + "_" + partnerId + "_" + country + "WINBACK"); message = rabbitTemplate.receive(getQueueNames(productId, partnerId, country, "WINBACK"), 10); if (message != null) { Log4J.getLogger().info(new String(message.getBody())); return message; } Log4J.getLogger().info(productId + "_" + partnerId + "_" + country + "FREETRIAL_RENEWAL"); message = rabbitTemplate.receive(getQueueNames(productId, partnerId, country, "FREETRIAL_RENEWAL"), 5000); if (message != null) { Log4J.getLogger().info(new String(message.getBody())); return message; } return message; } } <file_sep>package com.vuclip.premiumengg.automation.billing_package_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import groovy.transform.ToString; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"timezone", "currency", "countryName", "countryCode", "operationType"}) @Getter @Setter @ToString @NoArgsConstructor @AllArgsConstructor public class BPSSaveCountryRequest { @JsonProperty("timezone") private String timezone; @JsonProperty("currency") private String currency; @JsonProperty("countryName") private String countryName; @JsonProperty("countryCode") private String countryCode; @JsonProperty("operationType") private String operationType; }<file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"countryCode", "operationType"}) @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString public class Country { @JsonProperty("countryCode") private String countryCode; @JsonProperty("operationType") private String operationType; } <file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.tests; import com.vuclip.premiumengg.automation.common.JDBCTemplate; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.common.RabbitMQConnection; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.models.PublishConfigRequest; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.models.SASQueueResponse; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.models.UserSubscriptionRequest; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils.*; import com.vuclip.premiumengg.automation.utils.DBUtils; import com.vuclip.premiumengg.automation.utils.ObjectMapperUtils; import org.apache.commons.lang3.RandomUtils; import org.apache.log4j.Logger; import org.springframework.amqp.core.Message; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.HashMap; import java.util.Map; /** * @author mayank.bharshiv */ public class SASSystemChurnSuccessTest { private static Logger logger = Log4J.getLogger("SystemChurnSuccessTest"); int productId; int partnerId; PublishConfigRequest publishConfigRequest = null; private SASHelper sasHelper; private String countryCode = "IN"; @BeforeClass(alwaysRun = true) public void setup() throws Exception { sasHelper = new SASHelper(); productId = SASUtils.productId; partnerId = productId; } @DataProvider(name = "systemChurnSuccessPositiveDataProvider") public Object[][] systemChurnSuccessPositiveDataProvider() { return new Object[][]{ /* Passed */ {"DEACTIVATE_CONSENT", "SYSTEM_CHURN", "DCT_INIT", "FAILURE", "churn", "OPEN", "IN_PROGRESS", "FAILURE", "SYSTEM_CHURN", "DEACTIVATE_CONSENT", "SYSTEM_CHURN", "DCT_INIT", "FAILURE", "churn", "OPEN", "IN_PROGRESS", "SYSTEM_CHURN"}, /* Passed */ {"DEACTIVATE_CONSENT", "SYSTEM_CHURN", "DCT_INIT", "FAILURE", "churn", "OPEN", "IN_PROGRESS", "ERROR", "SYSTEM_CHURN", "DEACTIVATE_CONSENT", "SYSTEM_CHURN", "DCT_INIT", "ERROR", "churn", "OPEN", "IN_PROGRESS", "SYSTEM_CHURN"}, /* Passed */ {"DEACTIVATE_CONSENT", "SYSTEM_CHURN", "DCT_INIT", "IN_PROGRESS", "churn", "OPEN", "IN_PROGRESS", "FAILURE", "SYSTEM_CHURN", "DEACTIVATE_CONSENT", "SYSTEM_CHURN", "DCT_INIT", "FAILURE", "churn", "OPEN", "IN_PROGRESS", "SYSTEM_CHURN"}, /* Passed */ {"DEACTIVATE_CONSENT", "SYSTEM_CHURN", "DCT_INIT", "IN_PROGRESS", "churn", "OPEN", "IN_PROGRESS", "ERROR", "SYSTEM_CHURN", "DEACTIVATE_CONSENT", "SYSTEM_CHURN", "DCT_INIT", "ERROR", "churn", "OPEN", "IN_PROGRESS", "SYSTEM_CHURN"}, }; } @Test(dataProvider = "systemChurnSuccessPositiveDataProvider", groups = {"one"}) public void systemChurnSuccessPositiveTests(String eventActionType, String activityType, String currentSubscriptionState, String transactionState, String actionTable, String beforeSchedularStatus, String afterSchedularStatus, String afteNewEventStatus, String queueName, String newEventActionType, String newActivityType, String newCurrentSubscriptionState, String newTransactionState, String newActionTable, String newBeforeSchedularStatus, String newAfterSchedularStatus, String newQueueName) throws Exception { Integer subscriptionId = RandomUtils.nextInt(900, 1000); String testMessage = subscriptionId + " " + activityType + " " + currentSubscriptionState + " " + transactionState + " " + actionTable + " " + newCurrentSubscriptionState + " " + newTransactionState + " " + newActionTable; logger.info("***************Starting System Churn Two Flows Positive Retry test [ " + testMessage + " ]"); try { JDBCTemplate.getDbConnection().update( "INSERT INTO `scheduled_activity_service`.`churn` (`product_id`, `partner_id`, `country_code`, `date`, `subscription_id`, `attempt_number`, `status`) VALUES" + " ('" + productId + "', '" + partnerId + "', '" + countryCode + "', '1522849806000', '" + subscriptionId + "', '2', 'IN_PROGRESS');"); RabbitUtil.purgeAllActivityQueue(productId, partnerId, countryCode); logger.info("=========>First time user subscription event getting trigger"); UserSubscriptionRequest uSRequest = SASUtils.generateUserSubscriptionRequest(productId, partnerId, activityType, "", currentSubscriptionState, transactionState, eventActionType, subscriptionId); SASValidationHelper.validate_sas_api_response(sasHelper.userSubscription(uSRequest)); SASDBHelper.showAllActivityTableData("FIRST ", String.valueOf(subscriptionId)); logger.info("=========>First event: Verify DB after event trigger"); Map<String, String> expectedRecords = new HashMap<String, String>(); expectedRecords.put("status", beforeSchedularStatus); expectedRecords.put("product_id", String.valueOf(productId)); expectedRecords.put("partner_id", String.valueOf(partnerId)); expectedRecords.put("subscription_id", String.valueOf(subscriptionId)); expectedRecords.put("country_code", countryCode); expectedRecords.put("date", String.valueOf(uSRequest.getSubscriptionInfo().getNextBillingDate())); SASValidationHelper.validateTableRecord(DBUtils.getRecord(actionTable, "subscription_id = " + subscriptionId + " and product_id = " + productId + " and partner_id=" + partnerId + " and date=" + uSRequest.getSubscriptionInfo().getNextBillingDate()) .get(0), expectedRecords); logger.info("=========>First Event: schedular call "); SASValidationHelper.validate_schedular_api_response( sasHelper.scheduler(SASUtils.generateSchedulerRequest(productId, partnerId, activityType))); logger.info("=========>First Event: Vefiry DB After Schedular Call "); expectedRecords.put("status", afterSchedularStatus); SASValidationHelper.validateTableRecord(DBUtils.getRecord(actionTable, "subscription_id = " + subscriptionId + " and product_id=" + productId + " and partner_id=" + partnerId).get(0), expectedRecords); logger.info("=========>First Event: Queue verification Name: " + RabbitUtil.getQueueName(productId, partnerId, countryCode, queueName)); Message message = RabbitUtil.receive(RabbitMQConnection.getRabbitTemplate(), RabbitUtil.getQueueName(productId, partnerId, countryCode, queueName), 10000); // Message message = RabbitMQConnection.getRabbitTemplate() // .receive(productId + "_" + partnerId + "_" + queueName.toUpperCase() + "ccc", 25000); SASValidationHelper.validateQueueMessage( ObjectMapperUtils.readValueFromString(new String(message.getBody()), SASQueueResponse.class), productId, partnerId, subscriptionId, countryCode, activityType); logger.info("=========>Second time user subscription event getting trigger"); UserSubscriptionRequest newSubscriptionRequest = SASUtils.generateUserSubscriptionRequest(productId, partnerId, newActivityType.toUpperCase(), currentSubscriptionState, newCurrentSubscriptionState, newTransactionState, newEventActionType, subscriptionId); newSubscriptionRequest.getSubscriptionInfo().setNextBillingDate(DateTimeUtil.getDateByAddingValidity( newSubscriptionRequest.getSubscriptionInfo().getNextBillingDate(), 1, TimeUnitEnum.DAY.name())); newSubscriptionRequest.getActivityEvent().setNextBillingDate(DateTimeUtil.getDateByAddingValidity( newSubscriptionRequest.getActivityEvent().getNextBillingDate(), 1, TimeUnitEnum.DAY.name())); SASValidationHelper.validate_sas_api_response(sasHelper.userSubscription(newSubscriptionRequest)); logger.info("=========>Second event: previous Event's DB verification"); expectedRecords.put("status", afteNewEventStatus); SASValidationHelper.validateTableRecord(DBUtils .getRecord(actionTable, "subscription_id = " + subscriptionId + " and product_id=" + productId + " and partner_id=" + partnerId + " and date=" + uSRequest.getSubscriptionInfo().getNextBillingDate()) .get(0), expectedRecords); logger.info("=========>Second event: DB verification before schedular call"); expectedRecords.put("status", newBeforeSchedularStatus); expectedRecords.put("date", String.valueOf(newSubscriptionRequest.getSubscriptionInfo().getNextBillingDate())); SASValidationHelper.validateTableRecord( DBUtils.getRecord(newActionTable, "subscription_id = " + subscriptionId + " and product_id=" + productId + " and partner_id=" + partnerId + " and date=" + newSubscriptionRequest.getSubscriptionInfo().getNextBillingDate()) .get(0), expectedRecords); logger.info("=========>Second event: Schedular call"); SASValidationHelper.validate_schedular_api_response( sasHelper.scheduler(SASUtils.generateSchedulerRequest(productId, partnerId, activityType))); logger.info("=========>Second event: DB verification after schedular call"); expectedRecords.put("status", newAfterSchedularStatus); SASValidationHelper.validateTableRecord( DBUtils.getRecord(newActionTable, "subscription_id = " + subscriptionId + " and product_id=" + productId + " and partner_id=" + partnerId + " and date=" + newSubscriptionRequest.getSubscriptionInfo().getNextBillingDate()) .get(0), expectedRecords); logger.info("=========>Second event: Queue verification " + RabbitUtil.getQueueName(productId, partnerId, countryCode, newQueueName)); message = RabbitUtil.receive(RabbitMQConnection.getRabbitTemplate(), RabbitUtil.getQueueName(productId, partnerId, countryCode, newQueueName), 10000); /*message = RabbitMQConnection.getRabbitTemplate().receive( productId + "_" + partnerId + "_" + newQueueName.toUpperCase() + "ccc", 25000);*/ SASValidationHelper.validateQueueMessage( ObjectMapperUtils.readValueFromString(new String(message.getBody()), SASQueueResponse.class), productId, partnerId, subscriptionId, countryCode, newActivityType); } catch (Exception e) { logger.info("=========>ERROR due to exception"); Assert.fail(e.getMessage()); } } } <file_sep>package com.vuclip.premiumengg.automation.schedular_service.common.models; import lombok.*; @Data @AllArgsConstructor @NoArgsConstructor @Builder @ToString public class TimeWindow { private String startime; private String endTime; } <file_sep> package com.vuclip.premiumengg.automation.subscription_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "productId", "partnerId", "subscriptionBillingCode", "chargedBillingCode", "fallbackBillingCode", "mode", "actionId", "activityId", "transactionId", "transactionStateId", "chargedPrice", "partnerTransactionId", "actionResult", "serviceId", "subscriptionId", "closed", "circleCode", "userSource", "userId", "clientUserId", "itemId", "errorCode", "errorDesc", "delayed", "itemTypeId", "nextBillingDate", "countryCode" }) @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString public class ConfirmSync { @JsonProperty("countryCode") private String countryCode; @JsonProperty("productId") private Integer productId; @JsonProperty("partnerId") private Integer partnerId; @JsonProperty("subscriptionBillingCode") private String subscriptionBillingCode; @JsonProperty("chargedBillingCode") private String chargedBillingCode; @JsonProperty("fallbackBillingCode") private String fallbackBillingCode; @JsonProperty("mode") private String mode; @JsonProperty("actionId") private Integer actionId; @JsonProperty("activityId") private Integer activityId; @JsonProperty("transactionId") private String transactionId; @JsonProperty("transactionStateId") private Integer transactionStateId; @JsonProperty("chargedPrice") private Double chargedPrice; @JsonProperty("partnerTransactionId") private String partnerTransactionId; @JsonProperty("actionResult") private String actionResult; @JsonProperty("serviceId") private String serviceId; @JsonProperty("subscriptionId") private Long subscriptionId; @JsonProperty("closed") private Boolean closed; @JsonProperty("circleCode") private String circleCode; @JsonProperty("userSource") private String userSource; @JsonProperty("userId") private String userId; @JsonProperty("clientUserId") private String clientUserId; @JsonProperty("itemId") private String itemId; @JsonProperty("errorCode") private String errorCode; @JsonProperty("errorDesc") private String errorDesc; @JsonProperty("delayed") private boolean delayed; @JsonProperty("itemTypeId") private String itemTypeId; @JsonProperty("nextBillingDate") private Long nextBillingDate; // @Override // public String toString() { // return "ConfirmSync [productId=" + productId + ", partnerId=" + partnerId + ", subscriptionBillingCode=" // + subscriptionBillingCode + ", chargedBillingCode=" + chargedBillingCode + ", fallbackBillingCode=" // + fallbackBillingCode + ", mode=" + mode + ", actionId=" + actionId + ", activityId=" + activityId // + ", transactionId=" + transactionId + ", transactionStateId=" + transactionStateId + ", chargedPrice=" // + chargedPrice + ", partnerTransactionId=" + partnerTransactionId + ", actionResult=" + actionResult // + ", serviceId=" + serviceId + ", subscriptionId=" + subscriptionId + ", closed=" + closed // + ", circleCode=" + circleCode + ", userSource=" + userSource + ", userId=" + userId + ", clientUserId=" // + clientUserId + ", itemId=" + itemId + ", errorCode=" + errorCode + ", errorDesc=" + errorDesc // + ", delayed=" + delayed + ", itemTypeId=" + itemTypeId + ", nextBillingDate=" + nextBillingDate // + ", additionalProperties=" + additionalProperties + "]"; // } } <file_sep> package com.vuclip.premiumengg.automation.subscription_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.Getter; import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "userDetails", "productId", "partnerId", "country" }) @Getter @Setter public class SubscriptionBlock { @JsonProperty("userDetails") private UserDetails userDetails; @JsonProperty("productId") private Integer productId; @JsonProperty("partnerId") private Integer partnerId; @JsonProperty("country") private String country; } <file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.*; import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"product", "productPartnerMappings", "productCountryMapping", "smsConfigs", "retry", "churnNotifications", "adNetworkNotifications", "pricePoints", "stateConfigs", "blackouts", "activityFlows"}) @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString public class PublishConfigRequest { @JsonProperty("product") private Product product; @JsonProperty("productPartnerMappings") private List<ProductPartnerMapping> productPartnerMappings = null; @JsonProperty("productCountryMapping") private ProductCountryMapping productCountryMapping; @JsonProperty("smsConfigs") private List<SmsConfig> smsConfigs = null; @JsonProperty("retry") private List<Retry> retry = null; @JsonProperty("churnNotifications") private List<ChurnNotification> churnNotifications = null; @JsonProperty("adNetworkNotifications") private List<AdNetworkNotification> adNetworkNotifications = null; @JsonProperty("pricePoints") private List<PricePoint> pricePoints = null; @JsonProperty("stateConfigs") private List<StateConfig> stateConfigs = null; @JsonProperty("blackouts") private List<Blackout> blackouts = null; @JsonProperty("activityFlows") private List<ActivityFlow> activityFlows = null; } <file_sep><project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.vuclip.premiumengg</groupId> <version>1.0.0</version> <name>system-tests</name> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <parallelType>methods</parallelType> <threads>1</threads> <serviceName>billing-package-service</serviceName> <profileName>ci</profileName> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <repositories> <repository> <snapshots> <enabled>false</enabled> </snapshots> <id>central</id> <name>libs-release</name> <url>http://172.16.17.32:8081/artifactory/libs-release</url> </repository> <repository> <snapshots/> <id>snapshots</id> <name>libs-snapshot</name> <url>http://172.16.17.32:8081/artifactory/libs-snapshot</url> </repository> <repository> <id>releases</id> <url>http://172.16.31.10:8081/nexus/content/repositories/releases</url> </repository> <repository> <id>thirdparty</id> <url>http://172.16.31.10:8081/nexus/content/repositories/thirdparty</url> </repository> <repository> <snapshots> <enabled>false</enabled> </snapshots> <id>repo</id> <name>repo</name> <url>http://172.16.17.32:8081/artifactory/repo</url> </repository> </repositories> <dependencies> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>2.0.8.RELEASE</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.25</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>3.0.7</version> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.9.8</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.16</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.2.3</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.14</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.14</version> </dependency> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.54</version> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.9.7</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.amqp</groupId> <artifactId>spring-rabbit</artifactId> <version>2.0.3.RELEASE</version> </dependency> <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>5.2.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok-maven --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.0</version> </dependency> <dependency> <groupId>io.javaslang</groupId> <artifactId>javaslang</artifactId> <version>2.0.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugin</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.21.0</version> <configuration> <systemPropertyVariables> <propertiesFile> ${project.basedir}/src/test/resources/configurations/${serviceName}/setup.properties </propertiesFile> </systemPropertyVariables> <suiteXmlFiles> <file>src/test/resources/suites/${serviceName}/testng-${profileName}.xml</file> </suiteXmlFiles> <properties> <property> <name>listener</name> <value>com.vuclip.premiumengg.automation.listners.RetryListener</value> </property> </properties> <parallel>${parallelType}</parallel> <threadCount>${threads}</threadCount> <testFailureIgnore>false</testFailureIgnore> </configuration> </plugin> </plugins> </build> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.21.0</version> </plugin> </plugins> </reporting> <artifactId>system-tests</artifactId> </project> <file_sep>package com.vuclip.premiumengg.automation.billing_package_service.tests; import com.vuclip.premiumengg.automation.billing_package_service.common.models.BillingPackage; import com.vuclip.premiumengg.automation.billing_package_service.common.models.BillingResponse; import com.vuclip.premiumengg.automation.billing_package_service.common.utils.BPSHelper; import com.vuclip.premiumengg.automation.billing_package_service.common.utils.BPSValidationHelper; import com.vuclip.premiumengg.automation.common.Log4J; import io.restassured.response.Response; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.HashMap; import java.util.Map; /** * Created by Kohitij_Das on 21/03/18. */ public class GetBillingOptionsWithFilter { private BPSHelper bpsHelper; private BPSValidationHelper validationHelper; @BeforeClass(alwaysRun = true) public void setup() throws Exception { bpsHelper = new BPSHelper(); validationHelper = new BPSValidationHelper(); } @Test public void verify_get_billing_options_with_productId() throws Exception { Log4J.getLogger().info("===================================>TEST: verify_get_billing_options_with_productId "); final Map<String, Object> params = new HashMap<String, Object>(); params.put("productId", BillingPackage.PACKAGE1.getProductId()); Response response = bpsHelper.getBillingOptionWithFilters(params); validationHelper.validate_billing_response(response, BillingResponse.SUCCESS); validationHelper.validate_billing_packages(response, BillingPackage.PACKAGE1, "billingPackages"); } @Test public void verify_get_billing_options_without_productId() throws Exception { Log4J.getLogger() .info("===================================>TEST: verify_get_billing_options_without_productId "); final Map<String, Object> params = new HashMap<String, Object>(); final Response response = bpsHelper.getBillingOptionWithFilters(params); validationHelper.validate_billing_response(response, BillingResponse.BADREQUEST); } @DataProvider(name = "validFilterOptions") public Object[][] validFilterOptions() { return new Object[][]{{"partnerId", BillingPackage.PACKAGE1.getPartnerId()}, {"isCarrier", BillingPackage.PACKAGE1.isCarrier()}, {"billingCode", BillingPackage.PACKAGE1.getBillingCode()}, {"price", BillingPackage.PACKAGE1.getPrice()}, {"country", BillingPackage.PACKAGE1.getCountry()}, {"itemId", BillingPackage.PACKAGE1.getItemId()}, {"itemTypeId", BillingPackage.PACKAGE1.getItemTypeId()}, // Client id not use as parameter {"clientId", // BillingPackage.PACKAGE1.getClientId()} }; } @Test(dataProvider = "validFilterOptions") public void verify_get_billing_options_with_valid_filter(String filterName, Object filterValue) { Log4J.getLogger().info("===================================>TEST: verify_get_billing_options_with_valid_filter " + filterName + ", " + filterValue); final Map<String, Object> params = new HashMap<String, Object>(); params.put("productId", BillingPackage.PACKAGE1.getProductId()); params.put(filterName, filterValue); try { Response response = bpsHelper.getBillingOptionWithFilters(params); validationHelper.validate_billing_response(response, BillingResponse.SUCCESS); validationHelper.validate_billing_packages(response, BillingPackage.PACKAGE1, "billingPackages"); } catch (Exception e) { e.printStackTrace(); } } @DataProvider(name = "invalidFilterOptions") public Object[][] invalidFilterOptions() { return new Object[][]{{"partnerId", 99}, {"isCarrier", true}, {"billingCode", "111222"}, {"price", 9999}, {"country", "dummy"}, {"itemId", 99}, {"itemTypeId", 99}, // Client id not use as parameter{"clientId", 99} }; } @Test(dataProvider = "invalidFilterOptions") public void verify_get_billing_options_with_invalid_filter(String filterName, Object filterValue) throws Exception { Log4J.getLogger().info("===================================>" + "TEST: verify_get_billing_options_with_invalid_filter" + filterName + ", " + filterValue); final Map<String, Object> params = new HashMap<String, Object>(); params.put("productId", BillingPackage.PACKAGE1.getProductId()); params.put(filterName, filterValue); validationHelper.validate_billing_response(bpsHelper.getBillingOptionWithFilters(params), BillingResponse.NOTFOUND); } } <file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils; import com.vuclip.premiumengg.automation.common.Configuration; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.models.PublishConfigRequest; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.models.SchedulerRequest; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.models.UserSubscriptionRequest; import io.restassured.http.ContentType; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; import static io.restassured.RestAssured.given; import static io.restassured.RestAssured.with; /** * @author mayank.bharshiv */ public class SASHelper { final String saveProductResource = "/saveProduct"; final String userSubscriptionResource = "/event/userSubcription"; final String schedulerResource = "/schedular"; RequestSpecification requestSpecification; /** * Default constructor. Initializes the request template. */ public SASHelper() { this.requestSpecification = with().baseUri(Configuration.sasServer); } /** * @param publishConfigRequest * @return response * @throws Exception */ public Response saveProduct(PublishConfigRequest publishConfigRequest) throws Exception { final Response response = given(requestSpecification).contentType(ContentType.JSON).body(publishConfigRequest) .log().all().post(saveProductResource); response.prettyPrint(); return response; } /** * @param publishConfigRequest * @return response * @throws Exception */ public Response saveProduct(String publishConfigRequest) throws Exception { final Response response = given(requestSpecification).contentType(ContentType.JSON).body(publishConfigRequest) .post(saveProductResource); response.prettyPrint(); return response; } /** * @param userSubscriptionRequest * @return * @throws Exception */ public Response userSubscription(UserSubscriptionRequest userSubscriptionRequest) throws Exception { final Response response = given(requestSpecification).contentType(ContentType.JSON) .body(userSubscriptionRequest).log().all().post(userSubscriptionResource); response.prettyPrint(); return response; } /** * @param schedulerRequest * @return * @throws Exception */ public Response scheduler(SchedulerRequest schedulerRequest) throws Exception { if (schedulerRequest.getActivityType() != null) { if (schedulerRequest.getActivityType().equalsIgnoreCase("ACTIVATION")) schedulerRequest.setActivityType("ACTIVATION_RETRY"); if (schedulerRequest.getActivityType().equalsIgnoreCase("DEACTIVATION")) schedulerRequest.setActivityType("DEACTIVATION_RETRY"); } final Response response = given(requestSpecification).contentType(ContentType.JSON).body(schedulerRequest).log() .all().post(schedulerResource); response.prettyPrint(); return response; } public Response scheduler(String jsonstring) throws Exception { final Response response = given(requestSpecification).contentType(ContentType.JSON).body(jsonstring).log().all() .post(schedulerResource); response.prettyPrint(); return response; } } <file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.common.models; public enum SASTables { winback, renewal, activation, deactivation, churn, free_trail } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.utils; import java.util.Map; import org.apache.log4j.Logger; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.configuration_service.common.models.CountryResponseVO; import com.vuclip.premiumengg.automation.utils.AppAssert; public class CountryValidationHelper { private static Logger logger = Log4J.getLogger("CSValidationHelper"); public static void validateTableRecord(Map<String, Object> map, CountryResponseVO countryResponseVO) { logger.info("Verify Country Table"); AppAssert.assertEqual(map.get("country_name").toString(), countryResponseVO.getCountry().getCountryName()); AppAssert.assertEqual(map.get("currency").toString(), countryResponseVO.getCountry().getCurrency()); AppAssert.assertEqual(map.get("country_code").toString(), countryResponseVO.getCountry().getCountryCode()); AppAssert.assertEqual(map.get("timezone").toString(), countryResponseVO.getCountry().getTimezone()); } public static void validateResponse(CountryResponseVO actual, CountryResponseVO expected) { if(actual.getCountry().getOperationType()!=null) { AppAssert.assertEqual(actual.getMessage(), expected.getMessage(), "Verification for message"); AppAssert.assertEqual(actual.getResponseCode(), expected.getResponseCode(), "verification for respose code"); AppAssert.assertEqual(actual.isSuccessful(), expected.isSuccessful()); AppAssert.assertEqual(actual.getCountry().getCountryName(), expected.getCountry().getCountryName()); AppAssert.assertEqual(actual.getCountry().getCurrency(), expected.getCountry().getCurrency()); AppAssert.assertEqual(actual.getCountry().getOperationType(), expected.getCountry().getOperationType()); AppAssert.assertEqual(actual.getCountry().getTimezone(), expected.getCountry().getTimezone()); AppAssert.assertEqual(actual.getCountry().getCountryCode(), expected.getCountry().getCountryCode()); } else { AppAssert.assertEqual(actual.getMessage(), expected.getMessage(), "Verification for message"); AppAssert.assertEqual(actual.getResponseCode(), expected.getResponseCode(), "verification for respose code"); AppAssert.assertEqual(actual.isSuccessful(), expected.isSuccessful()); AppAssert.assertEqual(actual.getCountry().getCountryName(), expected.getCountry().getCountryName()); AppAssert.assertEqual(actual.getCountry().getCurrency(), expected.getCountry().getCurrency()); AppAssert.assertEqual(actual.getCountry().getTimezone(), expected.getCountry().getTimezone()); AppAssert.assertEqual(actual.getCountry().getCountryCode(), expected.getCountry().getCountryCode()); } } } <file_sep>package com.vuclip.premiumengg.automation.common; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitAdmin; /** * @author rahul s */ public class RabbitAdminConnection { private static RabbitAdmin rabbitAdmin; private RabbitAdminConnection() { } public static RabbitAdmin getRabbitAdminConnection() { if (rabbitAdmin == null) { System.out.println("========== Creating Rabbit MQ Admin Connection ============"); CachingConnectionFactory connectionFactory = new CachingConnectionFactory(Configuration.rabbitMQServer); connectionFactory.setUsername(Configuration.rabbitMQUser); connectionFactory.setPassword(Configuration.rabbitMQPassword); connectionFactory.setPort(Integer.parseInt(Configuration.rabbitMQPort)); rabbitAdmin = new RabbitAdmin(connectionFactory); System.out.println("========== Created Rabbit MQ admin ============"); } return rabbitAdmin; } public static void closeAllConnection() { System.out.println("======== Closing Rabbit MQ Admin connection ========="); if (rabbitAdmin != null) if (rabbitAdmin.getRabbitTemplate() != null) if (rabbitAdmin.getRabbitTemplate().getConnectionFactory() != null) rabbitAdmin.getRabbitTemplate().stop(); } } <file_sep>package com.vuclip.premiumengg.automation.subscription_service.common.utils; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.common.RedisTemplateConnection; import com.vuclip.premiumengg.automation.subscription_service.common.models.ConfirmSync; import com.vuclip.premiumengg.automation.subscription_service.common.models.ConfirmSyncQueue; import com.vuclip.premiumengg.automation.subscription_service.common.models.RabbitMessage; import com.vuclip.premiumengg.automation.subscription_service.common.models.SaveProductRequest; import com.vuclip.premiumengg.automation.subscription_service.common.models.SubscriptionBlock; import com.vuclip.premiumengg.automation.subscription_service.common.models.SubscriptionBlockStatus; import com.vuclip.premiumengg.automation.subscription_service.common.models.SubscriptionStatus; import com.vuclip.premiumengg.automation.subscription_service.common.models.SubscriptionUnBlock; import com.vuclip.premiumengg.automation.utils.ObjectMapperUtils; import com.vuclip.subscription.nosql.docs.UserKeySubscriptionIdDoc; import com.vuclip.subscription.nosql.docs.UserSubscriptionDoc; import com.vuclip.subscription.rdbms.entities.BlockedUser; public class SUtils { public static int productId = 8181; public static SaveProductRequest productConfig = null; private static Logger logger = Log4J.getLogger("SSUtils"); /** * * @param JsonFileName * @param type * @return */ public static <T> T loadJson(String JsonFileName, Class<T> type) { return ObjectMapperUtils .readValue("src/test/resources/configurations/subscription-service/request/" + JsonFileName, type); } public static void generateUserSubscriptionTableData(Long subscription_id, String created_on, Long activation_date, int blacklisted, String charged_billing_code, int cooldowned, Long deactivation_date, Long end_date, String msisdn, Long next_billing_date, int paid, int partner_id, int product_id, Long start_date, String sub_type, int subscribable, String subscription_billing_code, String subscription_status, int validity_days, String user_id, String user_sub_auth_key, int renewalAllowed) { Map<String, Object> insertRecordinDatabase = new HashMap<String, Object>(); logger.info("Generate User Subscription Table"); insertRecordinDatabase.put("deactivation_date", deactivation_date); insertRecordinDatabase.put("subscription_id", subscription_id); insertRecordinDatabase.put("created_on", SUtils.dbReadableFormat(created_on)); insertRecordinDatabase.put("activation_date", activation_date); insertRecordinDatabase.put("renewal_allowed", renewalAllowed); insertRecordinDatabase.put("charged_billing_code", SUtils.dbReadableFormat(charged_billing_code)); insertRecordinDatabase.put("charged_price", 0); insertRecordinDatabase.put("circle_code", SUtils.dbReadableFormat("circlecode")); insertRecordinDatabase.put("country", SUtils.dbReadableFormat("MY")); insertRecordinDatabase.put("customer_transaction_id", SUtils.dbReadableFormat("TXN123456")); insertRecordinDatabase.put("end_date", end_date); insertRecordinDatabase.put("item_id", 1); insertRecordinDatabase.put("item_type_id", 1); insertRecordinDatabase.put("mode", SUtils.dbReadableFormat("WAP")); insertRecordinDatabase.put("msisdn", SUtils.dbReadableFormat(msisdn)); insertRecordinDatabase.put("next_billing_date", next_billing_date); insertRecordinDatabase.put("paid", paid); insertRecordinDatabase.put("partner_id", partner_id); insertRecordinDatabase.put("product_id", product_id); insertRecordinDatabase.put("start_date", start_date); insertRecordinDatabase.put("subscription_billing_code", SUtils.dbReadableFormat(subscription_billing_code)); insertRecordinDatabase.put("subscription_status", SUtils.dbReadableFormat(subscription_status)); insertRecordinDatabase.put("validity_days", validity_days); insertRecordinDatabase.put("user_id", SUtils.dbReadableFormat(user_id)); insertRecordinDatabase.put("user_preffered_language", SUtils.dbReadableFormat("en")); insertRecordinDatabase.put("user_source", SUtils.dbReadableFormat("D_KIM_87348")); insertIntoDatabase("user_subscription", insertRecordinDatabase); } public static void generateBlockedUserTableData(Long id, int blockType, String created_date, Long end_date, Integer product_id, Integer partner_id, Long start_date, String user_id, String country) { Map<String, Object> insertRecordinDatabase = new HashMap<String, Object>(); logger.info("Generate Blocked User Table"); insertRecordinDatabase.put("id", id); insertRecordinDatabase.put("block_type", blockType); insertRecordinDatabase.put("created_on", SUtils.dbReadableFormat(created_date)); insertRecordinDatabase.put("end_date", end_date); insertRecordinDatabase.put("partner_id", partner_id); insertRecordinDatabase.put("product_id", product_id); insertRecordinDatabase.put("start_date",start_date); insertRecordinDatabase.put("user_id", SUtils.dbReadableFormat(user_id)); insertRecordinDatabase.put("country", SUtils.dbReadableFormat(country)); insertIntoDatabase("blocked_user", insertRecordinDatabase); } public static void generateFreeTrialTableData(Integer id, String created_on, String last_free_trial_date, Integer availed_free_trial_count, String last_free_trial_billing_code, Integer product_id, Integer partner_id, String user_id) { Map<String, Object> insertRecordinDatabase = new HashMap<String, Object>(); logger.info("Generate Free Trial History Table"); insertRecordinDatabase.put("id", id); insertRecordinDatabase.put("created_on", SUtils.dbReadableFormat(created_on)); insertRecordinDatabase.put("last_free_trial_date", SUtils.dbReadableFormat(last_free_trial_date)); insertRecordinDatabase.put("partner_id", partner_id); insertRecordinDatabase.put("product_id", product_id); insertRecordinDatabase.put("availed_free_trial_count", availed_free_trial_count); insertRecordinDatabase.put("last_free_trial_billing_code", SUtils.dbReadableFormat(last_free_trial_billing_code)); insertRecordinDatabase.put("user_id", user_id); insertIntoDatabase("free_trial_history", insertRecordinDatabase); } public static void insertIntoProductPartner(int id, int allowed_free_trial_count, int blacklist_applicable, int blacklist_validity, int cooldown_applicable, int cooldown_validity, int partner_id, int product_id, int step_up_charging_applicable, int time_unit, int validity_from_partner) { Map<String, Object> insertRecordinDatabase = new HashMap<String, Object>(); logger.info("Generate Product Partner Table"); insertRecordinDatabase.put("id", id); insertRecordinDatabase.put("allowed_free_trial_count", allowed_free_trial_count); insertRecordinDatabase.put("blacklist_applicable", blacklist_applicable); insertRecordinDatabase.put("blacklist_validity", blacklist_validity); insertRecordinDatabase.put("cooldown_applicable", cooldown_applicable); insertRecordinDatabase.put("cooldown_validity", cooldown_validity); insertRecordinDatabase.put("partner_id", partner_id); insertRecordinDatabase.put("product_id", product_id); insertRecordinDatabase.put("step_up_charging_applicable", step_up_charging_applicable); insertRecordinDatabase.put("time_unit", time_unit); insertRecordinDatabase.put("validity_from_partner", validity_from_partner); insertIntoDatabase("product_partner_mapping", insertRecordinDatabase); } /** * * @param tabeName * @param dataSet */ private static void insertIntoDatabase(String tabeName, Map<String, Object> dataSet) { logger.info("Insert Into Database"); SDBHelper.addRecordInTable(tabeName, dataSet); } /** * * @param key * @return */ public static String dbReadableFormat(String key) { return ("'" + key + "'"); } public static void generateRedisValueUserId(Long subscription_id, String created_on, Long activation_date, int blacklisted, String charged_billing_code, int cooldowned, Long deactivation_date, Long end_date, String msisdn, Long next_billing_date, int paid, int partner_id, int product_id, Long start_date, String sub_type, int subscribable, String subscription_billing_code, String subscription_status, int validity_days, String user_id, String user_sub_auth_key, int renewalAllowed) throws ParseException { logger.info("Generate Redis Value"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); logger.info("Subscription status in Redis=>" + subscription_status); UserSubscriptionDoc redisEntryValueDetail = new UserSubscriptionDoc(); try { redisEntryValueDetail = loadJson("redis.json", UserSubscriptionDoc.class); if (deactivation_date != null) { redisEntryValueDetail.setDeactivationDate(deactivation_date); } else { redisEntryValueDetail.setDeactivationDate(null); } redisEntryValueDetail.setSubscriptionId(subscription_id); // redisEntryValueDetail.setUserSubAuthKey(user_sub_auth_key); redisEntryValueDetail.setCreatedOn(df.parse(created_on)); redisEntryValueDetail.setActivationDate(activation_date); redisEntryValueDetail.setChargedBillingCode(charged_billing_code); redisEntryValueDetail.setChargedPrice(0D); redisEntryValueDetail.setCountry("MY"); redisEntryValueDetail.setCustomerTransactionId("TXN123456"); redisEntryValueDetail.setEndDate(end_date); redisEntryValueDetail.setItemId(1); redisEntryValueDetail.setItemTypeId(1); redisEntryValueDetail.setMode("WAP"); redisEntryValueDetail.setMsisdn(msisdn); redisEntryValueDetail.setNextBillingDate(next_billing_date); redisEntryValueDetail.setPaid(DateUtils.convertIntToBoolean(paid)); // redisEntryValueDetail.setPartner("UMOBILE"); redisEntryValueDetail.setPartnerId(partner_id); // redisEntryValueDetail.setPlanCycle("WEEKLY"); redisEntryValueDetail.setProductId(product_id); redisEntryValueDetail.setStartDate(start_date); // redisEntryValueDetail.setSubType(SubType.PAID); // redisEntryValueDetail.setSubscribeable(DateUtils.convertIntToBoolean(subscribable)); redisEntryValueDetail.setSubscriptionBillingCode(subscription_billing_code); redisEntryValueDetail.setSubscriptionValidityDays(validity_days); redisEntryValueDetail.setUserId(user_id); redisEntryValueDetail.setUserPreferredLanguage("en"); redisEntryValueDetail.setUserSource("D_KIM_87348"); // redisEntryValueDetail.setClientUserId("viu-xyt-84873"); redisEntryValueDetail.setRenewalAllowed(DateUtils.convertIntToBoolean(renewalAllowed)); switch (subscription_status) { case "ACT_INIT": redisEntryValueDetail.setSubscriptionStatus(SubscriptionStatus.ACT_INIT); break; case "ACTIVATED": redisEntryValueDetail.setSubscriptionStatus(SubscriptionStatus.ACTIVATED); break; case "DEACTIVATED": redisEntryValueDetail.setSubscriptionStatus(SubscriptionStatus.DEACTIVATED); break; case "PARKING": redisEntryValueDetail.setSubscriptionStatus(SubscriptionStatus.PARKING); break; case "SUSPEND": redisEntryValueDetail.setSubscriptionStatus(SubscriptionStatus.SUSPEND); break; case "DCT_INIT": redisEntryValueDetail.setSubscriptionStatus(SubscriptionStatus.DCT_INIT); break; default: logger.info("No match for subscription status"); } } catch (Exception e) { e.printStackTrace(); } UserKeySubscriptionIdDoc userKeySubscriptionIdDoc = new UserKeySubscriptionIdDoc(); userKeySubscriptionIdDoc.setSubscriptionId(subscription_id); String redisKeyUSERID = user_sub_auth_key; String redisKeyMSISDN = "MSISDN_" + product_id + "_" + msisdn; logger.info("Redis Key UserId:" + redisKeyUSERID); logger.info("Redis Key Msisdn:" + redisKeyMSISDN); logger.info("Redis Key SubId:" + String.valueOf(subscription_id)); RedisTemplateConnection.getRedisConnection().opsForValue().set(redisKeyUSERID, userKeySubscriptionIdDoc); RedisTemplateConnection.getRedisConnection().opsForValue().set(redisKeyMSISDN, userKeySubscriptionIdDoc); RedisTemplateConnection.getRedisConnection().opsForValue() .set(String.valueOf(userKeySubscriptionIdDoc.getSubscriptionId()), redisEntryValueDetail); logger.info("Redis Data" + redisEntryValueDetail.toString()); } public static SubscriptionUnBlock generateSubscriptionUnBlockValues(String userId, String blockType, int productId, int partnerId, String country) { logger.info("generate subscription block values"); SubscriptionUnBlock subscriptionUnBlock = loadJson("susbscriptionUnBlock.json", SubscriptionUnBlock.class); subscriptionUnBlock.setBlockType(blockType); subscriptionUnBlock.setUserId(userId); subscriptionUnBlock.setPartnerId(productId); subscriptionUnBlock.setProductId(partnerId); subscriptionUnBlock.setCountry(country); return subscriptionUnBlock; } public static SubscriptionBlock generateSubscriptionBlockValues(String userId, int productId, int partnerId, String country, String msisdn) { logger.info("generate subscription block values"); SubscriptionBlock subscriptionBlock = loadJson("subscriptionBlock.json", SubscriptionBlock.class); subscriptionBlock.getUserDetails().setUserId(userId); subscriptionBlock.getUserDetails().setMsisdn(msisdn); subscriptionBlock.setPartnerId(productId); subscriptionBlock.setProductId(partnerId); subscriptionBlock.setCountry(country); return subscriptionBlock; } public static SubscriptionBlockStatus generateSubscriptionBlockStatusValues(String userId, int productId, int partnerId, String country) { logger.info("generate subscription block values"); SubscriptionBlockStatus subscriptionBlockStatus = loadJson("subscriptionBlockStatus.json", SubscriptionBlockStatus.class); subscriptionBlockStatus.setUserId(userId); subscriptionBlockStatus.setPartnerId(productId); subscriptionBlockStatus.setProductId(partnerId); subscriptionBlockStatus.setCountry(country); return subscriptionBlockStatus; } public static ConfirmSync generateConfirmCallValues(Integer productId, Integer partnerId, String subscriptionBillingCode, String chargedBillingCode, String fallbackBillingCode, Integer actionId, Integer activityId, Integer transactionStateId, String actionResult, Long subscriptionId, String userId, Boolean closed, Long nextBillingDate) { logger.info("generate confirm sync api values"); ConfirmSync confirmValues = loadJson("ConfirmSync.json", ConfirmSync.class); confirmValues.setPartnerId(partnerId); confirmValues.setProductId(productId); confirmValues.setSubscriptionBillingCode(subscriptionBillingCode); confirmValues.setChargedBillingCode(chargedBillingCode); confirmValues.setFallbackBillingCode(fallbackBillingCode); confirmValues.setActionId(actionId); confirmValues.setActivityId(activityId); confirmValues.setTransactionStateId(transactionStateId); confirmValues.setActionResult(actionResult); confirmValues.setSubscriptionId(subscriptionId); confirmValues.setUserId(userId); confirmValues.setClosed(closed); confirmValues.setNextBillingDate(nextBillingDate); return confirmValues; } public static RabbitMessage generateRabbitMQValues(String activity, int partnerId, int productId, String subscriptionBillingCode, String chargedBillingCode, String action, String transactionState, Long subscriptionId, Boolean closed, Long nextBillingDate, String actionResult, Long activation_date, String transactionId, String userId) throws Exception { logger.info("generate rabbit mq values"); RabbitMessage rabbitMessage = loadJson("RabbitMQMessage.json", RabbitMessage.class); logger.info("set default Value"); rabbitMessage.setActivity(activity); rabbitMessage.setProductId(productId); rabbitMessage.setPartnerId(partnerId); rabbitMessage.setAttemptedBillingCode(subscriptionBillingCode); rabbitMessage.setChargedBillingCode(chargedBillingCode); rabbitMessage.setAction(action); rabbitMessage.setTransactionState(transactionState); rabbitMessage.setSubscriptionId(subscriptionId); rabbitMessage.setClosed(closed); rabbitMessage.setNextBillingDate(nextBillingDate); rabbitMessage.setActionResult(actionResult); rabbitMessage.setActivationDate(activation_date); rabbitMessage.setRequestedBillingCode(chargedBillingCode); rabbitMessage.setTransactionId(transactionId); rabbitMessage.setUserId(userId); rabbitMessage.setMsisdn(userId); SRabitMessageHelper.addMessageToQueue(rabbitMessage); return null; } public static void generateRedisValueForBlockUnblock(Long subscription_id, String country, String blockType, String created_on, Long end_date, String msisdn, int partnerId, int productId, Long start_date, String user_id) throws ParseException { logger.info("Generate Redis Value for Block/Unblock"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); BlockedUser redisEntryBlockUnblock = new BlockedUser(); try { redisEntryBlockUnblock = loadJson("RedisBlockUnblock.json", BlockedUser.class); redisEntryBlockUnblock.setId(subscription_id); redisEntryBlockUnblock.setBlockType(blockType); redisEntryBlockUnblock.setCountry(country); redisEntryBlockUnblock.setCreateDate(df.parse(created_on)); redisEntryBlockUnblock.setStartDate(start_date); redisEntryBlockUnblock.setEndDate(end_date); redisEntryBlockUnblock.setUserId(user_id); redisEntryBlockUnblock.setMsisdn(msisdn); redisEntryBlockUnblock.setProductId(productId); redisEntryBlockUnblock.setPartnerId(partnerId); } catch (Exception e) { e.printStackTrace(); } String redisKey = "USERID_" + productId + "_" + partnerId + "_" + country + "_" + user_id; logger.info("Redis Key for Block/Unblock User:" + redisKey); RedisTemplateConnection.getRedisConnection().opsForValue().set(redisKey, redisEntryBlockUnblock); System.out.println("Redis Data for Block/Unblock" + redisEntryBlockUnblock.toString()); } public static ConfirmSyncQueue generateConfirmDataForQueue(Integer productId, Integer partnerId, String subscriptionBillingCode, String chargedBillingCode, String fallbackBillingCode, Integer actionId, Integer activityId, Integer transactionStateId, String actionResult, Long subscriptionId, String userId, Boolean closed, Long nextBillingDate) { logger.info("generate confirm sync api values"); ConfirmSyncQueue confirmValues = loadJson("ConfirmSyncQueue.json", ConfirmSyncQueue.class); confirmValues.setPartnerId(partnerId); confirmValues.setProductId(productId); confirmValues.setRequestedBillingCode(subscriptionBillingCode); confirmValues.setChargedBillingCode(chargedBillingCode); confirmValues.setAttemptedBillingCode(fallbackBillingCode); confirmValues.setAction(actionId); confirmValues.setActivity(activityId); confirmValues.setTransactionState(transactionStateId); confirmValues.setActionResult(actionResult); confirmValues.setSubscriptionId(subscriptionId); confirmValues.setUserId(userId); confirmValues.setClosed(closed); confirmValues.setNextBillingDate(nextBillingDate); return confirmValues; } } <file_sep> package com.vuclip.premiumengg.automation.subscription_service.common.models; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "retryId", "productId", "partnerId", "countryCode", "operationType", "activityType", "maxRetryCount", "retryIntervalInMinutes", "attemptWindow", "typeOfCycle", "batchSize", "schedulingFrequencyInMinutes", "schedulingDays", "executingTimeWindow", "executingDays", "status", "actionDefaultEiligible", "retryable" }) public class Retry { @JsonProperty("retryId") private Integer retryId; @JsonProperty("productId") private Integer productId; @JsonProperty("partnerId") private Integer partnerId; @JsonProperty("countryCode") private String countryCode; @JsonProperty("operationType") private String operationType; @JsonProperty("activityType") private String activityType; @JsonProperty("maxRetryCount") private Integer maxRetryCount; @JsonProperty("retryIntervalInMinutes") private Integer retryIntervalInMinutes; @JsonProperty("attemptWindow") private String attemptWindow; @JsonProperty("typeOfCycle") private String typeOfCycle; @JsonProperty("batchSize") private Integer batchSize; @JsonProperty("schedulingFrequencyInMinutes") private Integer schedulingFrequencyInMinutes; @JsonProperty("schedulingDays") private String schedulingDays; @JsonProperty("executingTimeWindow") private String executingTimeWindow; @JsonProperty("executingDays") private String executingDays; @JsonProperty("status") private String status; @JsonProperty("actionDefaultEiligible") private Boolean actionDefaultEiligible; @JsonProperty("retryable") private Boolean retryable; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("retryId") public Integer getRetryId() { return retryId; } @JsonProperty("retryId") public void setRetryId(Integer retryId) { this.retryId = retryId; } @JsonProperty("productId") public Integer getProductId() { return productId; } @JsonProperty("productId") public void setProductId(Integer productId) { this.productId = productId; } @JsonProperty("partnerId") public Integer getPartnerId() { return partnerId; } @JsonProperty("partnerId") public void setPartnerId(Integer partnerId) { this.partnerId = partnerId; } @JsonProperty("countryCode") public String getCountryCode() { return countryCode; } @JsonProperty("countryCode") public void setCountryCode(String countryCode) { this.countryCode = countryCode; } @JsonProperty("operationType") public String getOperationType() { return operationType; } @JsonProperty("operationType") public void setOperationType(String operationType) { this.operationType = operationType; } @JsonProperty("activityType") public String getActivityType() { return activityType; } @JsonProperty("activityType") public void setActivityType(String activityType) { this.activityType = activityType; } @JsonProperty("maxRetryCount") public Integer getMaxRetryCount() { return maxRetryCount; } @JsonProperty("maxRetryCount") public void setMaxRetryCount(Integer maxRetryCount) { this.maxRetryCount = maxRetryCount; } @JsonProperty("retryIntervalInMinutes") public Integer getRetryIntervalInMinutes() { return retryIntervalInMinutes; } @JsonProperty("retryIntervalInMinutes") public void setRetryIntervalInMinutes(Integer retryIntervalInMinutes) { this.retryIntervalInMinutes = retryIntervalInMinutes; } @JsonProperty("attemptWindow") public String getAttemptWindow() { return attemptWindow; } @JsonProperty("attemptWindow") public void setAttemptWindow(String attemptWindow) { this.attemptWindow = attemptWindow; } @JsonProperty("typeOfCycle") public String getTypeOfCycle() { return typeOfCycle; } @JsonProperty("typeOfCycle") public void setTypeOfCycle(String typeOfCycle) { this.typeOfCycle = typeOfCycle; } @JsonProperty("batchSize") public Integer getBatchSize() { return batchSize; } @JsonProperty("batchSize") public void setBatchSize(Integer batchSize) { this.batchSize = batchSize; } @JsonProperty("schedulingFrequencyInMinutes") public Integer getSchedulingFrequencyInMinutes() { return schedulingFrequencyInMinutes; } @JsonProperty("schedulingFrequencyInMinutes") public void setSchedulingFrequencyInMinutes(Integer schedulingFrequencyInMinutes) { this.schedulingFrequencyInMinutes = schedulingFrequencyInMinutes; } @JsonProperty("schedulingDays") public String getSchedulingDays() { return schedulingDays; } @JsonProperty("schedulingDays") public void setSchedulingDays(String schedulingDays) { this.schedulingDays = schedulingDays; } @JsonProperty("executingTimeWindow") public String getExecutingTimeWindow() { return executingTimeWindow; } @JsonProperty("executingTimeWindow") public void setExecutingTimeWindow(String executingTimeWindow) { this.executingTimeWindow = executingTimeWindow; } @JsonProperty("executingDays") public String getExecutingDays() { return executingDays; } @JsonProperty("executingDays") public void setExecutingDays(String executingDays) { this.executingDays = executingDays; } @JsonProperty("status") public String getStatus() { return status; } @JsonProperty("status") public void setStatus(String status) { this.status = status; } @JsonProperty("actionDefaultEiligible") public Boolean getActionDefaultEiligible() { return actionDefaultEiligible; } @JsonProperty("actionDefaultEiligible") public void setActionDefaultEiligible(Boolean actionDefaultEiligible) { this.actionDefaultEiligible = actionDefaultEiligible; } @JsonProperty("retryable") public Boolean getRetryable() { return retryable; } @JsonProperty("retryable") public void setRetryable(Boolean retryable) { this.retryable = retryable; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.tests; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.log4j.Logger; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.configuration_service.common.models.AdNetworkRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.ConfigRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.ConfigResponseVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.ConfigTables; import com.vuclip.premiumengg.automation.configuration_service.common.models.ConfigVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.CountryRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.CriteriaRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.CriterionName; import com.vuclip.premiumengg.automation.configuration_service.common.models.CriterionOperator; import com.vuclip.premiumengg.automation.configuration_service.common.models.CriterionRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.DateCoumputationCriterionName; import com.vuclip.premiumengg.automation.configuration_service.common.models.DateCoumputationCriterionOperator; import com.vuclip.premiumengg.automation.configuration_service.common.models.DateCoumputationCriterionRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.DeleteConfigTables; import com.vuclip.premiumengg.automation.configuration_service.common.models.GroupingOperator; import com.vuclip.premiumengg.automation.configuration_service.common.models.ItemTypeId; import com.vuclip.premiumengg.automation.configuration_service.common.models.PartnerRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.TimeUnit; import com.vuclip.premiumengg.automation.configuration_service.common.utils.AdNetworkHelper; import com.vuclip.premiumengg.automation.configuration_service.common.utils.AdNetworkUtil; import com.vuclip.premiumengg.automation.configuration_service.common.utils.CSDBHelper; import com.vuclip.premiumengg.automation.configuration_service.common.utils.CSUtils; import com.vuclip.premiumengg.automation.configuration_service.common.utils.CSValidationHelper; import com.vuclip.premiumengg.automation.configuration_service.common.utils.ConfigHelper; import com.vuclip.premiumengg.automation.configuration_service.common.utils.ConfigUtil; import com.vuclip.premiumengg.automation.configuration_service.common.utils.ConfigValidationHelper; import com.vuclip.premiumengg.automation.configuration_service.common.utils.CountryHelper; import com.vuclip.premiumengg.automation.configuration_service.common.utils.CountryUtil; import com.vuclip.premiumengg.automation.configuration_service.common.utils.PartnerHelper; import com.vuclip.premiumengg.automation.configuration_service.common.utils.PartnerUtil; import com.vuclip.premiumengg.automation.utils.AppAssert; import com.vuclip.premiumengg.automation.utils.DBUtils; import io.restassured.response.Response; public class SaveConfigTest { private static Logger logger = Log4J.getLogger("SaveConfigTest"); private static ConfigRequestVO request; private static ConfigResponseVO expectedResponse; private static ConfigResponseVO updateConfig; private static ConfigVO config; private static String productName; private static int productId; private static String adNetworkName="Ad Network 111"; @BeforeClass(alwaysRun = true) public void setUP() throws Exception { logger.info("cleaning record for SaveCountryTest"); int updateCountCountry = DBUtils.cleanTable("country", "country_name = " + CSDBHelper.dbReadableFormat(SaveCountryTest.countryName)); logger.info("cleaned " + updateCountCountry + " record"); logger.info("cleaning record for AdNetwork"); int updateCountAdNetwork = DBUtils.cleanTable("ad_network", "name = " + CSDBHelper.dbReadableFormat(adNetworkName)); logger.info("cleaned " + updateCountAdNetwork + " record"); logger.info("cleaning record for Partner"); int updateCountPartner = DBUtils.cleanTable("partner", "partner_name = " + CSDBHelper.dbReadableFormat(SavePartnerTests.partneName)); logger.info("cleaned " + updateCountPartner + " record"); logger.info("cleaning record for Conifg Tables "); List<String> tables = Stream.of(DeleteConfigTables.values()).map(Enum::name).collect(Collectors.toList()); for (String tableName : tables) { DBUtils.cleanTable(tableName, null); } logger.info("Save Partner"); PartnerRequestVO request = PartnerUtil.createMockRequestVO(SavePartnerTests.partneName, SavePartnerTests.partneName, "ACTIVE", false, "telco", true, "user1", true, "Vuclip", "Vuclip", "Vuclip", true, true, "Vuclip URL", "Vuclip URL", "Vuclip URL", "Vuclip URL"); Response response = PartnerHelper.savePartner(request); CSValidationHelper.validate_cs_api_response(response); logger.info("Save Country"); CountryRequestVO requestCountry = CountryUtil.createMockRequestVO(SaveCountryTest.countryName, "IN", "GMT", "INR"); Response responseCountry = CountryHelper.saveCountry(requestCountry); CSValidationHelper.validate_cs_api_response(responseCountry); logger.info("Save Ad Network"); AdNetworkRequestVO requestAdNetwork = AdNetworkUtil.createMockRequestVO(adNetworkName, 1, "voluum_tid", "notification url", "GET", "ALL", "active", "churn notification url", "dummy"); Response responseAdNetwork = AdNetworkHelper.saveAdNetwork(requestAdNetwork); CSValidationHelper.validate_cs_api_response(responseAdNetwork); } @Test(groups = { "positive" }) public void saveConifgTests() throws Exception { logger.info("Starting ======> Verify config saved in Database"); try { request = ConfigUtil.createMockRequestVO("VIU", "OTT", "SUBSCRIPTION_STORE", "www.viu.com", "contextName", 123L, true, 30, "www.viu.com", "www.viu.com", "www.viu.com", "VIU Product", "active", "Etisalat UAE", true, true, true, "Parser Endpoint", "Url Generation Endpoint", "dd-mm-yyyy", "India", "BC01", 100.0, 30, 99999, "1234", 1, 1, 1, ItemTypeId.PRODUCT, true, "Price Point 1", false, "BC01", false, "BC01", false, 60, true, "active", true, 10, 0, 10, 10, 10, adNetworkName, 10, 20, 30, "7:30-10:30,23:00-5:00", "ALL", "24", "ACTIVATION_RETRY", 10, 120, "7:00AM-2:00PM", "CALANDER_DAY", 100, 200, 100, 30, 10, 12, 10, 10, "CONTENT_SMS", "Redirection Context", 1, 100, 100, true, "active", Arrays.asList(CriteriaRequestVO.builder().smsText("SMS Text") .criterions(Arrays.asList(CriterionRequestVO.builder() .name(CriterionName.fromValue("activity")).operator(CriterionOperator.EQUAL) .value("Activation").groupingOperator(GroupingOperator.fromValue("NONE")).build())) .dateCoumputationCriterion(DateCoumputationCriterionRequestVO.builder() .name(DateCoumputationCriterionName.fromValue("next_billing_date")) .operator(DateCoumputationCriterionOperator.PLUS).value("24") .unit(TimeUnit.fromValue("HOUR")).build()) .build())); config = ConfigUtil.getMockConfigVO(request); expectedResponse = new ConfigResponseVO(true, 200, CSUtils.uBSMockURL + " : Successful\n", config); logger.info("Expected Response:" + expectedResponse.toString()); Response response = ConfigHelper.saveConfig(request); CSValidationHelper.validate_cs_api_response(response); logger.info("Validate Resposne Body"); updateConfig = response.as(ConfigResponseVO.class); productId = updateConfig.getConfig().getProduct().getProductId(); productName = updateConfig.getConfig().getProduct().getProductName(); logger.info("Actual Resposne:" + updateConfig.toString()); ConfigValidationHelper.validateResponse(updateConfig, expectedResponse); logger.info("Validate Database"); ConfigValidationHelper.validateDataInDB(updateConfig, expectedResponse); } catch (Exception e) { e.printStackTrace(); } } @Test(groups = { "positive" }, dependsOnMethods = { "saveConifgTests" }, priority = 2) public void updateConfigTests() throws Exception { logger.info("Starting ======> Verify config updated in Database"); try { ConfigUtil.createUpdateConfigData(updateConfig); expectedResponse = new ConfigResponseVO(true, 200, CSUtils.uBSMockURL + " : Successful\n", updateConfig.getConfig()); logger.info("Expected Response:" + expectedResponse.toString()); Response response = ConfigHelper.updateConfig(updateConfig.getConfig()); CSValidationHelper.validate_cs_api_response(response); logger.info("Validate Resposne Body"); ConfigResponseVO actualResposne = response.as(ConfigResponseVO.class); productId = actualResposne.getConfig().getProduct().getProductId(); productName = actualResposne.getConfig().getProduct().getProductName(); logger.info("Actual Resposne:" + actualResposne.toString()); ConfigValidationHelper.validateUpdateResponse(actualResposne, expectedResponse); logger.info("Validate Database"); ConfigValidationHelper.validateDataInDB(updateConfig, expectedResponse); } catch (Exception e) { e.printStackTrace(); } } @Test(groups = { "positive" }, dependsOnMethods = { "saveConifgTests" }, priority = 3) public void getConfigByProductName() throws Exception { logger.info("Starting ======> Get Config By productName"); try { expectedResponse = new ConfigResponseVO(true, 200, "Success", updateConfig.getConfig()); logger.info("Expected Response:" + expectedResponse.toString()); Response response = ConfigHelper.getConfigByProductName(productName); CSValidationHelper.validate_cs_api_response(response); logger.info("Validate Resposne Body"); ConfigResponseVO actualResposne = response.as(ConfigResponseVO.class); logger.info("Actual Resposne:" + actualResposne.toString()); ConfigValidationHelper.validateResponse(actualResposne, expectedResponse); } catch (Exception e) { e.printStackTrace(); } } @Test(groups = { "positive" }, dependsOnMethods = { "saveConifgTests" }, priority = 4) public void getConfigByProductId() throws Exception { logger.info("Starting ======> Get Config By productName"); try { expectedResponse = new ConfigResponseVO(true, 200, "Success", updateConfig.getConfig()); logger.info("Expected Response:" + expectedResponse.toString()); Response response = ConfigHelper.getConfigByProductId(productId); CSValidationHelper.validate_cs_api_response(response); logger.info("Validate Resposne Body"); ConfigResponseVO actualResposne = response.as(ConfigResponseVO.class); logger.info("Actual Resposne:" + actualResposne.toString()); ConfigValidationHelper.validateResponse(actualResposne, expectedResponse); } catch (Exception e) { e.printStackTrace(); } } @Test(groups = { "positive" }, dependsOnMethods = { "saveConifgTests" }, priority = 5) public void deleteByProductName() throws Exception { logger.info("Starting ======> Delete By productName"); try { expectedResponse = new ConfigResponseVO(true, 200, CSUtils.uBSMockURL + " : Successful\n", updateConfig.getConfig()); logger.info("Expected Response:" + expectedResponse.toString()); Response response = ConfigHelper.deleteConfigByName(productName); CSValidationHelper.validate_cs_api_response(response); logger.info("Validate Database for Deletion"); List<String> tables = Stream.of(ConfigTables.values()).map(Enum::name).collect(Collectors.toList()); for (String tableName : tables) { CSDBHelper.verifyNoActivityRecordPresent(tableName, null); } logger.info("Validate Database"); AppAssert.assertEqual( DBUtils.getRecord("config_details", "request_data= " + CSDBHelper.dbReadableFormat(productName)) .get(0).get("request_type").toString(), "Delete", "Verify Databse is updated for Delete Request"); logger.info("Validate Resposne Body"); ConfigResponseVO actualResposne = response.as(ConfigResponseVO.class); logger.info("Actual Resposne:" + actualResposne.toString()); ConfigValidationHelper.validateResponse(actualResposne, expectedResponse); } catch (Exception e) { e.printStackTrace(); } } } <file_sep> package com.vuclip.premiumengg.automation.subscription_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.Getter; import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "blockType", "startDate", "endDate" }) @Getter @Setter public class BlockedUserData { @JsonProperty("blockType") private String blockType; @JsonProperty("startDate") private Long startDate; @JsonProperty("endDate") private Long endDate; } <file_sep>ssServer=http://10.11.100.8:8091/schedular-service dbServer=10.11.100.8 dbPort=3306 dbName=schedular dbUser=root dbPassword=<PASSWORD> rabbitMQServer=10.11.100.8 rabbitMQPort=5672 rabbitMQUser=jenkins rabbitMQPassword=<PASSWORD> <file_sep> package com.vuclip.premiumengg.automation.subscription_service.common.models; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "smsConfigId", "type", "redirectionContext", "defaultSmsLanguageId", "batchSize", "smsLength", "autoPlay", "status", "criterias", "productId", "partnerId", "countryCode", "operationType" }) public class SmsConfig { @JsonProperty("smsConfigId") private Integer smsConfigId; @JsonProperty("type") private String type; @JsonProperty("redirectionContext") private String redirectionContext; @JsonProperty("defaultSmsLanguageId") private Integer defaultSmsLanguageId; @JsonProperty("batchSize") private Integer batchSize; @JsonProperty("smsLength") private Integer smsLength; @JsonProperty("autoPlay") private Boolean autoPlay; @JsonProperty("status") private String status; @JsonProperty("criterias") private List<Criteria> criterias = null; @JsonProperty("productId") private Integer productId; @JsonProperty("partnerId") private Integer partnerId; @JsonProperty("countryCode") private String countryCode; @JsonProperty("operationType") private String operationType; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("smsConfigId") public Integer getSmsConfigId() { return smsConfigId; } @JsonProperty("smsConfigId") public void setSmsConfigId(Integer smsConfigId) { this.smsConfigId = smsConfigId; } @JsonProperty("type") public String getType() { return type; } @JsonProperty("type") public void setType(String type) { this.type = type; } @JsonProperty("redirectionContext") public String getRedirectionContext() { return redirectionContext; } @JsonProperty("redirectionContext") public void setRedirectionContext(String redirectionContext) { this.redirectionContext = redirectionContext; } @JsonProperty("defaultSmsLanguageId") public Integer getDefaultSmsLanguageId() { return defaultSmsLanguageId; } @JsonProperty("defaultSmsLanguageId") public void setDefaultSmsLanguageId(Integer defaultSmsLanguageId) { this.defaultSmsLanguageId = defaultSmsLanguageId; } @JsonProperty("batchSize") public Integer getBatchSize() { return batchSize; } @JsonProperty("batchSize") public void setBatchSize(Integer batchSize) { this.batchSize = batchSize; } @JsonProperty("smsLength") public Integer getSmsLength() { return smsLength; } @JsonProperty("smsLength") public void setSmsLength(Integer smsLength) { this.smsLength = smsLength; } @JsonProperty("autoPlay") public Boolean getAutoPlay() { return autoPlay; } @JsonProperty("autoPlay") public void setAutoPlay(Boolean autoPlay) { this.autoPlay = autoPlay; } @JsonProperty("status") public String getStatus() { return status; } @JsonProperty("status") public void setStatus(String status) { this.status = status; } @JsonProperty("criterias") public List<Criteria> getCriterias() { return criterias; } @JsonProperty("criterias") public void setCriterias(List<Criteria> criterias) { this.criterias = criterias; } @JsonProperty("productId") public Integer getProductId() { return productId; } @JsonProperty("productId") public void setProductId(Integer productId) { this.productId = productId; } @JsonProperty("partnerId") public Integer getPartnerId() { return partnerId; } @JsonProperty("partnerId") public void setPartnerId(Integer partnerId) { this.partnerId = partnerId; } @JsonProperty("countryCode") public String getCountryCode() { return countryCode; } @JsonProperty("countryCode") public void setCountryCode(String countryCode) { this.countryCode = countryCode; } @JsonProperty("operationType") public String getOperationType() { return operationType; } @JsonProperty("operationType") public void setOperationType(String operationType) { this.operationType = operationType; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } } <file_sep>package com.vuclip.premiumengg.automation.billing_package_service.common.base; import com.vuclip.premiumengg.automation.billing_package_service.common.models.BPSSaveCountryRequest; import com.vuclip.premiumengg.automation.billing_package_service.common.models.BPSSavePartnerRequest; import com.vuclip.premiumengg.automation.billing_package_service.common.models.BPSSaveProductRequest; import com.vuclip.premiumengg.automation.billing_package_service.common.models.BillingPackage; import com.vuclip.premiumengg.automation.billing_package_service.common.utils.BPSContext; import com.vuclip.premiumengg.automation.billing_package_service.common.utils.BPSDBUtil; import com.vuclip.premiumengg.automation.billing_package_service.common.utils.BPSHelper; import com.vuclip.premiumengg.automation.common.Configuration; import com.vuclip.premiumengg.automation.common.JDBCTemplate; import com.vuclip.premiumengg.automation.utils.ObjectMapperUtils; import org.apache.commons.lang3.RandomUtils; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import java.io.File; import java.io.FileInputStream; import java.util.Properties; /** * @author Kohitij_Das */ public class InitializeTestSuite { /** * Method to be invoked before launch of any Suite execution. */ @BeforeSuite(alwaysRun = true) public final void init() { System.out.println("====== SettingUp billing-package-service-system-tests execution ======"); FileInputStream inputStream = null; Properties properties = new Properties(); try { String filePath = System.getProperty("propertiesFile"); File configFile = new File(filePath); inputStream = new FileInputStream(configFile); properties.load(inputStream); Configuration.billingPackageServer = properties.getProperty("billingPackageServer"); Configuration.dbServer = properties.getProperty("dbServer"); Configuration.dbPort = properties.getProperty("dbPort"); Configuration.dbName = properties.getProperty("dbName"); Configuration.dbUser = properties.getProperty("dbUser"); Configuration.dbPassword = <PASSWORD>("dbPassword"); int id = RandomUtils.nextInt(100, 100000); BPSHelper bPSHelper = new BPSHelper(); BPSSaveCountryRequest saveCountryRequest = ObjectMapperUtils.readValue( "src/test/resources/configurations/billing-package-service/request/saveCountry.json", BPSSaveCountryRequest.class); bPSHelper.saveCountry(saveCountryRequest); BPSSavePartnerRequest savePartnerRequest = ObjectMapperUtils.readValue( "src/test/resources/configurations/billing-package-service/request/savePartner.json", BPSSavePartnerRequest.class); savePartnerRequest.setPartnerId(id); savePartnerRequest.setPartnerName("PN_" + id); bPSHelper.savePartner(savePartnerRequest); BPSSaveProductRequest saveProductRequest = ObjectMapperUtils.readValue( "src/test/resources/configurations/billing-package-service/request/saveProduct.json", BPSSaveProductRequest.class); saveProductRequest.getProduct().setProductId(id); saveProductRequest.getProduct().setProductName("PN_" + id); saveProductRequest.getPricePoints().get(0).setPartnerId(id); saveProductRequest.getPricePoints().get(0).setProductId(id); saveProductRequest.getPricePoints().get(0).setBillingCode("billingCode" + id + "1"); saveProductRequest.getPricePoints().get(0).setFallbackPpBillingCode("billingCode" + id + "2"); saveProductRequest.getPricePoints().get(0).setFreeTrialBillingCode("billingCode" + id + "3"); bPSHelper.saveProduct(saveProductRequest); BPSContext.saveCountryRequest = saveCountryRequest; BPSContext.savePartnerRequest = savePartnerRequest; BPSContext.saveProductRequest = saveProductRequest; BillingPackage.PACKAGE1 = new BillingPackage(id, "PN_" + id, id, "PN_" + id, "IN", "IN", "billingCode" + id + "1", saveProductRequest.getPricePoints().get(0).getServiceId(), saveProductRequest.getPricePoints().get(0).getPrice(), saveCountryRequest.getCurrency(), 0, saveProductRequest.getPricePoints().get(0).getParkingPeriod(), saveProductRequest.getPricePoints().get(0).getSuspendPeriod(), saveProductRequest.getPricePoints().get(0).getNotificationWaitPeriod(), saveProductRequest.getPricePoints().get(0).getTimeUnit(), saveProductRequest.getPricePoints().get(0).getItemId(), saveProductRequest.getPricePoints().get(0).getItemTypeId(), 0, saveProductRequest.getPricePoints().get(0).getStatus(), saveProductRequest.getPricePoints().get(0).getBalanceCheckRequired(), false, false, false); } catch (Exception e) { e.printStackTrace(); } } @AfterSuite(alwaysRun = true) public void teardown() throws Exception { JDBCTemplate.closeAllConnections(); new BPSDBUtil().cleanupBillingPackage(); } }<file_sep>package com.vuclip.premiumengg.automation.billing_package_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import groovy.transform.ToString; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"product", "pricePoints"}) @Getter @Setter @ToString @NoArgsConstructor @AllArgsConstructor public class BPSSaveProductRequest { @JsonProperty("product") private BPSProduct product; @JsonProperty("pricePoints") private List<BPSPricePoint> pricePoints = null; } <file_sep>package com.vuclip.premiumengg.automation.ad_network_service.common.models; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.*; import java.util.HashMap; import java.util.List; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"criteriaId", "smsText", "criterions", "dateCoumputationCriterion"}) @Getter @Setter @ToString @EqualsAndHashCode @AllArgsConstructor @NoArgsConstructor public class Criteria { @JsonProperty("criteriaId") private Integer criteriaId; @JsonProperty("smsText") private String smsText; @JsonProperty("criterions") private List<Criterion> criterions = null; @JsonProperty("dateCoumputationCriterion") private DateCoumputationCriterion dateCoumputationCriterion; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); }<file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.tests; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.models.PublishConfigRequest; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.models.UserSubscriptionRequest; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils.*; import org.apache.commons.lang3.RandomUtils; import org.apache.log4j.Logger; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * @author rahul.sahu */ public class SASSuccessDeactivationChurn { private static Logger logger = Log4J.getLogger("SASSuccessDeactivationChurn"); int productId; int partnerId; PublishConfigRequest publishConfigRequest = null; private String countryCode = "IN"; @BeforeClass(alwaysRun = true) public void setup() throws Exception { productId = SASUtils.productId; partnerId = productId; } @DataProvider(name = "successTwoFlowPositiveDataProvider") public Object[][] successTwoFlowPositiveDataProvider() { return new Object[][]{ /* PASSED */ {"DEACTIVATE_CONSENT", "DEACTIVATION", "DCT_INIT", "FAILURE", "deactivation", "OPEN", "IN_PROGRESS", "SUCCESS", "DEACTIVATION_RETRY", "DEACTIVATION_RETRY", "DEACTIVATION_RETRY", "DEACTIVATE_CONSENT", "DEACTIVATION_RETRY", "DEACTIVATED", "SUCCESS"}, /* RAHUL * {"DEACTIVATE_CONSENT", "SYSTEM_CHURN", "DCT_INIT", "IN_PROGRESS", "churn", * "OPEN", "IN_PROGRESS", "SUCCESS", * "SYSTEM_CHURN","SYSTEM_CHURN","SYSTEM_CHURN", "DEACTIVATE_CONSENT", * "SYSTEM_CHURN", "DEACTIVATED","SUCCESS"}, */}; } @Test(dataProvider = "successTwoFlowPositiveDataProvider", groups = {"positive"}) public void successTwoFlowPositiveTests(String eventActionType, String activityType, String currentSubscriptionState, String transactionState, String actionTable, String beforeSchedularStatus, String afterSchedularStatus, String afteNewEventStatus, String schedularActivityType, String queueName, String queueActivity, String newEventActionType, String newActivityType, String newCurrentSubscriptionState, String newTransactionState) { Integer subscriptionId = RandomUtils.nextInt(58000, 59000); String testMessage = subscriptionId + " " + activityType + " " + currentSubscriptionState + " " + transactionState + " " + actionTable + " " + newCurrentSubscriptionState; logger.info("***************Starting success Two Flow Positive Tests [ " + testMessage + " ]"); try { SASHelper sasHelper = new SASHelper(); Logger logger = Log4J.getLogger("SAS FLOW"); logger.info("=========>First time user subscription event getting trigger"); UserSubscriptionRequest firstUserSubscriptionRequest = SASUtils.generateUserSubscriptionRequest(productId, partnerId, activityType, currentSubscriptionState, transactionState, eventActionType, subscriptionId); SASValidationHelper.validate_sas_api_response(sasHelper.userSubscription(firstUserSubscriptionRequest)); SASDBHelper.showAllActivityTableData("FIRST ", String.valueOf(subscriptionId)); logger.info("=========>First event: Verify DB after event trigger"); SASValidationHelper.verifyEventTable(actionTable, subscriptionId, productId, partnerId, firstUserSubscriptionRequest.getSubscriptionInfo().getNextBillingDate(), beforeSchedularStatus, countryCode); logger.info("=========>First Event: scheduale call "); SASValidationHelper.validate_schedular_api_response( sasHelper.scheduler(SASUtils.generateSchedulerRequest(productId, partnerId, actionTable))); SASDBHelper.showAllActivityTableData("second", String.valueOf(subscriptionId)); logger.info("=========>First Event: Vefiry DB After Schedular Call "); SASValidationHelper.verifyEventTable(actionTable, subscriptionId, productId, partnerId, firstUserSubscriptionRequest.getSubscriptionInfo().getNextBillingDate(), afterSchedularStatus, countryCode); logger.info("=========>First Event: Queue verification : "); SASValidationHelper.validateQueue(queueName, queueActivity, productId, partnerId, subscriptionId, countryCode); logger.info("=========>Second time user subscription event getting trigger"); UserSubscriptionRequest newSubscriptionRequest = SASUtils.generateUserSubscriptionRequest(productId, partnerId, newActivityType.toUpperCase(), newCurrentSubscriptionState, newTransactionState, newEventActionType, subscriptionId, DateTimeUtil.getDateByAddingValidity( firstUserSubscriptionRequest.getSubscriptionInfo().getNextBillingDate(), 1, TimeUnitEnum.DAY.name())); SASValidationHelper.validate_sas_api_response(sasHelper.userSubscription(newSubscriptionRequest)); SASDBHelper.showAllActivityTableData("THIRD", String.valueOf(subscriptionId)); logger.info("=========>Second event: previous Event's DB verification"); SASValidationHelper.verifyEventTable(actionTable, subscriptionId, productId, partnerId, firstUserSubscriptionRequest.getSubscriptionInfo().getNextBillingDate(), afteNewEventStatus, countryCode); } catch (Exception e) { Assert.fail(e.getMessage()); } } } <file_sep>package com.vuclip.premiumengg.automation.subscription_service.common.models; import java.util.HashMap; import java.util.Map; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; /** * * @author <EMAIL> * */ @Data @Builder @NoArgsConstructor @AllArgsConstructor @ToString public class SubscriptionStatusDto { private String userId; private Long userSubscriptionId; private Long subStartDate; private Long subEndDate; private Long nextBillingDate; private Double amount; private Country country; private Partner partner; private SubscriptionPlanCycle planCycle; private Long partnerId; private boolean isSubscribeable; private boolean isBalcklisted; private boolean isCooldown; private SubscriptionStatus subscriptionStatus; private String msisdn; private int subscriptionValidityDays; private int providerId; private String subscriptionBillingCode; private String chargedBillingCode; private String customerTransactionId; private SubType subType; private Advertisement advertisement; private boolean renewalAllowed; private Map<String, String> payload = new HashMap<String, String>(); } <file_sep>package com.vuclip.premiumengg.automation.ad_network_service.common.utils; public class ANSTestContext { public static int productId; public static String billingCode; public static String countryCode = "IN"; public static int paidPercentage = 100; public static int freePercentage = 100; public static int winbackPercentage = 100; public static Boolean freeTrialApplicable = false; public static Integer parkingPeriod = 10; public static String churnNotificationUrl = "http://172.16.17.32:6060/conversion/{XXX}/pixel.jpg"; public static String notificationUrl = "http://172.16.17.32:6060/conversion/{XXX}/pixel.jpg"; public static String productName = "AIRTEL"; public static String timezone = "GMT"; public static Integer adNetworkId; public static int partnerId; public static String requestParamName; } <file_sep>package com.vuclip.premiumengg.automation.ad_network_service.common.models; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.*; import java.util.HashMap; import java.util.List; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"smsConfigId", "type", "redirectionContext", "defaultSmsLanguageId", "batchSize", "smsLength", "autoPlay", "status", "criterias", "productId", "partnerId", "countryCode", "operationType"}) @Getter @Setter @ToString @EqualsAndHashCode @AllArgsConstructor @NoArgsConstructor public class SmsConfig { @JsonProperty("smsConfigId") private Integer smsConfigId; @JsonProperty("type") private String type; @JsonProperty("redirectionContext") private String redirectionContext; @JsonProperty("defaultSmsLanguageId") private Integer defaultSmsLanguageId; @JsonProperty("batchSize") private Integer batchSize; @JsonProperty("smsLength") private Integer smsLength; @JsonProperty("autoPlay") private Boolean autoPlay; @JsonProperty("status") private String status; @JsonProperty("criterias") private List<Criteria> criterias = null; @JsonProperty("productId") private Integer productId; @JsonProperty("partnerId") private Integer partnerId; @JsonProperty("countryCode") private String countryCode; @JsonProperty("operationType") private String operationType; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); }<file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @EqualsAndHashCode(exclude= {"operationType"}) @ToString @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_EMPTY) public class StateConfigVO { private int stateConfigId; private int actInitDuration; private int activeDuration; private int parkingDuration; private int graceDuration; private int suspendDuration; private int blacklistDuration; private String productName; private String partnerName; private String countryName; private String pricePoint; private String operationType; } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.vuclip.premiumengg.automation.ad_network_service.common.models.Country; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @EqualsAndHashCode @ToString @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonIgnoreProperties({ "countries" }) @JsonPropertyOrder({ "product", "productPartnerMappings", "productCountryMapping", "smsConfigs", "retry", "churnNotifications", "adNetworkNotifications", "pricePoints", "stateConfigs", "blockouts","activityFlows","countries" }) public class ConfigVO { @JsonProperty("product") private ProductVO product; @JsonProperty("productPartnerMappings") private List<ProductPartnerMappingVO> productPartnerMappings = null; @JsonProperty("productCountryMapping") private ProductCountryMappingVO productCountryMapping; @JsonProperty("smsConfigs") private List<SmsConfigVO> smsConfigs = null; @JsonProperty("retry") private List<RetryVO> retry = null; @JsonProperty("churnNotifications") private List<ChurnNotificationVO> churnNotifications = null; @JsonProperty("adNetworkNotifications") private List<AdNetworkNotificationVO> adNetworkNotifications = null; @JsonProperty("pricePoints") private List<PricePointVO> pricePoints = null; @JsonProperty("stateConfigs") private List<StateConfigVO> stateConfigs = null; @JsonProperty("blockouts") private List<BlackoutVO> blockouts = null; @JsonProperty("activityFlows") private List<ActivityFlowVO> activityFlows = new ArrayList<>(); @JsonProperty("countries") private List<Country> countries; } <file_sep>package com.vuclip.premiumengg.automation.common; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * Created by rahul s */ public class RedisTemplateConnection { private static RedisTemplate<String, Object> template = null; private RedisTemplateConnection() { } @SuppressWarnings("deprecation") public static RedisTemplate<String, Object> getRedisConnection() { if (template == null) { Log4J.getLogger().info("Setting up Redis Template"); template = new RedisTemplate<>(); String config[] = Configuration.redisServers.split(":"); JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(); jedisConnectionFactory.setHostName(config[0]); jedisConnectionFactory.setPort(Integer.parseInt(config[1])); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); @SuppressWarnings({"rawtypes", "unchecked"}) Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); template.setValueSerializer(jackson2JsonRedisSerializer); template.setKeySerializer(new StringRedisSerializer()); template.setConnectionFactory(jedisConnectionFactory); template.afterPropertiesSet(); } Log4J.getLogger().info("Redis Template is set"); return template; } public static void closeConnection() { if (template != null) if (template.getConnectionFactory() != null) if (template.getConnectionFactory().getConnection() != null) template.getConnectionFactory().getConnection().close(); } public static ValueOperations<String, Object> getValueOperation() { return getRedisConnection().opsForValue(); } } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @EqualsAndHashCode(callSuper = false) @ToString @Builder @AllArgsConstructor @NoArgsConstructor @JsonPropertyOrder({ "successful", "responseCode", "message", "adNetwork" }) public class AdNetworkResponseVO { @JsonProperty("successful") private boolean successful; @JsonProperty("responseCode") private int responseCode; @JsonProperty("message") private String message; @JsonProperty("adNetwork") private AdNetworkVO adNetwork; } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; public enum ItemTypeId { PRODUCT(0), CATEGORY(1), LANGUAGE(2), MICROSITE(3), BANNER(4), LINK(5); private final int value; ItemTypeId(int value) { this.value = value; } public int getValue() { return value; } public static ItemTypeId fromValue(int val) { for (ItemTypeId type : ItemTypeId.values()) { if (type.getValue() == val) { return type; } } return null; } } <file_sep> package com.vuclip.premiumengg.automation.subscription_service.common.models; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "product", "productPartnerMappings", "productCountryMapping", "smsConfigs", "retry", "churnNotifications", "adNetworkNotifications", "pricePoints", "stateConfigs", "blackouts", "activityFlows" }) public class SaveProductRequest { @JsonProperty("product") private Product product; @JsonProperty("productPartnerMappings") private List<ProductPartnerMapping> productPartnerMappings = null; @JsonProperty("productCountryMapping") private ProductCountryMapping productCountryMapping; @JsonProperty("smsConfigs") private List<SmsConfig> smsConfigs = null; @JsonProperty("retry") private List<Retry> retry = null; @JsonProperty("churnNotifications") private List<ChurnNotification> churnNotifications = null; @JsonProperty("adNetworkNotifications") private List<AdNetworkNotification> adNetworkNotifications = null; @JsonProperty("pricePoints") private List<PricePoint> pricePoints = null; @JsonProperty("stateConfigs") private List<StateConfig> stateConfigs = null; @JsonProperty("blackouts") private List<Blackout> blackouts = null; @JsonProperty("activityFlows") private List<ActivityFlow> activityFlows = null; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("product") public Product getProduct() { return product; } @JsonProperty("product") public void setProduct(Product product) { this.product = product; } @JsonProperty("productPartnerMappings") public List<ProductPartnerMapping> getProductPartnerMappings() { return productPartnerMappings; } @JsonProperty("productPartnerMappings") public void setProductPartnerMappings(List<ProductPartnerMapping> productPartnerMappings) { this.productPartnerMappings = productPartnerMappings; } @JsonProperty("productCountryMapping") public ProductCountryMapping getProductCountryMapping() { return productCountryMapping; } @JsonProperty("productCountryMapping") public void setProductCountryMapping(ProductCountryMapping productCountryMapping) { this.productCountryMapping = productCountryMapping; } @JsonProperty("smsConfigs") public List<SmsConfig> getSmsConfigs() { return smsConfigs; } @JsonProperty("smsConfigs") public void setSmsConfigs(List<SmsConfig> smsConfigs) { this.smsConfigs = smsConfigs; } @JsonProperty("retry") public List<Retry> getRetry() { return retry; } @JsonProperty("retry") public void setRetry(List<Retry> retry) { this.retry = retry; } @JsonProperty("churnNotifications") public List<ChurnNotification> getChurnNotifications() { return churnNotifications; } @JsonProperty("churnNotifications") public void setChurnNotifications(List<ChurnNotification> churnNotifications) { this.churnNotifications = churnNotifications; } @JsonProperty("adNetworkNotifications") public List<AdNetworkNotification> getAdNetworkNotifications() { return adNetworkNotifications; } @JsonProperty("adNetworkNotifications") public void setAdNetworkNotifications(List<AdNetworkNotification> adNetworkNotifications) { this.adNetworkNotifications = adNetworkNotifications; } @JsonProperty("pricePoints") public List<PricePoint> getPricePoints() { return pricePoints; } @JsonProperty("pricePoints") public void setPricePoints(List<PricePoint> pricePoints) { this.pricePoints = pricePoints; } @JsonProperty("stateConfigs") public List<StateConfig> getStateConfigs() { return stateConfigs; } @JsonProperty("stateConfigs") public void setStateConfigs(List<StateConfig> stateConfigs) { this.stateConfigs = stateConfigs; } @JsonProperty("blackouts") public List<Blackout> getBlackouts() { return blackouts; } @JsonProperty("blackouts") public void setBlackouts(List<Blackout> blackouts) { this.blackouts = blackouts; } @JsonProperty("activityFlows") public List<ActivityFlow> getActivityFlows() { return activityFlows; } @JsonProperty("activityFlows") public void setActivityFlows(List<ActivityFlow> activityFlows) { this.activityFlows = activityFlows; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } } <file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.utils.DBUtils; import java.util.List; import java.util.Map; public class SASDBHelper { /** * @param whereClause */ public static void cleanTestData(String whereClause) { DBUtils.cleanTable("activation", whereClause); DBUtils.cleanTable("churn", whereClause); DBUtils.cleanTable("content_sms_user_info", whereClause); DBUtils.cleanTable("deactivation", whereClause); DBUtils.cleanTable("engagement_sms_user_info", whereClause); DBUtils.cleanTable("free_trail", whereClause); DBUtils.cleanTable("optout_sms_user_info", whereClause); DBUtils.cleanTable("prerenewal_sms_user_info", whereClause); DBUtils.cleanTable("renewal", whereClause); DBUtils.cleanTable("renewal_retry", whereClause); DBUtils.cleanTable("winback", whereClause); } /** * @param whereClause */ public static void cleanAllTables(String whereClause) { DBUtils.cleanTable("job_config", whereClause); DBUtils.cleanTable("activation", whereClause); DBUtils.cleanTable("churn", whereClause); DBUtils.cleanTable("content_sms_user_info", whereClause); DBUtils.cleanTable("deactivation", whereClause); DBUtils.cleanTable("engagement_sms_user_info", whereClause); DBUtils.cleanTable("free_trail", whereClause); DBUtils.cleanTable("optout_sms_user_info", whereClause); DBUtils.cleanTable("prerenewal_sms_user_info", whereClause); DBUtils.cleanTable("product_partner_country_config", whereClause); DBUtils.cleanTable("renewal", whereClause); DBUtils.cleanTable("winback", whereClause); } /** * DO NOT DELETE THIS IS FOR DEBUG PURPOSE WHEN WE WANT TO SEE DB ACTIVITIES DURING FIXING TEST CASE * * @param message * @param subscriptionId */ public static String showAllActivityTableData(String message, String subscriptionId) { String type = null; // try { // List<Map<String, Object>> record1 = DBUtils.getRecords("activation", // "subscription_id = " + subscriptionId); // if (record1.size() >= 1) { // Log4J.getLogger().info(message + "table name activation "); // logTableRecord(record1); // // type = "activation"; // } // List<Map<String, Object>> record2 = DBUtils.getRecords("deactivation", // "subscription_id = " + subscriptionId); // if (record2.size() >= 1) { // Log4J.getLogger().info(message + "table name deactivation "); // logTableRecord(record2); // // type = "deactivation"; // } // List<Map<String, Object>> record3 = DBUtils.getRecords("churn", // "subscription_id = " + subscriptionId); // if (record3.size() >= 1) { // Log4J.getLogger().info(message + "table name churn "); // logTableRecord(record3); // // type = "churn"; // } // List<Map<String, Object>> record4 = DBUtils.getRecords("free_trail", // "subscription_id = " + subscriptionId); // if (record4.size() >= 1) { // Log4J.getLogger().info(message + "table name free_trial"); // logTableRecord(record4); // // type = "free_trial"; // } // List<Map<String, Object>> record5 = DBUtils.getRecords("renewal", // "subscription_id = " + subscriptionId); // if (record5.size() >= 1) { // Log4J.getLogger().info(message + "table name renewal "); // logTableRecord(record5); // // type = "renewal"; // } // List<Map<String, Object>> record6 = DBUtils.getRecords("winback", // "subscription_id = " + subscriptionId); // if (record6.size() >= 1) { // Log4J.getLogger().info(message + "table name winback "); // logTableRecord(record6); // // type = "winback"; // } // // } catch (Exception e) { // Log4J.getLogger().info("Error in fetching data"); // } return type; } public static void logTableRecord(List<Map<String, Object>> records) { for (Map<String, Object> map : records) { Log4J.getLogger().info(map.get("date").toString() + " " + map.get("status").toString()); } } } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; import java.util.HashMap; import java.util.Map; public enum ActivityType { ACTIVATION(1), RENEWAL(2), DEACTIVATION(3), WINBACK(4), ACTIVATION_RETRY(5), FREETRIAL_RENEWAL( 6), DEACTIVATION_RETRY(7), SYSTEM_CHURN(8), UNBLOCK(9), BLACKLIST(10); private int activityId; private ActivityType(int activityId) { this.activityId = activityId; } public int getActivityId() { return activityId; } private static Map<Integer, ActivityType> activityTypeEnumMap = new HashMap<>(); private static Map<String, ActivityType> activityTypeByNameap = new HashMap<>(); static { for (ActivityType activityTypeEnum : ActivityType.values()) { activityTypeEnumMap.put(activityTypeEnum.activityId, activityTypeEnum); activityTypeByNameap.put(activityTypeEnum.toString(), activityTypeEnum); } } public static ActivityType getActivity(int activityId) { return activityTypeEnumMap.get(activityId); } public static ActivityType getActivity(String name) { return activityTypeByNameap.get(name); } } <file_sep>package com.vuclip.premiumengg.automation.ad_network_service.common.models; public enum ANSTableNames { user_adnotification("user_adnotification"), ad_network("ad_network"), app_user("app_user"), billing_package( "billing_package"), product_adnetwork_details( "product_adnetwork_details"), temp_failover_store("temp_failover_store"); private String value; private ANSTableNames(String value) { this.value = value; } public static ANSTableNames fromValue(String val) { for (ANSTableNames tableName : ANSTableNames.values()) { if (tableName.getValue().equals(val)) { return tableName; } } return null; } public String getValue() { return value; } } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; @Getter @EqualsAndHashCode @ToString @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_EMPTY) public class CriterionVO { private int criterionId; private CriterionName name; private CriterionOperator operator; private String value; private GroupingOperator groupingOperator; } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; public enum DeleteConfigTables { action, activity_flow, ad_network_notification, blackout, churn_notification, config_details, criterion, price_point, product, product_country, product_partner, retry, state_config } <file_sep>package com.vuclip.premiumengg.automation.utils; import com.vuclip.premiumengg.automation.common.JDBCTemplate; import com.vuclip.premiumengg.automation.common.Log4J; import java.sql.SQLException; import java.util.List; import java.util.Map; public class DBUtils { public static List<Map<String, Object>> getRecord(String tableName, String whereClause) throws SQLException { List<Map<String, Object>> record = getRecords(tableName, whereClause); if (record.size() > 1) throw new SQLException("There are more then one records for query"); else return record; } public static int cleanTable(String tableName, String whereClause) { String query = "delete from " + tableName; if (whereClause != null) query += " where " + whereClause; try { Log4J.getLogger("DBLogger").info(query); return JDBCTemplate.getDbConnection().update(query); } catch (Exception ex) { System.out.println(ex.getMessage()); } return 0; } public static List<Map<String, Object>> getRecords(String tableName, String whereClause) { String query = "select * from " + tableName; if (whereClause != null) query += " where " + whereClause; try { Thread.sleep(600); Log4J.getLogger("DBLogger").info(query); return JDBCTemplate.getDbConnection().queryForList(query); } catch (Exception ex) { System.out.println(ex.getMessage()); } return null; } public static void addRecordInTable(String tableName, String clause) { String query = "INSERT INTO " + tableName; if (clause != null) query += " VALUES(" + clause + ")"; try { Log4J.getLogger("DBLogger").info(query); JDBCTemplate.getDbConnection().execute(query); } catch (Exception ex) { System.out.println(ex.getMessage()); } } } <file_sep>package com.vuclip.premiumengg.automation.subscription_service.common.utils; import java.sql.SQLException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.log4j.Logger; import com.vuclip.premiumengg.automation.common.JDBCTemplate; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.utils.AppAssert; import com.vuclip.premiumengg.automation.utils.DBUtils; public class SDBHelper { static Logger logger = Log4J.getLogger("SSDBHelper"); public static void verifyNoActivityRecordPresent(String tableName, int productId, int partnerId, String userId) throws SQLException { AppAssert .assertTrue( DBUtils.getRecord(tableName, "user_id =" + userId + " and product_id =" + String.valueOf(productId) + " and partner_id=" + String.valueOf(partnerId)) .size() == 0, "verify no entry in " + tableName); } public static boolean getFlag(String flagType, String userId) throws SQLException { logger.info("get flag value for " + flagType); List<Map<String, Object>> getFlag = DBUtils.getRecord("user_subscription", "user_id=" + userId); boolean flag = (boolean) getFlag.get(0).get(flagType); logger.info(flagType + ":" + flag); return flag; } public static Object getColumnValueUsingUserId(String tableName, String columnName, String whereClause) throws SQLException { logger.info("get value for " + columnName + " from " + tableName); List<Map<String, Object>> getValue = DBUtils.getRecord(tableName, whereClause); Object value = (Object) getValue.get(0).get(columnName); logger.info(columnName + ":" + value.toString()); return value; } public static int getValidityDaysFromProductPartner(String validityType) throws SQLException { logger.info("get validity days for " + validityType); List<Map<String, Object>> dateRecord = DBUtils.getRecord("product_partner_country_mapping", "product_id=" + SUtils.productId); Integer days = (Integer) dateRecord.get(0).get(validityType); logger.info(validityType + ":" + days); return days; } public static int getValidityDaysFromBillingPackage(String validityType, String billingCode) throws SQLException { logger.info("get validity days for " + validityType); List<Map<String, Object>> dateRecord = DBUtils.getRecord("billing_package", "billing_code=" + SUtils.dbReadableFormat(billingCode)); Integer days = (Integer) dateRecord.get(0).get(validityType); logger.info(validityType + ":" + days); return days; } public static Integer validateDates(String tableName, String whereClause, String startDateCoulmnName, String endDateColumnName) throws SQLException { logger.info("Get day difference between " + startDateCoulmnName + " and " + endDateColumnName); List<Map<String, Object>> dateRecord = DBUtils.getRecord(tableName, whereClause); Long startDate = (Long) dateRecord.get(0).get(startDateCoulmnName); Long endDate = (Long) dateRecord.get(0).get(endDateColumnName); Integer days = (int) DateUtils.getDaysBetweenJavaDates(DateUtils.convertLongToStringDate(startDate), DateUtils.convertLongToStringDate(endDate)); logger.info("Days:" + days); return days; } public static Integer validateDatesBlockedUser(String tableName, String whereClause, String startDateCoulmnName, String endDateColumnName) throws SQLException { logger.info("Get day difference between " + startDateCoulmnName + " and " + endDateColumnName); List<Map<String, Object>> dateRecord = DBUtils.getRecord(tableName, whereClause); Long startDate = (Long) dateRecord.get(0).get(startDateCoulmnName); Long endDate = (Long) dateRecord.get(0).get(endDateColumnName); Integer days = (int) DateUtils.getDaysBetweenJavaDates(startDate.toString(), endDate.toString()); logger.info("Days:" + days); return days; } public static void cleanAllTables(String whereClause) { DBUtils.cleanTable("product_partner_country_mapping", whereClause); DBUtils.cleanTable("user_subscription", whereClause); DBUtils.cleanTable("blocked_user", whereClause); DBUtils.cleanTable("free_trial_history", whereClause); DBUtils.cleanTable("billing_package", whereClause); DBUtils.cleanTable("blocked_user", whereClause); } public static void validateTable(String tableName, String userId, int productId, int partnerId, Long nextBillingDate, String userSubAuthKey, String subscriptionStatus) throws SQLException { logger.info("=========>Validate Database"); Map<String, String> expectedRecords = new HashMap<String, String>(); expectedRecords.put("next_billing_date", String.valueOf(nextBillingDate)); expectedRecords.put("partner_id", String.valueOf(partnerId)); expectedRecords.put("product_id", String.valueOf(productId)); expectedRecords.put("user_id", userId); expectedRecords.put("user_sub_auth_key", userSubAuthKey); expectedRecords.put("subscription_status", subscriptionStatus); SValidationHelper.validateTableRecord(DBUtils.getRecord(tableName, "user_id=" + userId).get(0), expectedRecords); } @SuppressWarnings("rawtypes") public static void addRecordInTable(String tableName, Map<String, Object> tableData) { int size = tableData.size(); Map.Entry pairs = null; String query = "INSERT INTO XXX (YYY) VALUES (ZZZ)"; String coulmnName = ""; String columnData = ""; Iterator<Entry<String, Object>> it = tableData.entrySet().iterator(); int counter = 1; while (it.hasNext()) { pairs = it.next(); coulmnName += pairs.getKey(); columnData += pairs.getValue(); if (size > counter) { coulmnName += ", "; columnData += ", "; } counter++; } query = query.replace("XXX", tableName).replace("YYY", coulmnName).replace("ZZZ", columnData); try { Log4J.getLogger("DBLogger").info(query); Log4J.getLogger("DBLogger").info("Updated " + JDBCTemplate.getDbConnection().update(query) + " Records"); } catch (Exception ex) { System.out.println(ex.getMessage()); } } } <file_sep>dummyServer=http://localhost:8080<file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.tests; import org.apache.commons.lang3.RandomUtils; import org.apache.log4j.Logger; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils.RabbitUtil; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils.SASUtils; /** * @author rahul.sahu */ public class SASActivationDeactivationSuccessTest { private static Logger logger = Log4J.getLogger("SASActivationDeactivationSuccessTest"); int productId; int partnerId; private String countryCode = "IN"; @BeforeClass(alwaysRun = true) public void setup() throws Exception { productId = SASUtils.productId; partnerId = productId; } @DataProvider(name = "activationDeactivationPostiveDataProvider") public Object[][] activationDeactivationPostiveDataProvider() { return new Object[][] { /* * String eventActionType, String activityType, String currentSubscriptionState, * String transactionState, String actionTable, String beforeSchedularStatus, * String afterSchedularStatus, String afteNewEventStatus,String * schedularActivityType, String queueName,String queueActivity, String * newEventActionType, String newActivityType, String * newCurrentSubscriptionState, String newTransactionState, String * newActionTable, String newBeforeSchedularStatus, String * newAfterSchedularStatus,String newSchedularActivityType, String * newQueueName,String newQueueActivityType */ /* SECONDTIMEFIX */{ "CHARGING", "ACTIVATION", "ACTIVATED", "SUCCESS", "renewal", "OPEN", "IN_PROGRESS", "SUCCESS", "RENEWAL", "RENEWAL", "RENEWAL", "CHARGING", "RENEWAL", "ACTIVATED", "SUCCESS", "renewal", "OPEN", "IN_PROGRESS", "RENEWAL", "RENEWAL", "RENEWAL" }, // /* SECONDTIMEFIX */{ "CHARGING", "ACTIVATION", "ACTIVATED", "SUCCESS", "renewal", "OPEN", "IN_PROGRESS", // "ERROR", "RENEWAL", "RENEWAL", "RENEWAL", "CHARGING", "RENEWAL", "ACTIVATED", "ERROR", // "renewal", "OPEN", "IN_PROGRESS", "RENEWAL", "RENEWAL", "RENEWAL" }, // // /* SECONDTIMEFIX */{ "CHARGING", "ACTIVATION", "ACTIVATED", "SUCCESS", "renewal", "OPEN", "IN_PROGRESS", // "FAILURE", "RENEWAL", "RENEWAL", "RENEWAL", "CHARGING", "RENEWAL", "ACTIVATED", "FAILURE", // "renewal", "OPEN", "IN_PROGRESS", "RENEWAL", "RENEWAL", "RENEWAL" }, /* SECONDTIMEFIX */{ "CHARGING", "ACTIVATION", "ACT_INIT", "FAILURE", "activation", "OPEN", "IN_PROGRESS", "SUCCESS", "ACTIVATION_RETRY", "ACTIVATION_RETRY", "ACTIVATION_RETRY", "CHARGING", "ACTIVATION_RETRY", "ACTIVATED", "SUCCESS", "renewal", "OPEN", "IN_PROGRESS", "RENEWAL", "RENEWAL", "RENEWAL" }, /* SECONDTIMEFIX */{ "CHARGING", "ACTIVATION", "ACT_INIT", "FAILURE", "activation", "OPEN", "IN_PROGRESS", "FAILURE", "ACTIVATION_RETRY", "ACTIVATION_RETRY", "ACTIVATION_RETRY", "CHARGING", "ACTIVATION_RETRY", "ACT_INIT", "FAILURE", "activation", "OPEN", "IN_PROGRESS", "ACTIVATION_RETRY", "ACTIVATION_RETRY", "ACTIVATION_RETRY" }, /* SECONDTIMEFIX */{ "CHARGING", "ACTIVATION", "ACT_INIT", "FAILURE", "activation", "OPEN", "IN_PROGRESS", "ERROR", "ACTIVATION_RETRY", "ACTIVATION_RETRY", "ACTIVATION_RETRY", "CHARGING", "ACTIVATION_RETRY", "ACT_INIT", "ERROR", "activation", "OPEN", "IN_PROGRESS", "ACTIVATION_RETRY", "ACTIVATION_RETRY", "ACTIVATION_RETRY" }, /* SECONDTIMEFIX */{ "CHARGING", "ACTIVATION", "PARKING", "LOW_BALANCE", "winback", "OPEN", "IN_PROGRESS", "ERROR", "WINBACK", "WINBACK", "WINBACK", "CHARGING", "WINBACK", "PARKING", "ERROR", "winback", "OPEN", "IN_PROGRESS", "WINBACK", "WINBACK", "WINBACK" }, /* SECONDTIMEFIX */{ "CHARGING", "ACTIVATION", "PARKING", "LOW_BALANCE", "winback", "OPEN", "IN_PROGRESS", "SUCCESS", "WINBACK", "WINBACK", "WINBACK", "CHARGING", "WINBACK", "ACTIVATED", "SUCCESS", "renewal", "OPEN", "IN_PROGRESS", "RENEWAL", "RENEWAL", "RENEWAL" }, /* SECONDTIMEFIX */{ "CHARGING", "ACTIVATION", "PARKING", "LOW_BALANCE", "winback", "OPEN", "IN_PROGRESS", "LOW_BALANCE", "WINBACK", "WINBACK", "WINBACK", "CHARGING", "WINBACK", "PARKING", "LOW_BALANCE", "winback", "OPEN", "IN_PROGRESS", "WINBACK", "WINBACK", "WINBACK" }, }; } @Test(dataProvider = "activationDeactivationPostiveDataProvider", groups = { "bug" }) public void activationDeactivationSuccessPositiveTests(String eventActionType, String activityType, String currentSubscriptionState, String transactionState, String actionTable, String beforeSchedularStatus, String afterSchedularStatus, String afteNewEventStatus, String schedularActivityType, String queueName, String queueActivity, String newEventActionType, String newActivityType, String newCurrentSubscriptionState, String newTransactionState, String newActionTable, String newBeforeSchedularStatus, String newAfterSchedularStatus, String newSchedularActivityType, String newQueueName, String newQueueActivityType) { Integer subscriptionId = RandomUtils.nextInt(58000, 59000); String testMessage = subscriptionId + " " + activityType + " " + currentSubscriptionState + " " + transactionState + " " + actionTable + " " + newCurrentSubscriptionState + " " + newTransactionState + " " + newActionTable; logger.info("***************Starting activationDeactivationSuccessPositiveTests [ " + testMessage + " ]"); RabbitUtil.purgeAllActivityQueue(productId, partnerId, countryCode); try { SASUtils.executeActivityFlows(subscriptionId, productId, partnerId, countryCode, eventActionType, activityType, currentSubscriptionState, transactionState, actionTable, beforeSchedularStatus, afterSchedularStatus, afteNewEventStatus, schedularActivityType, queueName, queueActivity, newEventActionType, newActivityType, newCurrentSubscriptionState, newTransactionState, newActionTable, newBeforeSchedularStatus, newAfterSchedularStatus, newSchedularActivityType, newQueueName, newQueueActivityType); } catch (Exception e) { e.printStackTrace(); logger.info("=========>ERROR due to exception"); Assert.fail(e.getMessage()); } } } <file_sep>ansServer=http://10.11.100.8:8085/ad-network-service dbServer=10.11.100.8 dbPort=3306 dbName=ad_network_service dbUser=root dbPassword=<PASSWORD> rabbitMQServer=10.11.100.8 rabbitMQPort=5672 rabbitMQUser=jenkins rabbitMQPassword=<PASSWORD> ans.redis.clusters=10.11.100.8:6380<file_sep>package com.vuclip.premiumengg.automation.subscription_service.common.models; public class Advertisement { } <file_sep>package com.vuclip.premiumengg.automation.schedular_service.common.utils; import com.vuclip.premiumengg.automation.common.Configuration; import com.vuclip.premiumengg.automation.schedular_service.common.models.SchedulerSaveProductRequest; import io.restassured.http.ContentType; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; import java.util.HashMap; import java.util.Map; import static io.restassured.RestAssured.given; import static io.restassured.RestAssured.with; /** * @author rahul.sahu */ public class SSHelper { // private static Logger logger = Log4J.getLogger("GetJobTests"); private static RequestSpecification requestSpecification; public static RequestSpecification getRequestSpecification() { if (requestSpecification == null) { requestSpecification = with().baseUri(Configuration.ssServer); } return requestSpecification; } public static Response sendMessage(SchedulerSaveProductRequest jsonString) throws Exception { final Response response = given(getRequestSpecification()).contentType(ContentType.JSON).log().all() .body(jsonString).urlEncodingEnabled(false).post("/saveProduct"); response.prettyPrint(); return response; } public static Response getAllJobs() throws Exception { final Response response = given(getRequestSpecification()).contentType(ContentType.JSON).log().all() .get("/job/all-job.mvc"); response.prettyPrint(); return response; } public static Response getRunningJobs(String jobkeyName, String jobGroupName) throws Exception { Map<String, String> parametersMap = new HashMap<>(); parametersMap.put("jobkeyName", jobkeyName); parametersMap.put("jobGroupName", jobGroupName); final Response response = given(getRequestSpecification()).contentType(ContentType.JSON).log().all() .queryParams(parametersMap).get("/job/running-job.mvc"); response.prettyPrint(); return response; } public static Response getPauseJobs(String jobkeyName, String jobGroupName) throws Exception { Map<String, String> parametersMap = new HashMap<>(); parametersMap.put("jobkeyName", jobkeyName); parametersMap.put("jobGroupName", jobGroupName); final Response response = given(getRequestSpecification()).contentType(ContentType.JSON).log().all() .queryParams(parametersMap).get("/job/pause-job.mvc"); response.prettyPrint(); return response; } public static Response runJob(String jobkeyName, String jobGroupName) throws Exception { Map<String, String> parametersMap = new HashMap<>(); parametersMap.put("jobkeyName", jobkeyName); parametersMap.put("jobGroupName", jobGroupName); final Response response = given(getRequestSpecification()).contentType(ContentType.JSON).log().all() .queryParams(parametersMap).get("/job/admin/run-now-job.mvc"); response.prettyPrint(); return response; } public static Response pauseJob(String jobkeyName, String jobGroupName) throws Exception { Map<String, String> parametersMap = new HashMap<>(); parametersMap.put("jobkeyName", jobkeyName); parametersMap.put("jobGroupName", jobGroupName); final Response response = given(getRequestSpecification()).contentType(ContentType.JSON).log().all() .queryParams(parametersMap).get("/job/admin/pause-job.mvc"); response.prettyPrint(); return response; } public static Response resumeJob(String jobkeyName, String jobGroupName) throws Exception { Map<String, String> parametersMap = new HashMap<>(); parametersMap.put("jobkeyName", jobkeyName); parametersMap.put("jobGroupName", jobGroupName); final Response response = given(getRequestSpecification()).contentType(ContentType.JSON).log().all() .queryParams(parametersMap).get("/job/admin/resume-job.mvc"); response.prettyPrint(); return response; } public static Response removeJob(String jobkeyName, String jobGroupName) throws Exception { Map<String, String> parametersMap = new HashMap<>(); parametersMap.put("jobkeyName", jobkeyName); parametersMap.put("jobGroupName", jobGroupName); final Response response = given(getRequestSpecification()).contentType(ContentType.JSON).log().all() .queryParams(parametersMap).get("/job/admin/remove-job.mvc"); response.prettyPrint(); return response; } public static Response interruptJob(String jobkeyName, String jobGroupName) throws Exception { Map<String, String> parametersMap = new HashMap<>(); parametersMap.put("jobkeyName", jobkeyName); parametersMap.put("jobGroupName", jobGroupName); final Response response = given(getRequestSpecification()).contentType(ContentType.JSON).log().all() .queryParams(parametersMap).get("/job/admin/interrupt-job.mvc"); response.prettyPrint(); return response; } } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; public enum FlowType { VUCLIP_CONSENT, PARTNER_CONSENT, VUCLIP_SYNC, VUCLIP_ASYNC, PARTNER_ASYNC; public static FlowType fromValue(String val) { for (FlowType type : FlowType.values()) { if (type.toString().equals(val)) { return type; } } return null; } } <file_sep>package com.vuclip.premiumengg.automation.ad_network_service.common.models; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.*; import java.util.HashMap; import java.util.List; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"activityFlowId", "productId", "partnerId", "countryCode", "name", "billingCode", "mode", "actions", "operationType"}) @NoArgsConstructor @AllArgsConstructor @Getter @Setter @ToString public class ActivityFlow { @JsonProperty("activityFlowId") private Integer activityFlowId; @JsonProperty("productId") private Integer productId; @JsonProperty("partnerId") private Integer partnerId; @JsonProperty("countryCode") private String countryCode; @JsonProperty("name") private String name; @JsonProperty("billingCode") private String billingCode; @JsonProperty("mode") private String mode; @JsonProperty("actions") private List<Action> actions = null; @JsonProperty("operationType") private String operationType; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); }<file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; @ToString @Builder @Getter @AllArgsConstructor @NoArgsConstructor public class ProductRequestVO { private Integer productId; private String productName; private String productType; private String storeType; private String url; private String context; private long cassId; private boolean encryptionEnable; private int encryptionValidityInMinutes; private String callbackUrl; private String consentCancelUrl; private String errorUrl; private String description; private String status; }<file_sep>package com.vuclip.premiumengg.automation.utils; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Interval; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; /** * Create by Ashish_Chhabra */ public class DateUtils { private DateTimeFormatter formatterGMT; private DateTimeFormatter formatterLocalTime; private DateTimeFormatter formatterWithTimeZone; private DateTimeFormatter formatterDate; private String timeZone; /** * @param localTimeZone */ public DateUtils(String localTimeZone) { this.timeZone = localTimeZone; formatterGMT = DateTimeFormat.forPattern("dd-MM-yyyy HH:mm:ss 'GMT'").withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT"))); formatterLocalTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.s").withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone(timeZone))); formatterWithTimeZone = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.s Z").withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT"))); formatterDate = DateTimeFormat.forPattern("yyyy-MM-dd ").withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone(timeZone))); } /** * @return */ public String getTimeZone() { return timeZone; } /** * @param timeZone */ public void setTimeZone(String timeZone) { this.timeZone = timeZone; } /** * @return */ public String getCurrentGMTTime() { DateTime gmtTime = new DateTime(DateTimeZone.UTC); return formatterGMT.print(gmtTime); } /** * @param timeFormat * @param timeOffsetInHours * @return */ public String getCurrentGMTTime(String timeFormat, int timeOffsetInHours) { DateTimeFormatter df = DateTimeFormat.forPattern(timeFormat); DateTime gmtTime = new DateTime(DateTimeZone.UTC); if (timeOffsetInHours > 0) { gmtTime = gmtTime.plusHours(timeOffsetInHours); } else { gmtTime = gmtTime.minusHours(-timeOffsetInHours); } return df.print(gmtTime); } /** * @param time * @return * @throws ParseException */ public String getGMTTimefromLocal(String time) throws ParseException { String tz = timeZone.replaceAll("GMT", "").replaceAll(":", ""); return formatterWithTimeZone.parseMutableDateTime(time + " " + tz).toString(formatterGMT); } /** * @return * @throws ParseException */ public Map<String, String> getGMTTimeforTpay() throws ParseException { DateTime gmtTime = new DateTime(DateTimeZone.UTC); formatterGMT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT"))); Map<String, String> dateMap = new HashMap<String, String>(); dateMap.put("paymentDate", formatterGMT.print(gmtTime).concat("Z")); dateMap.put("nextPaymentDate", formatterGMT.print(gmtTime.plusDays(1)).concat("Z")); return dateMap; } /** * @return */ public String getCurrentLocalTime() { DateTime localTime = new DateTime(DateTimeZone.forTimeZone(TimeZone.getTimeZone(timeZone))); return formatterLocalTime.print(localTime); } /** * @param period * @param timeUnit * @return * @throws ParseException */ public String addValidityGMT(String period, String timeUnit) throws ParseException { String resultTime = null; DateTime gmtTime = new DateTime(DateTimeZone.UTC); if ("DAY".equalsIgnoreCase(timeUnit)) { resultTime = formatterGMT.print((gmtTime.plusDays(Integer.parseInt(period)))); } else if ("HOUR".equalsIgnoreCase(timeUnit)) { resultTime = formatterGMT.print((gmtTime.plusHours(Integer.parseInt(period)))); } return resultTime; } /** * @param period * @param timeUnit * @return * @throws ParseException */ public String addValidityLocal(String period, String timeUnit) throws ParseException { String resultTime = null; DateTime localTime = new DateTime(DateTimeZone.forTimeZone(TimeZone.getTimeZone(timeZone))); if ("DAY".equalsIgnoreCase(timeUnit)) { resultTime = formatterLocalTime.print((localTime.plusDays(Integer.parseInt(period)))); } else if ("HOUR".equalsIgnoreCase(timeUnit)) { resultTime = formatterLocalTime.print((localTime.plusHours(Integer.parseInt(period)))); } return resultTime; } /** * @param windowInLocal1 * @param windowInLocal2 * @param timeToCheckinLocal * @param type * @return * @throws ParseException */ public String getGMTTimeFromLocalWindow(String windowInLocal1, String windowInLocal2, String timeToCheckinLocal, String type) throws ParseException { String resultTime = null; String time1 = formatterDate.print(new DateTime(DateTimeZone.forTimeZone(TimeZone.getTimeZone(timeZone)))) + windowInLocal1; String time2 = formatterDate.print(new DateTime(DateTimeZone.forTimeZone(TimeZone.getTimeZone(timeZone)))) + windowInLocal2; Interval interval1 = new Interval(formatterLocalTime.parseDateTime(time1), formatterLocalTime.parseDateTime(time2)); boolean interval1ContainsDateTime = interval1.contains(formatterLocalTime.parseDateTime(timeToCheckinLocal)); if (formatterLocalTime.parseDateTime(timeToCheckinLocal).isBefore((formatterLocalTime.parseDateTime(time1)))) { resultTime = time1; } else if (interval1ContainsDateTime) { resultTime = time2; } else if ("success".equalsIgnoreCase(type)) { resultTime = formatterDate.print(formatterLocalTime.parseDateTime(timeToCheckinLocal)) + windowInLocal1; } else { resultTime = formatterDate.print(new DateTime(DateTimeZone.forTimeZone(TimeZone.getTimeZone(timeZone))).plusDays(1)) + windowInLocal1; } return getGMTTimefromLocal(resultTime); } /** * @param windowInLocal1 * @param windowInLocal2 * @param windowInLocal3 * @param timeToCheckinLocal * @param type * @return * @throws ParseException */ public String getGMTTimeFromLocalWindow(String windowInLocal1, String windowInLocal2, String windowInLocal3, String timeToCheckinLocal, String type) throws ParseException { String resultTime = null; String time1 = formatterDate.print(new DateTime(DateTimeZone.forTimeZone(TimeZone.getTimeZone(timeZone)))) + windowInLocal1; String time2 = formatterDate.print(new DateTime(DateTimeZone.forTimeZone(TimeZone.getTimeZone(timeZone)))) + windowInLocal2; String time3 = formatterDate.print(new DateTime(DateTimeZone.forTimeZone(TimeZone.getTimeZone(timeZone)))) + windowInLocal3; Interval interval1 = new Interval(formatterLocalTime.parseDateTime(time1), formatterLocalTime.parseDateTime(time2)); Interval interval2 = new Interval(formatterLocalTime.parseDateTime(time2), formatterLocalTime.parseDateTime(time3)); boolean interval1ContainsDateTime = interval1.contains(formatterLocalTime.parseDateTime(timeToCheckinLocal)); boolean interval2ContainsDateTime = interval2.contains(formatterLocalTime.parseDateTime(timeToCheckinLocal)); if (formatterLocalTime.parseDateTime(timeToCheckinLocal).isBefore((formatterLocalTime.parseDateTime(time1)))) { resultTime = time1; } else if (interval1ContainsDateTime) { resultTime = time2; } else if (interval2ContainsDateTime) { resultTime = time3; } else if ("success".equalsIgnoreCase(type)) { resultTime = formatterDate.print(formatterLocalTime.parseDateTime(timeToCheckinLocal)) + windowInLocal1; } else { resultTime = formatterDate.print(new DateTime(DateTimeZone.forTimeZone(TimeZone.getTimeZone(timeZone))).plusDays(1)) + windowInLocal1; } return getGMTTimefromLocal(resultTime); } /** * @param date1 * @param date2 * @param thresholdInMinutes * @return * @throws ParseException */ public boolean compareDates(String date1, String date2, int thresholdInMinutes) throws ParseException { long diff = Math.abs(formatterGMT.parseDateTime(date1).getMillis() - formatterGMT.parseDateTime(date2).getMillis()); if (diff == 0) { return true; } else if (diff != 0 && (diff / (60 * 1000) % 60) <= thresholdInMinutes) { return true; } else { return false; } } } <file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"blackoutId", "productId", "partnerId", "countryCode", "period", "operationType", "blackoutWindow"}) @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString public class Blackout { @JsonProperty("blackoutId") private Integer blackoutId; @JsonProperty("productId") private Integer productId; @JsonProperty("partnerId") private Integer partnerId; @JsonProperty("countryCode") private String countryCode; @JsonProperty("period") private String period; @JsonProperty("operationType") private String operationType; @JsonProperty("blackoutWindow") private String blackoutWindow; } <file_sep>package com.vuclip.premiumengg.automation.billing_package_service.common.utils; import com.vuclip.premiumengg.automation.billing_package_service.common.models.BPSSaveCountryRequest; import com.vuclip.premiumengg.automation.billing_package_service.common.models.BPSSavePartnerRequest; import com.vuclip.premiumengg.automation.billing_package_service.common.models.BPSSaveProductRequest; import com.vuclip.premiumengg.automation.common.Configuration; import io.restassured.http.ContentType; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; import java.util.Map; import static io.restassured.RestAssured.given; import static io.restassured.RestAssured.with; /** * Created by Kohitij_Das on 20/03/18. */ public class BPSHelper { RequestSpecification requestSpecification; /** * ax Default constructor. Initialises the request template. */ public BPSHelper() { requestSpecification = with().baseUri(Configuration.billingPackageServer); } /** * @return * @throws Exception */ public Response getAllBillingOptions() throws Exception { final Response response = given(requestSpecification).contentType(ContentType.JSON).log().all() .get("/bps/api/getAllBillingOptions"); response.then().assertThat().statusCode(200); response.prettyPrint(); return response; } /** * @param params * @return * @throws Exception */ public Response getBillingOptionWithFilters(Map<String, Object> params) throws Exception { final Response response = given(requestSpecification).contentType(ContentType.JSON).log().all() .queryParams(params).get("/bps/api/getBillingOption"); response.prettyPrint(); return response; } /** * @param billingCode * @return * @throws Exception */ public Response getBillingOptionByBillingCode(String billingCode) throws Exception { final Response response = given(requestSpecification).contentType(ContentType.JSON).log().all() .pathParam("billing_code", billingCode).get("/bps/api/getBillingOptionByBillingCode/{billing_code}"); response.prettyPrint(); return response; } /** * @param jsonBody * @return * @throws Exception */ public Response saveProduct(BPSSaveProductRequest jsonBody) throws Exception { final Response response = given(requestSpecification).contentType(ContentType.JSON).body(jsonBody).log().all() .post("/bps/saveProduct"); response.prettyPrint(); return response; } public Response savePartner(BPSSavePartnerRequest jsonBody) throws Exception { final Response response = given(requestSpecification).contentType(ContentType.JSON).body(jsonBody).log().all() .post("/bps/savePartner"); response.prettyPrint(); return response; } public Response saveCountry(BPSSaveCountryRequest jsonBody) throws Exception { final Response response = given(requestSpecification).contentType(ContentType.JSON).body(jsonBody).log().all() .post("/bps/saveCountry"); response.prettyPrint(); return response; } } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; @Getter @ToString @Builder @AllArgsConstructor @NoArgsConstructor public class ConfigRequestVO { private ProductRequestVO product; private List<ProductPartnerMappingRequestVO> productPartnerMappings; private ProductCountryMappingRequestVO productCountryMapping; private List<SmsConfigRequestVO> smsConfigs; private List<RetryRequestVO> retry; private List<ChurnNotificationRequestVO> churnNotifications; private List<AdNetworkNotificationRequestVO> adNetworkNotifications; private List<PricePointRequestVO> pricePoints; private List<StateConfigRequestVO> stateConfigs; private List<BlackoutRequestVO> blockouts; private List<ActivityFlowRequestVO> activityFlows; }<file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.common.RabbitMQConnection; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.models.SASQueueResponse; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.models.SASTables; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.models.SchedulerRequest; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.models.UserSubscriptionRequest; import com.vuclip.premiumengg.automation.utils.AppAssert; import com.vuclip.premiumengg.automation.utils.DBUtils; import com.vuclip.premiumengg.automation.utils.ObjectMapperUtils; import io.restassured.response.Response; import org.apache.log4j.Logger; import org.springframework.amqp.core.Message; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public class SASValidationHelper { private static Logger logger = Log4J.getLogger("SASValidationHelper"); // private static Integer partnerId; public static void validate_sas_api_response(Response sasApiResponse) { AppAssert.assertEqual(sasApiResponse.statusCode(), 200, "Vefiry that response status code is 200 "); } public static void validate_sas_invalid_api_response(Response sasApiResponse) { AppAssert.assertEqual(sasApiResponse.statusCode(), 500, "Vefiry that response status code is 500 "); } public static void validate_schedular_api_response(Response schedularApiResponse) { AppAssert.assertEqual(schedularApiResponse.statusCode(), 200, "Validate that response status code is 200 "); AppAssert.assertEqual(schedularApiResponse.getBody().asString(), "SUCCESS", "verify scheduler api call"); } public static void validate_schedular_invalid_api_response(Response schedularApiResponse) { AppAssert.assertEqual(schedularApiResponse.statusCode(), 500, "Validate that response status code is 500 "); } public static void validateQueueMessage(SASQueueResponse queueResponse, SchedulerRequest schedulerRequest, UserSubscriptionRequest userSubscriptionRequest, String activityType) { logger.info("verification for RabbitMQ"); AppAssert.assertEqual(queueResponse.getSubscriptionId().toString(), userSubscriptionRequest.getSubscriptionInfo().getSubscriptionId().toString(), "Verify subscription ID"); AppAssert.assertEqual(queueResponse.getCountryCode().toUpperCase(), userSubscriptionRequest.getSubscriptionInfo().getCountry().toUpperCase(), "Verify country"); AppAssert.assertEqual(queueResponse.getPartnerId().toString().toUpperCase(), schedulerRequest.getPartnerId().toString().toUpperCase(), "Verify partner ID"); AppAssert.assertEqual(queueResponse.getProductId().toString().toUpperCase(), schedulerRequest.getPartnerId().toString().toUpperCase(), "Verify product ID"); AppAssert.assertEqual(queueResponse.getActivitType().toString().toUpperCase(), activityType.toUpperCase(), "Verify activity type"); } public static void validateTableRecord(Map<String, Object> actualrecord, Map<String, String> expectedRecord) { for (String key : expectedRecord.keySet()) { AppAssert.assertEqual(actualrecord.get(key).toString().toLowerCase(), expectedRecord.get(key).toLowerCase(), "Verify table fields"); } } public static void validateQueueMessage(SASQueueResponse queueResponse, int productId, int partnerId, int subscriptionId, String countryCode, String actionTable) { logger.info("verification for RabbitMQ"); AppAssert.assertEqual(queueResponse.getProductId().toString().toUpperCase(), String.valueOf(productId).toUpperCase(), "Verify product ID"); AppAssert.assertEqual(queueResponse.getPartnerId().toString().toUpperCase(), String.valueOf(partnerId).toUpperCase(), "Verify partner ID"); AppAssert.assertEqual(queueResponse.getSubscriptionId().toString(), String.valueOf(subscriptionId), "Verify subscription ID"); AppAssert.assertEqual(queueResponse.getCountryCode().toUpperCase(), countryCode.toUpperCase(), "Verify country"); if (actionTable.toUpperCase().equalsIgnoreCase("RENEWAL_RETRY")) AppAssert.assertEqual(queueResponse.getActivitType().toString().toUpperCase(), "RENEWAL", "Verify activity type"); else AppAssert.assertEqual(queueResponse.getActivitType().toString().toUpperCase(), actionTable.toUpperCase(), "Verify activity type"); } public static void verifyNoActivityRecordPresent(int productId, int partnerId, Integer subscriptionId, long date) { List<String> tables = Stream.of(SASTables.values()).map(Enum::name).collect(Collectors.toList()); for (String tableName : tables) { try { AppAssert.assertTrue( DBUtils.getRecord(tableName, " subscription_id =" + String.valueOf(subscriptionId) + " and product_id =" + String.valueOf(productId) + " and partner_id=" + String.valueOf(partnerId) + " and date=" + String.valueOf(date)) .size() == 0, "verify no entry in " + tableName); } catch (SQLException e) { AppAssert.assertTrue(false, "Error occoured while fetching data from DB " + tableName + " error message" + e.getMessage()); } } } public static void negativeFlow(Integer productId, Integer partnerId, String activityType, String currentSubscriptionState, String transactionState, String actionType, int subscriptionId) { UserSubscriptionRequest request = SASUtils.generateUserSubscriptionRequest(productId, partnerId, activityType, "", currentSubscriptionState, transactionState, actionType, subscriptionId); SASHelper sasHelper = new SASHelper(); try { validate_sas_api_response(sasHelper.userSubscription(request)); } catch (Exception e) { AppAssert.assertTrue(false, "error in api call"); } SASValidationHelper.verifyNoActivityRecordPresent(productId, partnerId, subscriptionId, request.getSubscriptionInfo().getNextBillingDate().longValue()); } public static String whereClause(int subscriptionId, int productId, int partnerId, String nextBillingDate, String Status, String countryCode) { return "product_id='" + productId + "' and partner_id='" + partnerId + "' and country_code='" + countryCode + "' and subscription_id='" + subscriptionId + "' and status='" + Status + "';"; } public static void verifyEventTable(String actionTable, int subscriptionId, int productId, int partnerId, long billingDate, String status, String countryCode) { try { AppAssert.assertTrue(DBUtils .getRecord(actionTable, whereClause(subscriptionId, productId, partnerId, "" + billingDate, status, countryCode)) .size() == 1); } catch (SQLException e) { e.printStackTrace(); AppAssert.assertTrue(false, "not able to fetch record from " + actionTable); } } public static void validateQueue(String queue, String activity, Integer productId, Integer partnerId, int subscriptionId, String countryCode) { Message message = RabbitUtil.receive(RabbitMQConnection.getRabbitTemplate(), RabbitUtil.getQueueName(productId, partnerId, countryCode, queue), 10000); validateQueueMessage(ObjectMapperUtils.readValueFromString(new String(message.getBody()), SASQueueResponse.class), productId, partnerId, subscriptionId, countryCode, activity); } } <file_sep>package com.vuclip.premiumengg.automation.utils; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class JsonHelper { /** * @param type * @param jsonObject * @param jsonElement * @return */ public static <T> String remove(Class<T> type, T jsonObject, String jsonElement) { String jObj = new GsonBuilder().create().toJson(jsonObject, type); JsonParser jsonParser = new JsonParser(); JsonObject jo = (JsonObject) jsonParser.parse(jObj); jo.remove(jsonElement); return jo.toString(); } public static <T> String remove(Class<T> type, T jsonObject, String objName, String jsonElement) { String jObj = new GsonBuilder().create().toJson(jsonObject, type); JsonParser jsonParser = new JsonParser(); JsonObject jo = (JsonObject) jsonParser.parse(jObj); // jo.remove(jsonElement); jo.getAsJsonObject(objName).remove(jsonElement); return jo.toString(); } } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; public enum ConfigTables { action, activity_flow, ad_network_notification, blackout, churn_notification, criterion, price_point, product, product_country, product_partner, retry, state_config } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; @Getter @EqualsAndHashCode @ToString @NoArgsConstructor @Builder @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_EMPTY) public class ActionVO { private int actionId; private ActionType action; private FlowType flowType; } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.tests; import static org.hamcrest.CoreMatchers.is; import java.util.Map; import org.apache.log4j.Logger; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.configuration_service.common.models.AdNetworkRequestVO; import com.vuclip.premiumengg.automation.configuration_service.common.models.AdNetworkResponseVO; import com.vuclip.premiumengg.automation.configuration_service.common.utils.AdNetworkHelper; import com.vuclip.premiumengg.automation.configuration_service.common.utils.AdNetworkUtil; import com.vuclip.premiumengg.automation.configuration_service.common.utils.AdNetworkValidationHelper; import com.vuclip.premiumengg.automation.configuration_service.common.utils.CSDBHelper; import com.vuclip.premiumengg.automation.configuration_service.common.utils.CSUtils; import com.vuclip.premiumengg.automation.configuration_service.common.utils.CSValidationHelper; import com.vuclip.premiumengg.automation.utils.DBUtils; import io.restassured.response.Response; public class SaveAdNetworkTest { private static Logger logger = Log4J.getLogger("SaveCountryTest"); private static AdNetworkRequestVO request; private static AdNetworkResponseVO expectedResponse; public static String adNetworkName = "Ad Network 1"; private static int adNetworkId; @BeforeClass(alwaysRun = true) public void clean() { logger.info("cleaning record for AdNetwork"); int updateCount = DBUtils.cleanTable("ad_network", "name = " + CSDBHelper.dbReadableFormat(adNetworkName)); logger.info("cleaned" + updateCount + " record"); } @Test(groups = { "positive" }) public void saveAdNetworkTests() throws Exception { logger.info("Starting ======> Verify ad network saved in Database"); try { request = AdNetworkUtil.createMockRequestVO(adNetworkName, 1, "voluum_tid", "notification url", "GET", "ALL", "active", "churn notification url", "dummy"); expectedResponse = AdNetworkUtil.getMockAdNetworkResponseVO(request, "Create", true, 200, CSUtils.uBSMockURL + " : Successful\n"); logger.info(expectedResponse.toString()); Response response = AdNetworkHelper.saveAdNetwork(request); CSValidationHelper.validate_cs_api_response(response); logger.info("Validate Resposne Body"); AdNetworkResponseVO adNetworkResponseVO = response.as(AdNetworkResponseVO.class); logger.info(adNetworkResponseVO.toString()); adNetworkId = adNetworkResponseVO.getAdNetwork().getAdNetworkId(); AdNetworkValidationHelper.validateResponse(adNetworkResponseVO, expectedResponse); logger.info("Validate Database"); Map<String, Object> dbRecord = DBUtils .getRecord("ad_network", "name = " + CSDBHelper.dbReadableFormat(adNetworkName)).get(0); AdNetworkValidationHelper.validateTableRecord(dbRecord, expectedResponse); } catch (Exception e) { e.printStackTrace(); } } @Test(groups = { "positive" }, dependsOnMethods = { "saveAdNetworkTests" }, priority = 2) public void updatePartnerTestInDatabase() throws Exception { logger.info("Starting ======> Verify AD Network updated in Database"); try { // PartnerDBHelper.insertRecordIntoPartner("Etisalat USA", 110); request = AdNetworkUtil.createMockRequestVO(adNetworkName, 1, "voluum_tid", "notification url", "GET", "ALL", "active", "churn notification url", "dummy"); expectedResponse = AdNetworkUtil.getMockAdNetworkResponseVO(request, "Update", true, 200, CSUtils.uBSMockURL + " : Successful\n"); logger.info(expectedResponse.toString()); Response response = AdNetworkHelper.updateAdNetwork(request); CSValidationHelper.validate_cs_api_response(response); AdNetworkResponseVO actualResponseVO = response.getBody().as(AdNetworkResponseVO.class); logger.info(actualResponseVO.toString()); logger.info("Response Validation"); AdNetworkValidationHelper.validateResponse(actualResponseVO, expectedResponse); logger.info("Validate Database"); Map<String, Object> dbRecord = DBUtils .getRecord("ad_network", "name = " + CSDBHelper.dbReadableFormat(adNetworkName)).get(0); AdNetworkValidationHelper.validateTableRecord(dbRecord, expectedResponse); } catch (Exception e) { e.printStackTrace(); } } @Test(groups = { "positive" }, dependsOnMethods = { "saveAdNetworkTests" }, priority = 3) public void getPartnerByName() throws Exception { logger.info("Starting ======> Verify Get AD Network By Name"); try { // PartnerDBHelper.insertRecordIntoPartner("get partner by name", 111); expectedResponse = AdNetworkUtil.getMockAdNetworkResponseVO(request, "Update", true, 200, "Success"); logger.info(expectedResponse.toString()); Response response = AdNetworkHelper.getAdNetworkByName(adNetworkName); CSValidationHelper.validate_cs_api_response(response); AdNetworkResponseVO actualResponseVO = response.getBody().as(AdNetworkResponseVO.class); logger.info(actualResponseVO.toString()); logger.info("Response Validation"); AdNetworkValidationHelper.validateResponse(actualResponseVO, expectedResponse); } catch (Exception e) { e.printStackTrace(); } } @Test(groups = { "positive" }, dependsOnMethods = { "saveAdNetworkTests" }) public void getPartnerById() throws Exception { logger.info("Starting ======> Verify Get Ad Network By ID"); try { // PartnerDBHelper.insertRecordIntoPartner("get partner by id", 112); expectedResponse = AdNetworkUtil.getMockAdNetworkResponseVO(request, "Update", true, 200, "Success"); logger.info(expectedResponse.toString()); Response response = AdNetworkHelper.getAdNetworkById(adNetworkId); CSValidationHelper.validate_cs_api_response(response); AdNetworkResponseVO actualResponseVO = response.getBody().as(AdNetworkResponseVO.class); logger.info(actualResponseVO.toString()); logger.info("Response Validation"); AdNetworkValidationHelper.validateResponse(actualResponseVO, expectedResponse); } catch (Exception e) { e.printStackTrace(); } } @Test(groups = { "positive" }, dependsOnMethods = { "saveAdNetworkTests" }, priority = 5) public void getAllPartner() throws Exception { logger.info("Starting ======> Verify Get All AD Network"); try { // PartnerDBHelper.insertRecordIntoPartner("get all", 113); Response response = AdNetworkHelper.getAllAdNetwork(); CSValidationHelper.validate_cs_api_response(response); logger.info("Verif size of partner in database and response"); int sizeOfAdNetworkInDB = CSDBHelper.getNumberOfRecordsInTable("ad_network", null); response.then().assertThat().body("size()", is(sizeOfAdNetworkInDB)); } catch (Exception e) { e.printStackTrace(); } } @Test(groups = { "positive" }, dependsOnMethods = { "saveAdNetworkTests" }, priority = 6) public void deleteAdNetworkByName() throws Exception { logger.info("Starting ======> Verify Delete AdNetwork By Name"); try { // AdNetworkDBHelper.insertRecordIntoAdNetwork("delete AdNetwork", 114); expectedResponse = AdNetworkUtil.getMockAdNetworkResponseVO(request, "Delete", true, 200, CSUtils.uBSMockURL + " : Successful\n"); logger.info(expectedResponse.toString()); Response response = AdNetworkHelper.deleteAdNetworkByName(adNetworkName); CSValidationHelper.validate_cs_api_response(response); CSDBHelper.verifyNoActivityRecordPresent("ad_network", "name = " + CSDBHelper.dbReadableFormat(adNetworkName)); AdNetworkResponseVO actualResponseVO = response.getBody().as(AdNetworkResponseVO.class); logger.info(actualResponseVO.toString()); logger.info("Response Validation"); AdNetworkValidationHelper.validateResponse(actualResponseVO, expectedResponse); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.*; import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"criteriaId", "smsText", "criterions", "dateCoumputationCriterion"}) @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString public class Criteria { @JsonProperty("criteriaId") private Integer criteriaId; @JsonProperty("smsText") private String smsText; @JsonProperty("criterions") private List<Criterion> criterions = null; @JsonProperty("dateCoumputationCriterion") private DateCoumputationCriterion dateCoumputationCriterion; } <file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"churnNotificationId", "typeOfChurn", "period", "productId", "partnerId", "countryCode", "operationType"}) @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString public class ChurnNotification { @JsonProperty("churnNotificationId") private Integer churnNotificationId; @JsonProperty("typeOfChurn") private String typeOfChurn; @JsonProperty("period") private String period; @JsonProperty("productId") private Integer productId; @JsonProperty("partnerId") private Integer partnerId; @JsonProperty("countryCode") private String countryCode; @JsonProperty("operationType") private String operationType; } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; @Getter @EqualsAndHashCode @ToString @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_EMPTY) public class CriterionResponseVO { private int criterionId; private String name; private String operator; private String value; private String groupingOperator; } <file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.tests; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.models.SchedulerRequest; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils.SASHelper; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils.SASUtils; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils.SASValidationHelper; import com.vuclip.premiumengg.automation.utils.JsonHelper; import org.apache.commons.lang3.RandomUtils; import org.apache.log4j.Logger; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class SchedulerAPINegativeTests { private static Logger logger = Log4J.getLogger("SchedulerAPINegativeTests"); int productId; int partnerId; String activityType = "WINBACK"; String previousSubscriptionState = "PARKING"; String currentSubscriptionState = "ACTIVATED"; String transactionState = "SUCCESS"; String actionType = "CHARGING"; Integer subscriptionId; String actionTable = "RENEWAL"; private SASHelper sasHelper; private String countryCode = "IN"; @BeforeClass(alwaysRun = true) public void setup() throws Exception { sasHelper = new SASHelper(); productId = RandomUtils.nextInt(77000, 77900); partnerId = productId; } @DataProvider(name = "schedulerApiInvalidFieldValuesDataProvider") public Object[][] schedulerApiInvalidFieldValuesDataProvider() { return new Object[][]{ {0, 0, null, null}, {partnerId, productId, countryCode, null}, /*bug{ 0, 0, countryCode,"RENEWAL" }, bug{ productId, 0, countryCode,"RENEWAL" }, bug { 0, partnerId, countryCode,"RENEWAL" }, bug { partnerId, productId, null,"RENEWAL" },*/ }; } @Test(dataProvider = "schedulerApiInvalidFieldValuesDataProvider", groups = {"positive"}) public void schedulerApiInvalidFieldValuesTest(Integer sproductId, Integer spartnerId, String scountryCode, String sactivityType) throws Exception { subscriptionId = RandomUtils.nextInt(100, 200); String testMessage = subscriptionId + " " + activityType + " " + previousSubscriptionState + " " + currentSubscriptionState + " " + transactionState + " " + actionType; logger.info("==================>Starting scheduler api invalid fields values test [ " + testMessage + " ]"); try { SASValidationHelper.validate_sas_api_response( sasHelper.userSubscription(SASUtils.generateUserSubscriptionRequest(productId, partnerId, activityType, previousSubscriptionState, currentSubscriptionState, transactionState, actionType, subscriptionId))); SchedulerRequest generateSchedulerRequest = SASUtils.generateSchedulerRequest(sproductId, spartnerId, actionTable); generateSchedulerRequest.setCountry(scountryCode); generateSchedulerRequest.setActivityType(sactivityType); SASValidationHelper.validate_schedular_invalid_api_response(sasHelper.scheduler(generateSchedulerRequest)); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } } @DataProvider(name = "schedulerApiMissingFieldsDataProvider") public Object[][] schedulerApiMissingFieldsDataProvider() { return new Object[][]{ /*bug{ "productId" }, bug{ "partnerId" }, bug{ "country" }*/ {"activityType"} }; } @Test(dataProvider = "schedulerApiMissingFieldsDataProvider", groups = {"positive"}) public void schedulerApiMissingFieldsValidation(String jsonElement) throws Exception { subscriptionId = RandomUtils.nextInt(100, 200); String testMessage = subscriptionId + " " + activityType + " " + previousSubscriptionState + " " + currentSubscriptionState + " " + transactionState + " " + actionType; logger.info("==================>Starting scheduler api missing fields test [ " + testMessage + " ]"); try { SASValidationHelper.validate_sas_api_response( sasHelper.userSubscription(SASUtils.generateUserSubscriptionRequest(productId, partnerId, activityType, previousSubscriptionState, currentSubscriptionState, transactionState, actionType, subscriptionId))); SchedulerRequest generateSchedulerRequest = SASUtils.generateSchedulerRequest(productId, partnerId, actionTable); String jsonString = JsonHelper.remove(SchedulerRequest.class, generateSchedulerRequest, jsonElement); System.out.println(jsonString); /*generateSchedulerRequest = ObjectMapperUtils.readValueFromString(jsonString, SchedulerRequest.class); System.out.println(generateSchedulerRequest.toString());*/ SASValidationHelper.validate_schedular_invalid_api_response(sasHelper.scheduler(jsonString)); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } } } <file_sep>package com.vuclip.premiumengg.automation.billing_package_service.tests; import com.vuclip.premiumengg.automation.billing_package_service.common.models.BillingPackage; import com.vuclip.premiumengg.automation.billing_package_service.common.models.BillingResponse; import com.vuclip.premiumengg.automation.billing_package_service.common.utils.BPSContext; import com.vuclip.premiumengg.automation.billing_package_service.common.utils.BPSHelper; import com.vuclip.premiumengg.automation.billing_package_service.common.utils.BPSValidationHelper; import com.vuclip.premiumengg.automation.common.Log4J; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Created by Kohitij_Das on 22/03/18. */ public class GetBillingOptionByBillingCode { private BPSHelper bpsHelper; private BPSValidationHelper validationHelper; @BeforeClass(alwaysRun = true) public void setup() throws Exception { bpsHelper = new BPSHelper(); validationHelper = new BPSValidationHelper(); } @Test public void verify_get_billing_options_with_valid_billingCode() throws Exception { Log4J.getLogger() .info("===================================>TEST: verify_get_billing_options_with_valid_billingCode"); final String validBillingCode = BPSContext.saveProductRequest.getPricePoints().get(0).getBillingCode(); validationHelper.validate_billing_packages(bpsHelper.getBillingOptionByBillingCode(validBillingCode), BillingPackage.PACKAGE1, "billingPackages"); } @Test public void verify_get_billing_options_with_invalid_billingCode() throws Exception { Log4J.getLogger() .info("===================================>TEST: verify_get_billing_options_with_invalid_billingCode"); final String invalidBillingCode = "999999"; validationHelper.validate_billing_response(bpsHelper.getBillingOptionByBillingCode(invalidBillingCode), BillingResponse.NOTFOUND); } } <file_sep> package com.vuclip.premiumengg.automation.configuration_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "partnerId", "partnerName", "description", "status", "autoRenewalApplicable", "type", "stepUpCharging", "userIdentifier", "balanceCheckRequired", "activationManagedBy", "renewalManagedBy", "deactivationManagedBy", "hasMoActivations", "hasMoDeactivations", "operationType", "partnerActivationConsentParserUrl", "partnerDeactivationConsentParserUrl", "partnerActivationConsentInitiationUrl", "partnerDeactivationConsentInitiationUrl" }) @Getter @Setter @AllArgsConstructor @NoArgsConstructor @ToString public class PartnerVO { @JsonProperty("partnerId") private Integer partnerId; @JsonProperty("partnerName") private String partnerName; @JsonProperty("description") private String description; @JsonProperty("status") private String status; @JsonProperty("autoRenewalApplicable") private Boolean autoRenewalApplicable; @JsonProperty("type") private String type; @JsonProperty("stepUpCharging") private Boolean stepUpCharging; @JsonProperty("userIdentifier") private String userIdentifier; @JsonProperty("balanceCheckRequired") private Boolean balanceCheckRequired; @JsonProperty("activationManagedBy") private String activationManagedBy; @JsonProperty("renewalManagedBy") private String renewalManagedBy; @JsonProperty("deactivationManagedBy") private String deactivationManagedBy; @JsonProperty("hasMoActivations") private Boolean hasMoActivations; @JsonProperty("hasMoDeactivations") private Boolean hasMoDeactivations; @JsonProperty("operationType") private String operationType; @JsonProperty("partnerActivationConsentParserUrl") private String partnerActivationConsentParserUrl; @JsonProperty("partnerDeactivationConsentParserUrl") private String partnerDeactivationConsentParserUrl; @JsonProperty("partnerActivationConsentInitiationUrl") private String partnerActivationConsentInitiationUrl; @JsonProperty("partnerDeactivationConsentInitiationUrl") private String partnerDeactivationConsentInitiationUrl; // // public PartnerVO() { // // } // // public PartnerVO(Integer partnerId, String partnerName, String description, String status, // Boolean autoRenewalApplicable, String type, Boolean stepUpCharging, String userIdentifier, // Boolean balanceCheckRequired, String activationManagedBy, String renewalManagedBy, // String deactivationManagedBy, Boolean hasMoActivations, Boolean hasMoDeactivations, String operationType, // String partnerActivationConsentParserUrl, String partnerDeactivationConsentParserUrl, // String partnerActivationConsentInitiationUrl, String partnerDeactivationConsentInitiationUrl) { // super(); // this.partnerId = partnerId; // this.partnerName = partnerName; // this.description = description; // this.status = status; // this.autoRenewalApplicable = autoRenewalApplicable; // this.type = type; // this.stepUpCharging = stepUpCharging; // this.userIdentifier = userIdentifier; // this.balanceCheckRequired = balanceCheckRequired; // this.activationManagedBy = activationManagedBy; // this.renewalManagedBy = renewalManagedBy; // this.deactivationManagedBy = deactivationManagedBy; // this.hasMoActivations = hasMoActivations; // this.hasMoDeactivations = hasMoDeactivations; // this.operationType = operationType; // this.partnerActivationConsentParserUrl = partnerActivationConsentParserUrl; // this.partnerDeactivationConsentParserUrl = partnerDeactivationConsentParserUrl; // this.partnerActivationConsentInitiationUrl = partnerActivationConsentInitiationUrl; // this.partnerDeactivationConsentInitiationUrl = partnerDeactivationConsentInitiationUrl; // } // // } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @EqualsAndHashCode(exclude= {"operationType"}) @ToString @Builder @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_EMPTY) public class Country { private String countryCode; private String operationType; } <file_sep>package com.vuclip.premiumengg.automation.ad_network_service.common.utils; import com.vuclip.premiumengg.automation.ad_network_service.common.models.Message; import com.vuclip.premiumengg.automation.ad_network_service.common.models.SaveAdnetwork; import com.vuclip.premiumengg.automation.ad_network_service.common.models.SaveCountry; import com.vuclip.premiumengg.automation.ad_network_service.common.models.SaveProduct; import com.vuclip.premiumengg.automation.utils.ObjectMapperUtils; import java.math.BigInteger; public class ANSUtils { /** * @param JsonFileName * @param type * @return */ public static <T> T loadJson(String JsonFileName, Class<T> type) { return ObjectMapperUtils .readValue("src/test/resources/configurations/ad-network-service/request/" + JsonFileName, type); } public static SaveProduct generateSaveProductConfig(Integer productId, String productName, Integer partnerId, Integer adNetworkId, String billingCode, String countryCode, Integer paidPercentage, Integer freePercentage, Integer winbackPercentage, Boolean freeTrialApplicable, Integer parkingPeriod) { SaveProduct saveProductRequest = loadJson("saveProduct.json", SaveProduct.class); saveProductRequest.getProduct().setProductId(productId); saveProductRequest.getProduct().setProductName(productName); saveProductRequest.getProductPartnerMappings().get(0).setProductId(productId); saveProductRequest.getProductPartnerMappings().get(0).setPartnerId(partnerId); saveProductRequest.getProductCountryMapping().setProductId(productId); saveProductRequest.getProductCountryMapping().getCountries().get(0).setCountryCode(countryCode); saveProductRequest.getSmsConfigs().get(0).setPartnerId(partnerId); saveProductRequest.getSmsConfigs().get(0).setProductId(productId); saveProductRequest.getSmsConfigs().get(0).setCountryCode(countryCode); saveProductRequest.getRetry().get(0).setPartnerId(partnerId); saveProductRequest.getRetry().get(0).setProductId(productId); saveProductRequest.getRetry().get(0).setCountryCode(countryCode); saveProductRequest.getChurnNotifications().get(0).setProductId(productId); saveProductRequest.getChurnNotifications().get(0).setPartnerId(partnerId); saveProductRequest.getChurnNotifications().get(0).setCountryCode(countryCode); saveProductRequest.getAdNetworkNotifications().get(0).setProductId(productId); saveProductRequest.getAdNetworkNotifications().get(0).setPartnerId(partnerId); saveProductRequest.getAdNetworkNotifications().get(0).setCountryCode(countryCode); saveProductRequest.getAdNetworkNotifications().get(0).setAdNetworkNotificationId(adNetworkId); saveProductRequest.getAdNetworkNotifications().get(0).setPaidPercentage(paidPercentage); saveProductRequest.getAdNetworkNotifications().get(0).setFreePercentage(freePercentage); saveProductRequest.getAdNetworkNotifications().get(0).setWinbackPercentage(winbackPercentage); saveProductRequest.getAdNetworkNotifications().get(1).setProductId(productId); saveProductRequest.getAdNetworkNotifications().get(1).setPartnerId(partnerId); saveProductRequest.getAdNetworkNotifications().get(1).setCountryCode(countryCode); saveProductRequest.getAdNetworkNotifications().get(1).setWinbackPercentage(winbackPercentage); saveProductRequest.getAdNetworkNotifications().get(1).setPaidPercentage(paidPercentage); saveProductRequest.getAdNetworkNotifications().get(1).setFreePercentage(freePercentage); saveProductRequest.getPricePoints().get(0).setProductId(productId); saveProductRequest.getPricePoints().get(0).setPartnerId(partnerId); saveProductRequest.getPricePoints().get(0).setBillingCode(billingCode); saveProductRequest.getPricePoints().get(0).setFallbackPpBillingCode(billingCode); saveProductRequest.getPricePoints().get(0).setFreeTrialBillingCode(billingCode); saveProductRequest.getPricePoints().get(0).setFreeTrialApplicable(freeTrialApplicable); saveProductRequest.getPricePoints().get(0).setParkingPeriod(parkingPeriod); saveProductRequest.getPricePoints().get(0).setCountryCode(countryCode); saveProductRequest.getStateConfigs().get(0).setProductId(productId); saveProductRequest.getStateConfigs().get(0).setPartnerId(partnerId); saveProductRequest.getStateConfigs().get(0).setCountryCode(countryCode); saveProductRequest.getBlackouts().get(0).setPartnerId(partnerId); saveProductRequest.getBlackouts().get(0).setProductId(productId); saveProductRequest.getBlackouts().get(0).setCountryCode(countryCode); saveProductRequest.getActivityFlows().get(0).setProductId(productId); saveProductRequest.getActivityFlows().get(0).setPartnerId(partnerId); saveProductRequest.getActivityFlows().get(0).setBillingCode(billingCode); saveProductRequest.getActivityFlows().get(0).setCountryCode(countryCode); return saveProductRequest; } public static SaveCountry generateSaveCountryrRequest(String countryCode, String timezone) { SaveCountry saveCountryRequest = loadJson("saveCountry.json", SaveCountry.class); saveCountryRequest.setCountryCode(countryCode); saveCountryRequest.setTimezone(timezone); saveCountryRequest.setCountryName(countryCode); return saveCountryRequest; } public static SaveAdnetwork generateSaveAdnetworkRequest(Integer adNetworkId, String requestParamName, String sourceIdentifer) { SaveAdnetwork saveAdNetworkRequest = loadJson("saveAdNetwork.json", SaveAdnetwork.class); saveAdNetworkRequest.setAdNetworkId(adNetworkId); saveAdNetworkRequest.setRequestParamName(requestParamName); saveAdNetworkRequest.setSourceIdentifier(sourceIdentifer); saveAdNetworkRequest.setChurnNotificationUrl(ANSTestContext.churnNotificationUrl.replace("XXX", requestParamName)); saveAdNetworkRequest .setNotificationUrl(ANSTestContext.notificationUrl.replace("XXX", requestParamName)); return saveAdNetworkRequest; } /*public static SaveProduct saveProduct(Integer productId, String productName, Integer partnerId, Integer adNetworkId, String billingCode, String countryCode, Integer paidPercentage, Integer freePercentage, Integer winbackPercentage, Boolean freeTrialApplicable, Integer parkingPeriod) throws Exception { SaveProduct saveProductRequest = ANSUtils.generateSaveProductConfig(productId, productName, partnerId, adNetworkId, billingCode, countryCode, paidPercentage, freePercentage, winbackPercentage, freeTrialApplicable, parkingPeriod); return saveProductRequest; }*/ public static SaveProduct generateSaveProductConfig(Integer productId, String productName, Integer partnerId, Integer adNetworkId, String billingCode) throws Exception { return generateSaveProductConfig(productId, productName, partnerId, adNetworkId, billingCode, ANSTestContext.countryCode, ANSTestContext.paidPercentage, ANSTestContext.freePercentage, ANSTestContext.winbackPercentage, ANSTestContext.freeTrialApplicable, ANSTestContext.parkingPeriod); } public static Message generateMessageForQueue(Integer productId, String userId, String billingCode, String billingPrice, String action, String activity, String transactionState, String actionResult, long subscriptionId, String eventType, BigInteger nextBillingDate, String adNetworkParams, Object churnNotificationParam, String transactionId, Object userSource) throws Exception { Message message = new Message(); message.setEventType(eventType); message.setProductId(productId); message.setProductName(String.valueOf(productId)); message.setPartnerId(productId); message.setPartnerName(String.valueOf(productId)); message.setUserId(userId); message.setMsisdn(userId); message.setAttemptedBillingCode(billingCode); message.setAttemptedPrice(billingPrice); message.setChargedBillingCode(billingCode); message.setChargedPrice(billingPrice); message.setRequestedBillingCode(billingCode); message.setRequestedPrice(billingPrice); message.setAction(action); message.setActivity(activity); message.setTransactionState(transactionState); message.setActionResult(actionResult); message.setSubscriptionId(subscriptionId); message.setNextBillingDate(nextBillingDate); message.setAdNetworkParams(adNetworkParams); message.setChurnNotificationParam(churnNotificationParam); message.setUserSource(userSource); message.setMode("WAP"); message.setDelayed(false); message.setClosed(true); message.setCustomerTransactionId(transactionId); message.setTransactionId(transactionId); System.out.println(ObjectMapperUtils.writeValueAsString(message)); return message; } } <file_sep>package com.vuclip.premiumengg.automation.ad_network_service.common.models; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.*; import java.util.HashMap; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"productId", "partnerId", "chargingDependOnSmsDelivery", "optOutSmsEnabled", "preRenewalSmsEnabled", "partnerConsentParserEndpoint", "partnerConsentUrlGenerationEndpoint", "dateFormat", "operationType", "blacklistApplicable", "validityFromPartner", "blacklistValidity", "cooldownApplicable", "cooldownValidity", "timeUnit", "stepUpChargingApplicable", "allowedFreeTrialCount"}) @Getter @Setter @ToString @EqualsAndHashCode @AllArgsConstructor @NoArgsConstructor public class ProductPartnerMapping { @JsonProperty("productId") private Integer productId; @JsonProperty("partnerId") private Integer partnerId; @JsonProperty("chargingDependOnSmsDelivery") private Boolean chargingDependOnSmsDelivery; @JsonProperty("optOutSmsEnabled") private Boolean optOutSmsEnabled; @JsonProperty("preRenewalSmsEnabled") private Boolean preRenewalSmsEnabled; @JsonProperty("partnerConsentParserEndpoint") private String partnerConsentParserEndpoint; @JsonProperty("partnerConsentUrlGenerationEndpoint") private String partnerConsentUrlGenerationEndpoint; @JsonProperty("dateFormat") private String dateFormat; @JsonProperty("operationType") private String operationType; @JsonProperty("blacklistApplicable") private Boolean blacklistApplicable; @JsonProperty("validityFromPartner") private Boolean validityFromPartner; @JsonProperty("blacklistValidity") private Integer blacklistValidity; @JsonProperty("cooldownApplicable") private Boolean cooldownApplicable; @JsonProperty("cooldownValidity") private Integer cooldownValidity; @JsonProperty("timeUnit") private String timeUnit; @JsonProperty("stepUpChargingApplicable") private Boolean stepUpChargingApplicable; @JsonProperty("allowedFreeTrialCount") private Integer allowedFreeTrialCount; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); }<file_sep>package com.vuclip.premiumengg.automation.subscription_service.common.base; import java.io.File; import java.io.FileInputStream; import java.util.Properties; import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; import com.vuclip.premiumengg.automation.common.Configuration; import com.vuclip.premiumengg.automation.common.JDBCTemplate; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.common.RabbitAdminConnection; import com.vuclip.premiumengg.automation.common.RabbitMQConnection; import com.vuclip.premiumengg.automation.common.RedisTemplateConnection; import com.vuclip.premiumengg.automation.subscription_service.common.models.SaveProductRequest; import com.vuclip.premiumengg.automation.subscription_service.common.utils.SDBHelper; import com.vuclip.premiumengg.automation.subscription_service.common.utils.SHelper; import com.vuclip.premiumengg.automation.subscription_service.common.utils.SUtils; import com.vuclip.premiumengg.automation.subscription_service.common.utils.SValidationHelper; import com.vuclip.premiumengg.automation.utils.ObjectMapperUtils; /** * @author <NAME> */ @Test public class InitializeTestSuite { /** * Method to be invoked before launch of any Suite execution. */ @BeforeSuite(alwaysRun = true) public final void init() { Log4J.getLogger().info("====== SettingUp subscription-service-tests execution ======"); FileInputStream inputStream = null; Properties properties = new Properties(); try { String filePath = System.getProperty("propertiesFile"); File configFile = new File(filePath); inputStream = new FileInputStream(configFile); properties.load(inputStream); Configuration.ssServer = properties.getProperty("ssServer"); Configuration.dbServer = properties.getProperty("dbServer"); Configuration.dbPort = properties.getProperty("dbPort"); Configuration.dbName = properties.getProperty("dbName"); Configuration.dbUser = properties.getProperty("dbUser"); Configuration.dbPassword = properties.getProperty("dbPassword"); Configuration.rabbitMQServer = properties.getProperty("rabbitMQServer"); Configuration.rabbitMQPort = properties.getProperty("rabbitMQPort"); Configuration.rabbitMQUser = properties.getProperty("rabbitMQUser"); Configuration.rabbitMQPassword = properties.getProperty("rabbitMQPassword"); RabbitMQConnection.getRabbitTemplate().setMessageConverter(new Jackson2JsonMessageConverter()); Configuration.redisServers = properties.getProperty("ss.redis.clusters"); RedisTemplateConnection.getRedisConnection().getConnectionFactory().getConnection().flushAll(); SDBHelper.cleanAllTables(null); SUtils.productId = 8181; SUtils.productConfig = SUtils.loadJson("saveProduct.json", SaveProductRequest.class); String jsonString = ObjectMapperUtils.writeValueAsString(SUtils.productConfig); jsonString = jsonString.replaceAll("1111", String.valueOf(SUtils.productId)); SUtils.productConfig = ObjectMapperUtils.readValueFromString(jsonString, SaveProductRequest.class); new SHelper(); SValidationHelper.validate_ss_api_response(SHelper.saveProduct(SUtils.productConfig)); } catch (Exception e) { e.printStackTrace(); } } @AfterSuite(alwaysRun = true) public void teardown() throws Exception { JDBCTemplate.closeAllConnections(); RabbitMQConnection.closeAllConnection(); RabbitAdminConnection.closeAllConnection(); } }<file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.utils; import static io.restassured.RestAssured.given; import static io.restassured.RestAssured.with; import org.apache.log4j.Logger; import com.vuclip.premiumengg.automation.common.Configuration; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.configuration_service.common.models.AdNetworkRequestVO; import io.restassured.http.ContentType; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; /** * @author mayank.bharshiv */ public class AdNetworkHelper { private static Logger logger = Log4J.getLogger("CountryHelper"); static RequestSpecification requestSpecification; /** * Default constructor. Initializes the request template. */ public static RequestSpecification getRequestSpecification() { if (requestSpecification == null) { requestSpecification = with().baseUri(Configuration.csServer); } return requestSpecification; } public static Response saveAdNetwork(AdNetworkRequestVO adNetworkRequestVO) throws Exception { logger.info("Save AdNetwork APi Called"); final Response response = given(getRequestSpecification()).contentType(ContentType.JSON) .body(adNetworkRequestVO).log().all().post("/adNetwork"); response.prettyPrint(); return response; } public static Response updateAdNetwork(AdNetworkRequestVO saveAdNetwork) throws Exception { logger.info("Update AdNetwork Api Called"); final Response response = given(getRequestSpecification()).contentType(ContentType.JSON).body(saveAdNetwork) .log().all().put("/adNetwork"); response.prettyPrint(); return response; } public static Response getAdNetworkByName(String AdNetworkName) throws Exception { logger.info("Get AdNetwork By Name Api Called"); final Response response = given(getRequestSpecification()).pathParam("adNetworkName", AdNetworkName) .contentType(ContentType.JSON).log().all().get("/adNetwork/{adNetworkName}"); response.prettyPrint(); return response; } public static Response getAdNetworkById(int AdNetworkId) throws Exception { logger.info("Get AdNetwork By ID Api Called"); final Response response = given(getRequestSpecification()).queryParam("adNetworkId", AdNetworkId) .contentType(ContentType.JSON).log().all().get("/adNetwork"); response.prettyPrint(); return response; } public static Response getAllAdNetwork() throws Exception { logger.info("Get ALL AdNetworks Api Called"); final Response response = given(getRequestSpecification()).contentType(ContentType.JSON).log().all() .get("/adNetwork/adNetworks"); response.prettyPrint(); return response; } public static Response deleteAdNetworkByName(String AdNetworkName) throws Exception { logger.info("Delete AdNetwork By Name Api Called"); final Response response = given(getRequestSpecification()).queryParam("adNetworkName", AdNetworkName) .contentType(ContentType.JSON).log().all().delete("/adNetwork"); response.prettyPrint(); return response; } } <file_sep>package com.vuclip.premiumengg.automation.billing_package_service.tests; import com.vuclip.premiumengg.automation.billing_package_service.common.models.BillingPackage; import com.vuclip.premiumengg.automation.billing_package_service.common.models.BillingResponse; import com.vuclip.premiumengg.automation.billing_package_service.common.utils.BPSHelper; import com.vuclip.premiumengg.automation.billing_package_service.common.utils.BPSValidationHelper; import com.vuclip.premiumengg.automation.common.Log4J; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Created by Kohitij_Das on 20/03/18. */ public class GetAllBillingOptions { private BPSHelper bpsHelper; private BPSValidationHelper validationHelper; @BeforeClass(alwaysRun = true) public void setup() throws Exception { bpsHelper = new BPSHelper(); validationHelper = new BPSValidationHelper(); } @Test public void verify_get_all_billing_options_success_response() throws Exception { Log4J.getLogger() .info("===================================>TEST: verify_get_all_billing_options_success_response"); validationHelper.validate_billing_response(bpsHelper.getAllBillingOptions(), BillingResponse.SUCCESS); } @Test public void verify_get_all_billing_options_billingPackages() throws Exception { Log4J.getLogger() .info("===================================>TEST: verify_get_all_billing_options_billingPackages"); validationHelper.validate_billing_packages(bpsHelper.getAllBillingOptions(), BillingPackage.PACKAGE1, "billingPackages"); } } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; public enum Mode { WAP, SMS, ANDROID_APP, IOS_APP, CC_TOOL, BACKEND; public static Mode fromValue(String val) { for (Mode type : Mode.values()) { if (type.toString().equals(val)) { return type; } } return null; } } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @EqualsAndHashCode(exclude= {"operationType"}) @ToString @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_EMPTY) public class ChurnNotificationVO { private int churnNotificationId; private TypeOfChurn typeOfChurn; private String period; private String productName; private String partnerName; private String countryName; private String operationType; }<file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"productId", "partnerId", "countryCode", "activityType", "subscriptionId", "attemptNumber"}) @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString public class SASQueueResponse { @JsonProperty("productId") private Object productId; @JsonProperty("partnerId") private Object partnerId; @JsonProperty("countryCode") private String countryCode; @JsonProperty("activityType") private String activitType; @JsonProperty("subscriptionId") private Object subscriptionId; @JsonProperty("attemptNumber") private Object attemptNumber; }<file_sep>package com.vuclip.premiumengg.automation.ad_network_service.tests; import com.vuclip.premiumengg.automation.ad_network_service.common.models.Message; import com.vuclip.premiumengg.automation.ad_network_service.common.utils.ANSMessageHelper; import com.vuclip.premiumengg.automation.ad_network_service.common.utils.ANSRedisUtils; import com.vuclip.premiumengg.automation.ad_network_service.common.utils.ANSTestContext; import com.vuclip.premiumengg.automation.ad_network_service.common.utils.ANSUtils; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils.DateTimeUtil; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils.TimeUnitEnum; import com.vuclip.premiumengg.automation.utils.DBUtils; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomUtils; import org.testng.annotations.Test; import java.math.BigInteger; /** * @author mayank.bharshiv */ public class ChurnUserDeactivatedDayOverTest { @Test(groups = {"pending", "bug"}) public void churnUserDeactivatedDayOverTest() throws Exception { Log4J.getLogger().info("===============================>Starting test case " + ChurnUserDeactivatedDayOverTest.class); int productId = ANSTestContext.productId; String billingCode = ANSTestContext.billingCode; BigInteger nBD = DateTimeUtil.getDateByAddingValidity(DateTimeUtil.getCurrentDateInGMT(), 20, TimeUnitEnum.DAY.name()); String userID = RandomStringUtils.random(10, false, true); long subscriptionId = RandomUtils.nextInt(100, 200); String addRow = "'" + "TRX_0bWIjr9XFh" + "'" + "," + 6561 + "," + "'" + "voluum_tidbNsEP=Xk2sPHJp8b" + "'" + "," + "'" + "SUCCESS" + "'" + "," + "'" + "NULL" + "'" + "," + "'" + "Xk2sPHJp8b" + "'" + "," + 0 + "," + "'" + "3544588762" + "'" + "," + 6561 + "," + 6561 + "," + 0 + "," + 105 + "," + "'" + "3544588762" + "'" + "," + "'" + "D_KIM114_188" + "'"; String requestParamVal = RandomStringUtils.random(10, true, true); String userSource = "D_KIM" + RandomUtils.nextInt(100, 900); String transactionId = "CHURN_TRX_" + RandomStringUtils.random(8, true, true); //TODO what to add?? DBUtils.addRecordInTable("user_adnotification", addRow); Message message = ANSUtils.generateMessageForQueue(productId, userID, billingCode, "50.0", "CONSENT", "ACTIVATION", "OPEN", "SUCCESS", subscriptionId, "ActivityEvent", nBD, ANSTestContext.requestParamName + "=" + requestParamVal, requestParamVal, transactionId, userSource); ANSMessageHelper.addMessageToQueue(message); System.out.println( "ANSRedisUtils.isKeyPresent(transactionId) ===== >" + ANSRedisUtils.keyPresent(transactionId)); message = ANSUtils.generateMessageForQueue(productId, userID, billingCode, "50.0", "CONSENT", "ACTIVATION", "CONFIRMED", "SUCCESS", subscriptionId, "ActivityEvent", nBD, ANSTestContext.requestParamName + "=" + requestParamVal, requestParamVal, transactionId, userSource); ANSMessageHelper.addMessageToQueue(message); System.out.println( "ANSRedisUtils.isKeyPresent(transactionId) ===== >" + ANSRedisUtils.keyPresent(transactionId)); message = ANSUtils.generateMessageForQueue(productId, userID, billingCode, "50.0", "CHARGING", "ACTIVATION", "SUCCESS", "SUCCESS", subscriptionId, "ActivityEvent", nBD, ANSTestContext.requestParamName + "=" + requestParamVal, requestParamVal, transactionId, userSource); ANSMessageHelper.addMessageToQueue(message); message = ANSUtils.generateMessageForQueue(productId, userID, billingCode, "50.0", "PROCESS_DEACTIVATE", "DEACTIVATION", "SUCCESS", "SUCCESS", subscriptionId, "ActivityEvent", nBD, ANSTestContext.requestParamName + "=" + requestParamVal, requestParamVal, transactionId, userSource); ANSMessageHelper.addMessageToQueue(message); System.out.println( "ANSRedisUtils.isKeyPresent(transactionId) ===== >" + ANSRedisUtils.keyPresent(transactionId)); } } <file_sep>package com.vuclip.premiumengg.automation.ad_network_service.common.models; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.*; import java.util.HashMap; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"adNetworkId", "name", "retryLimit", "requestParamName", "notificationUrl", "httpMethod", "notifyOnActivity", "status", "churnNotificationUrl", "sourceIdentifier", "operationType"}) @Getter @Setter @ToString @EqualsAndHashCode @AllArgsConstructor @NoArgsConstructor public class SaveAdnetwork { @JsonProperty("adNetworkId") private Integer adNetworkId; @JsonProperty("name") private String name; @JsonProperty("retryLimit") private Integer retryLimit; @JsonProperty("requestParamName") private String requestParamName; @JsonProperty("notificationUrl") private String notificationUrl; @JsonProperty("httpMethod") private String httpMethod; @JsonProperty("notifyOnActivity") private String notifyOnActivity; @JsonProperty("status") private String status; @JsonProperty("churnNotificationUrl") private String churnNotificationUrl; @JsonProperty("sourceIdentifier") private String sourceIdentifier; @JsonProperty("operationType") private String operationType; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); }<file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @EqualsAndHashCode(exclude= {"operationType"}) @ToString @Builder @AllArgsConstructor @NoArgsConstructor @JsonInclude(JsonInclude.Include.NON_EMPTY) public class AdNetworkNotificationVO { private int adNetworkNotificationId; private String name; private int paidPercentage; private int freePercentage; private int winbackPercentage; private String productName; private String partnerName; private String countryName; private String pricePoint; private String operationType; } <file_sep>package com.vuclip.premiumengg.automation.ad_network_service.common.utils; import com.vuclip.premiumengg.automation.ad_network_service.common.models.ANSProductAdnetworkTableFields; import com.vuclip.premiumengg.automation.ad_network_service.common.models.ANSTableNames; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.utils.DBUtils; import org.testng.Assert; import java.util.List; import java.util.Map; public class ANSDBUtils extends DBUtils { public static void cleanAllTable() { ANSTableNames tableNames[] = ANSTableNames.values(); for (ANSTableNames tableName : tableNames) { cleanTable(tableName.getValue(), null); } } public static String showProductAdnetworkDetailsTableData(String message, String productId, String partnerId) { String type = null; try { List<Map<String, Object>> record1 = DBUtils.getRecords("product_adnetwork_details", "product_id = " + productId + " and partner_id = " + partnerId); if (record1.size() >= 1) { Log4J.getLogger().info(message + "table name product_adnetwork_details "); logTableRecord(record1); type = "product_adnetwork_details"; } } catch (Exception e) { Log4J.getLogger().info("Error in fetching data"); } return type; } public static void logTableRecord(List<Map<String, Object>> records) { ANSProductAdnetworkTableFields tableFields[] = ANSProductAdnetworkTableFields.values(); Log4J.getLogger().info("Verify All Records are getting update in table"); for (Map<String, Object> map : records) { for (ANSProductAdnetworkTableFields tableField : tableFields) { if (map.get(tableField.getValue()) == null) { Assert.fail("Api not working"); } } } } } <file_sep>package com.vuclip.premiumengg.automation.ad_network_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.*; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"delivery_mode"}) @Getter @Setter @ToString @EqualsAndHashCode @AllArgsConstructor @NoArgsConstructor public class Properties { @JsonProperty("delivery_mode") private Integer deliveryMode; }<file_sep>package com.vuclip.premiumengg.automation.subscription_service.common.utils; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.common.RabbitMQConnection; import com.vuclip.premiumengg.automation.subscription_service.common.models.ConfirmSyncQueue; import com.vuclip.premiumengg.automation.subscription_service.common.models.RabbitMessage; import com.vuclip.premiumengg.automation.utils.AppAssert; import com.vuclip.premiumengg.automation.utils.ObjectMapperUtils; public class SRabitMessageHelper { public static void addMessageToQueue(RabbitMessage message) throws Exception { try { Log4J.getLogger().info("SENDING MESSAGE " + ObjectMapperUtils.writeValueAsString(message)); RabbitMQConnection.getRabbitTemplate().convertAndSend("core_subscription", message); Log4J.getLogger().info("MESSAGE SENT"); } catch (Exception e) { AppAssert.assertTrue(false, "not able to send message to queue"); } } public static void addMessageToQueue(ConfirmSyncQueue message) throws Exception { Log4J.getLogger().info(message.toString()); RabbitMQConnection.getRabbitTemplate().convertAndSend("core_subscription", message); Log4J.getLogger().info("Message sent"); } } <file_sep>package com.vuclip.premiumengg.automation.scheduled_activity_service.tests; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils.SASUtils; import com.vuclip.premiumengg.automation.scheduled_activity_service.common.utils.SASValidationHelper; import com.vuclip.premiumengg.automation.utils.AppAssert; import org.apache.commons.lang3.RandomUtils; import org.apache.log4j.Logger; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * @author rahul.s */ public class SASActivationRetryTest { private static Logger logger = Log4J.getLogger("SASActivationRetryTest"); int productId; int partnerId; private String countryCode = "IN"; @BeforeClass(alwaysRun = true) public void setup() throws Exception { productId = SASUtils.productId; partnerId = productId; } @DataProvider(name = "activationRetryPostiveDataProvider") public Object[][] activationRetryPostiveDataProvider() { return new Object[][]{ {"ACTIVATION_RETRY", "ACTIVATED", "SUCCESS", "CHARGING", "renewal"}, /** * failed{ "ACTIVATION_RETRY", "ACT_INIT", "FAILURE", "CHARGING", "activation" * }, */ /** * failed { "ACTIVATION_RETRY", "ACT_INIT", "ERROR", "CHARGING", "activation" }, */ /** * failed { "ACTIVATION_RETRY", "ACT_INIT", "IN_PROGRESS", "CHARGING", * "activation" }, */ // { "ACTIVATION_RETRY", "PARKING", "LOW_BALANCE", "CHARGING", "winback" }, }; } @Test(dataProvider = "activationRetryPostiveDataProvider", groups = {"positive"}) public void activationRetryPositiveTest(String activityType, String currentSubscriptionState, String transactionState, String eventActionType, String actionTable) throws Exception { Integer subscriptionId = RandomUtils.nextInt(1000, 2000); logger.info("==================>Starting activation Retry Positive Test [ " + SASUtils.getTestLogMessage(productId, subscriptionId, eventActionType, activityType, currentSubscriptionState, transactionState) + " ]"); try { String schedulerActivity = actionTable; String queueName = actionTable.toUpperCase(); SASUtils.executeActivityFlow(productId, partnerId, subscriptionId, countryCode, eventActionType, activityType, currentSubscriptionState, transactionState, actionTable, schedulerActivity, "OPEN", "IN_PROGRESS", queueName); } catch (Exception e) { logger.error("activationRetryPositiveTest Failed"); e.printStackTrace(); AppAssert.assertTrue(false); } } @DataProvider(name = "activationRetryNegativeDrataPovider") public Object[][] activationRetryNegativeDrataPovider() { return new Object[][]{{"ACTIVATION_RETRY", "ACTIVATED", "LOW_BALANCE", "CHARGING", "renewal"}, {"ACTIVATION_RETRY", "ACTIVATED", "FAILURE", "CHARGING", "renewal"}, {"ACTIVATION_RETRY", "ACTIVATED", "ERROR", "CHARGING", "renewal"}, {"ACTIVATION_RETRY", "ACTIVATED", "IN_PROGRESS", "CHARGING", "renewal"}, {"ACTIVATION_RETRY", "ACT_INIT", "LOW_BALANCE", "CHARGING", "renewal"}, {"ACTIVATION_RETRY", "ACT_INIT", "SUCCESS", "CHARGING", "activation"}, {"ACTIVATION_RETRY", "PARKING", "SUCCESS", "CHARGING", "winback"}, {"ACTIVATION_RETRY", "PARKING", "FAILURE", "CHARGING", "winback"}, {"ACTIVATION_RETRY", "PARKING", "ERROR", "CHARGING", "winback"}, {"ACTIVATION_RETRY", "PARKING", "IN_PROGRESS", "CHARGING", "winback"}}; } @Test(dataProvider = "activationRetryNegativeDrataPovider", groups = {"negative"}) public void activationRetryNegativeTest(String activityType, String currentSubscriptionState, String transactionState, String actionType, String actionTable) throws Exception { Integer subscriptionId = (RandomUtils.nextInt(3000, 4000)); logger.info( "==================>Starting activation Retry Negative Test [ " + SASUtils.getTestLogMessage(productId, subscriptionId, actionType, activityType, currentSubscriptionState, transactionState) + " ]"); SASValidationHelper.negativeFlow(productId, partnerId, activityType, currentSubscriptionState, transactionState, actionType, subscriptionId); } } <file_sep> package com.vuclip.premiumengg.automation.subscription_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.Getter; import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "userId" }) @Getter @Setter public class UserDetails { @JsonProperty("userId") private String userId; @JsonProperty("msisdn") private String msisdn; } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; public enum SmsType { CONTENT_SMS, ENGAGEMENT_SMS, PRE_RENEWAL_SMS, OPTOUT_SMS, ACTIVATION_SMS, DEACTIVATION_SMS, RENEWAL_SMS; public static SmsType fromValue(String val) { for (SmsType mode : SmsType.values()) { if (mode.toString().equals(val)) { return mode; } } return null; } } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; @Getter @ToString @Builder @AllArgsConstructor @NoArgsConstructor public class DateCoumputationCriterionRequestVO { private DateCoumputationCriterionName name; private DateCoumputationCriterionOperator operator; private String value; private TimeUnit unit; } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.models; import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; @Getter @ToString @Builder @AllArgsConstructor @NoArgsConstructor public class CriteriaRequestVO { private String smsText; private List<CriterionRequestVO> criterions; private DateCoumputationCriterionRequestVO dateCoumputationCriterion; } <file_sep>package com.vuclip.premiumengg.automation.ad_network_service.common.models; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.*; import java.util.HashMap; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"dateComputationCriterionId", "name", "operator", "value", "unit"}) @Getter @Setter @ToString @EqualsAndHashCode @AllArgsConstructor @NoArgsConstructor public class DateCoumputationCriterion { @JsonProperty("dateComputationCriterionId") private Integer dateComputationCriterionId; @JsonProperty("name") private String name; @JsonProperty("operator") private String operator; @JsonProperty("value") private String value; @JsonProperty("unit") private String unit; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); }<file_sep>package com.vuclip.premiumengg.automation.billing_package_service.common.models; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import groovy.transform.ToString; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"partnerId", "partnerName", "description", "status", "autoRenewalApplicable", "type", "stepUpCharging", "userIdentifier", "balanceCheckRequired", "activationManagedBy", "renewalManagedBy", "deactivationManagedBy", "hasMoActivations", "hasMoDeactivations", "operationType", "partnerActivationConsentParserUrl", "partnerDeactivationConsentParserUrl", "partnerActivationConsentInitiationUrl", "partnerDeactivationConsentInitiationUrl"}) @Getter @Setter @ToString @NoArgsConstructor @AllArgsConstructor public class BPSSavePartnerRequest { @JsonProperty("partnerId") private Integer partnerId; @JsonProperty("partnerName") private String partnerName; @JsonProperty("description") private String description; @JsonProperty("status") private String status; @JsonProperty("autoRenewalApplicable") private Boolean autoRenewalApplicable; @JsonProperty("type") private String type; @JsonProperty("stepUpCharging") private Boolean stepUpCharging; @JsonProperty("userIdentifier") private String userIdentifier; @JsonProperty("balanceCheckRequired") private Boolean balanceCheckRequired; @JsonProperty("activationManagedBy") private String activationManagedBy; @JsonProperty("renewalManagedBy") private String renewalManagedBy; @JsonProperty("deactivationManagedBy") private String deactivationManagedBy; @JsonProperty("hasMoActivations") private Boolean hasMoActivations; @JsonProperty("hasMoDeactivations") private Boolean hasMoDeactivations; @JsonProperty("operationType") private String operationType; @JsonProperty("partnerActivationConsentParserUrl") private String partnerActivationConsentParserUrl; @JsonProperty("partnerDeactivationConsentParserUrl") private String partnerDeactivationConsentParserUrl; @JsonProperty("partnerActivationConsentInitiationUrl") private String partnerActivationConsentInitiationUrl; @JsonProperty("partnerDeactivationConsentInitiationUrl") private String partnerDeactivationConsentInitiationUrl; }<file_sep>package com.vuclip.premiumengg.automation.ad_network_service.common.utils; import com.vuclip.premiumengg.automation.ad_network_service.common.models.Message; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.common.RabbitMQConnection; public class ANSMessageHelper { public static void addMessageToQueue(Message message) throws Exception { Log4J.getLogger().info(message.toString()); RabbitMQConnection.getRabbitTemplate().convertAndSend("core_adnetwork", message); Log4J.getLogger().info("Message sent"); } /*public static void addMessageToQueue(Integer productId, String productName, Integer partnerId, String partnerName, String userId, String attemptedBillingCode, String attemptedPrice, String chargedBillingCode, String chargedPrice, String requestedBillingCode, String requestedPrice, String action, String activity, String transactionState, String actionResult, long subscriptionId, String eventType, BigInteger nextBillingDate, String adNetworkParams, Object churnNotificationParam, Object userSource) throws Exception { Message message = new Message(); message.setEventType(eventType); message.setProductId(productId); message.setProductName(productName); message.setPartnerId(partnerId); message.setPartnerName(partnerName); message.setUserId(userId); message.setMsisdn(userId); message.setAttemptedBillingCode(attemptedBillingCode); message.setAttemptedPrice(attemptedPrice); message.setChargedBillingCode(chargedBillingCode); message.setChargedPrice(chargedPrice); message.setRequestedBillingCode(requestedBillingCode); message.setRequestedPrice(requestedPrice); message.setAction(action); message.setActivity(activity); message.setTransactionState(transactionState); message.setActionResult(actionResult); message.setSubscriptionId(subscriptionId); message.setUserSource(userSource); message.setNextBillingDate(nextBillingDate); message.setAdNetworkParams(adNetworkParams); message.setMode("WAP"); message.setChurnNotificationParam(churnNotificationParam); addMessageToQueue(message); }*/ } <file_sep>package com.vuclip.premiumengg.automation.configuration_service.common.utils; import static io.restassured.RestAssured.given; import static io.restassured.RestAssured.with; import org.apache.log4j.Logger; import com.vuclip.premiumengg.automation.common.Configuration; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.configuration_service.common.models.PartnerRequestVO; import io.restassured.http.ContentType; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; /** * @author mayank.bharshiv */ public class CSHelper { private static Logger logger = Log4J.getLogger("SavePartnerTests"); static RequestSpecification requestSpecification; /** * Default constructor. Initializes the request template. */ public static RequestSpecification getRequestSpecification() { if (requestSpecification == null) { requestSpecification = with().baseUri(Configuration.csServer); } return requestSpecification; } /** * @param publishConfigRequest * @return response * @throws Exception */ public static Response savePartner(PartnerRequestVO savePartner) throws Exception { logger.info("Save Partner Api Called"); final Response response = given(getRequestSpecification()).contentType(ContentType.JSON).body(savePartner).log() .all().post("/partner"); response.prettyPrint(); return response; } public static Response updatePartner(PartnerRequestVO savePartner) throws Exception { logger.info("Update Partner Api Called"); final Response response = given(getRequestSpecification()).contentType(ContentType.JSON).body(savePartner).log() .all().put("/partner"); response.prettyPrint(); return response; } public static Response getPartnerByName(String partnerName) throws Exception { logger.info("Get Partner By Name Api Called"); final Response response = given(getRequestSpecification()).pathParam("partnerName", partnerName).contentType(ContentType.JSON).log() .all().get("/partner/{partnerName}"); response.prettyPrint(); return response; } } <file_sep>package com.vuclip.premiumengg.automation.subscription_service.tests; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.log4j.Logger; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.vuclip.premiumengg.automation.common.Log4J; import com.vuclip.premiumengg.automation.subscription_service.common.models.BlockStatusResponse; import com.vuclip.premiumengg.automation.subscription_service.common.models.VerifyBlockUserStatusData; import com.vuclip.premiumengg.automation.subscription_service.common.utils.SHelper; import com.vuclip.premiumengg.automation.subscription_service.common.utils.SRedisUtils; import com.vuclip.premiumengg.automation.subscription_service.common.utils.SUtils; import com.vuclip.premiumengg.automation.subscription_service.common.utils.TestDataCreator; import com.vuclip.premiumengg.automation.utils.AppAssert; import com.vuclip.premiumengg.automation.utils.DBUtils; import io.restassured.response.Response; public class VerifyBlockUserStatus { private static Logger logger = Log4J.getLogger(SubscriptionBlockTests.class.toGenericString()); Map<String, String> query = new HashMap<String, String>(); @DataProvider(name = "subscriptionBlockTestBlackListed") public Iterator<Object[]> subscriptionBlockTestBlackListed() { ArrayList<VerifyBlockUserStatusData> verifyBlockUserStatusData = new ArrayList<VerifyBlockUserStatusData>(); verifyBlockUserStatusData.add(VerifyBlockUserStatusData.BLACKLIST); verifyBlockUserStatusData.add(VerifyBlockUserStatusData.NOTBLACKLIST); Collection<Object[]> dp = new ArrayList<Object[]>(); for (VerifyBlockUserStatusData sbData : verifyBlockUserStatusData) { dp.add(new Object[] { sbData }); } return dp.iterator(); } /** * Subscription Block Tests for Blacklisting/Cooldown User Test */ @Test(dataProvider = "subscriptionBlockTestBlackListed", groups = { "positive" }, priority = 1) public void subscriptionBlockTestBlackListed(VerifyBlockUserStatusData verifyBlockUserStatusData) throws Exception { logger.info("Starting ================> Subscription Block Tests for BlackList"); String user_sub_auth_key = TestDataCreator.createSubscriptionBlockUserStatus(verifyBlockUserStatusData); AppAssert.assertTrue(SRedisUtils.checkKey(user_sub_auth_key)); logger.info("Check Key Present in Redis for Blocked User"); String blockedUSerKey = "USERID_" + verifyBlockUserStatusData.getProduct_id() + "_" + verifyBlockUserStatusData.getPartner_id() + "_" + verifyBlockUserStatusData.getCountry() + "_" + verifyBlockUserStatusData.getUser_id(); AppAssert.assertTrue(SRedisUtils.checkKey(blockedUSerKey)); logger.info("Validate Blacklist User Status"); query.put("userId", verifyBlockUserStatusData.getUser_id()); query.put("productId", String.valueOf(verifyBlockUserStatusData.getProduct_id())); query.put("partnerId", String.valueOf(verifyBlockUserStatusData.getPartner_id())); query.put("country", verifyBlockUserStatusData.getCountry()); Response blockStatusResponse = SHelper.subscriptionBlockStatus(query); BlockStatusResponse blockStatus = blockStatusResponse.getBody().as(BlockStatusResponse.class); AppAssert.assertEqual(blockStatus.getBlockSummary(), verifyBlockUserStatusData.getBlockListSummary()); } @DataProvider(name = "subscriptionBlockTestNew") public Iterator<Object[]> subscriptionBlockTestNew() { ArrayList<VerifyBlockUserStatusData> verifyBlockUserStatusData = new ArrayList<VerifyBlockUserStatusData>(); verifyBlockUserStatusData.add(VerifyBlockUserStatusData.BLACKLISTNEWUSER); Collection<Object[]> dp = new ArrayList<Object[]>(); for (VerifyBlockUserStatusData sbData : verifyBlockUserStatusData) { dp.add(new Object[] { sbData }); } return dp.iterator(); } /** * Subscription Block Tests for Blacklisting/Cooldown User Test */ @Test(dataProvider = "subscriptionBlockTestNew", groups = { "positive" }) public void subscriptionBlockTestNew(VerifyBlockUserStatusData verifyBlockUserStatusData) throws Exception { logger.info("Starting ================> Subscription Block Tests for BlackList Status New User"); logger.info("Validate Blacklist User Status New"); query.put("userId", verifyBlockUserStatusData.getUser_id()); query.put("productId", String.valueOf(verifyBlockUserStatusData.getProduct_id())); query.put("partnerId", String.valueOf(verifyBlockUserStatusData.getPartner_id())); query.put("country", verifyBlockUserStatusData.getCountry()); Response blockStatusResponse = SHelper.subscriptionBlockStatus(query); BlockStatusResponse blockStatus = blockStatusResponse.getBody().as(BlockStatusResponse.class); AppAssert.assertEqual(blockStatus.getBlockSummary(), verifyBlockUserStatusData.getBlockListSummary()); } @BeforeClass(alwaysRun = true) public void cleanUp() { DBUtils.cleanTable("user_subscription", "product_id =" + SUtils.productId + " and partner_id =" + SUtils.productId); DBUtils.cleanTable("blocked_user", "product_id =" + SUtils.productId + " and partner_id =" + SUtils.productId); } }
47cf5478bf86d8b961bf2966da29be42f74affe3
[ "Java", "Maven POM", "INI" ]
122
Java
mayankbharshiv/systemTest-Vuclip
023417522b18d6724086883114094bccc643a555
5cb192e4003056f8f6cd5ae630d057dfc35eb1e7
refs/heads/master
<repo_name>voltrb/volt-mongo<file_sep>/app/mongo/lib/mongo_adaptor_client.rb module Volt class DataStore class MongoAdaptorClient < BaseAdaptorClient data_store_methods :find, :where, :skip, :order, :limit#, :count module MongoArrayStore # Find takes a query object def where(query = {}) add_query_part(:find, query) end alias_method :find, :where # .sort is already a ruby method, so we use order instead def order(sort) add_query_part(:sort, sort) end # def count # add_query_part(:count).then # end end # Due to the way define_method works, we need to remove the generated # methods from data_store_methods before we over-ride them. Volt::Persistors::ArrayStore.send(:remove_method, :where) Volt::Persistors::ArrayStore.send(:remove_method, :order) # Volt::Persistors::ArrayStore.send(:remove_method, :count) # include mongo's methods on ArrayStore Volt::Persistors::ArrayStore.send(:include, MongoArrayStore) def self.normalize_query(query) query = merge_finds_and_move_to_front(query) query = reject_skip_zero(query) query end def self.merge_finds_and_move_to_front(query) # Map first parts to string query = query.map { |v| v[0] = v[0].to_s; v } has_find = query.find { |v| v[0] == 'find' } if has_find # merge any finds merged_find_query = {} query = query.reject do |query_part| if query_part[0] == 'find' # on a find, merge into finds find_query = query_part[1] merged_find_query.merge!(find_query) if find_query # reject true else false end end # Add finds to the front query.insert(0, ['find', merged_find_query]) else # No find was done, add it in the first position query.insert(0, ['find']) end query end def self.reject_skip_zero(query) query.reject do |query_part| query_part[0] == 'skip' && query_part[1] == 0 end end end end end<file_sep>/README.md # volt-mongo This gem provides mongodb support for volt. Just include it in your gemfile and the gem will do the rest. It is included in new projects by default (currently). ``` gem 'volt-mongo' ```<file_sep>/app/mongo/controllers/main_controller.rb # require 'mongo/config/initializers/boot' module Mongo class MainController < Volt::ModelController end end <file_sep>/app/mongo/lib/mongo_adaptor_server.rb require 'mongo' require 'volt/utils/data_transformer' # We need to be able to deeply stringify keys for mongo class Hash def nested_stringify_keys self.stringify_keys.map do |key, value| if value.is_a?(Hash) value = value.nested_stringify_keys end [key, value] end.to_h end end module Volt class DataStore class MongoAdaptorServer < BaseAdaptorServer attr_reader :db, :mongo_db # check if the database can be connected to. # @return Boolean def connected? begin db true rescue ::Mongo::Error => e false end end def db return @db if @db if Volt.config.db_uri.present? db_name = Volt.config.db_uri.split('/').last || Volt.config.db_name @db ||= ::Mongo::Client.new(Volt.config.db_uri, database: db_name, :monitoring => false) else db_name = Volt.config.db_name @db ||= ::Mongo::Client.new("mongodb://#{Volt.config.db_host}:#{Volt.config.db_port}", database: db_name, :monitoring => false) end @db end def insert(collection, values) db[collection].insert_one(values) end def update(collection, values) values = values.nested_stringify_keys values = Volt::DataTransformer.transform(values) do |value| if defined?(VoltTime) && value.is_a?(VoltTime) value.to_time else value end end to_mongo_id!(values) # TODO: Seems mongo is dumb and doesn't let you upsert with custom id's begin db[collection].insert_one(values) rescue => error # Really mongo client? msg = error.message if (msg[/^E11000/] || msg[/^insertDocument :: caused by :: 11000 E11000/]) && msg['$_id_'] # Update because the id already exists update_values = values.dup id = update_values.delete('_id') db[collection].update_one({ '_id' => id }, update_values) else return { error: error.message } end end nil end def query(collection, query) if ENV['DB_LOG'] && collection.to_s != 'active_volt_instances' Volt.logger.info("Query: #{collection}: #{query.inspect}") end allowed_methods = %w(find skip limit sort) result = db[collection] query.each do |query_part| method_name, *args = query_part unless allowed_methods.include?(method_name.to_s) fail "`#{method_name}` is not part of a valid query" end args = args.map do |arg| if arg.is_a?(Hash) arg = arg.stringify_keys end arg end if method_name == 'find' && args.size > 0 qry = args[0] to_mongo_id!(qry) end result = result.send(method_name, *args) end if result.is_a?(::Mongo::Collection::View) result = result.to_a.map do |hash| # Return id instead of _id to_volt_id!(hash) # Volt expects symbol keys hash.symbolize_keys end#.tap {|v| puts "QUERY: " + v.inspect } end values = Volt::DataTransformer.transform(result) do |value| if defined?(VoltTime) && value.is_a?(Time) value = VoltTime.from_time(value) else value end end values end def delete(collection, query) if query.key?('id') query['_id'] = query.delete('id') end db[collection].delete_one(query) end # remove the collection entirely def drop_collection(collection) db[collection].drop end def drop_database db.database.drop end def adapter_version ::Mongo::VERSION end private # Mutate a hash to use id instead of _id def to_volt_id!(hash) if hash.key?('_id') # Run to_s to convert BSON::Id also hash['id'] = hash.delete('_id').to_s end end # Mutate a hash to use _id instead of id def to_mongo_id!(hash) if hash.key?('id') hash['_id'] = hash.delete('id') end end end end end
d9bc2d0c00faad49a7d0cf2b02bd22c39b75d8a6
[ "Markdown", "Ruby" ]
4
Ruby
voltrb/volt-mongo
8c6f90985929328edc54709cb849c171ed08b213
3e20fe98e39c177836e7bd934031cad9dcfd9a52
refs/heads/master
<repo_name>mackenzieTjogas/PurpleRun<file_sep>/402Proj/View Controllers/UserViewControllerEducation.swift // // UserViewControllerEducation.swift // 402Proj // // Created by <NAME> on 1/29/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class UserViewControllerEducation: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func makeCall(phoneNum: String) { if let url = URL(string: "tel://\(phoneNum)"), UIApplication.shared.canOpenURL(url) { if #available(iOS 10, *) { UIApplication.shared.open(url) } else { UIApplication.shared.openURL(url) } } } @IBAction func showEmergencyMessage(sender: UIButton) { let phoneNumber : String = "911" makeCall(phoneNum : phoneNumber) } @IBAction func exampleButton(sender: AnyObject) { if let url = URL(string: "https://www.speakcdn.com/assets/2497/domestic_violence_and_physical_abuse_ncadv.pdf") { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } @IBAction func exampleButton2(sender: AnyObject) { if let url = URL(string: "https://www.speakcdn.com/assets/2497/domestic_violence_and_psychological_abuse_ncadv.pdf") { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } @IBAction func exampleButton3(sender: AnyObject) { if let url = URL(string: "https://www.speakcdn.com/assets/2497/domestic_violence_and_economic_abuse_ncadv.pdf") { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } @IBAction func exampleButton4(sender: AnyObject) { if let url = URL(string: "https://www.betterhelp.com/advice/abuse/would-you-recognize-verbal-abuse-heres-what-you-need-to-know/") { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } @IBAction func exampleButton5(sender: AnyObject) { if let url = URL(string: "https://www.domesticshelters.org/domestic-violence-articles-information/when-abusers-use-sexual-abuse-to-control#.WsrJUZPwbaY") { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } @IBAction func exampleButton6(sender: AnyObject) { if let url = URL(string: "https://www.speakcdn.com/assets/2497/domestic_violence_and_stalking_ncadv.pdf") { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>/SDF/2.0 Preliminary Project Proposals.md # 2.0 Preliminary Project Proposals 1. Domestic Violence App <p>PurpleRun is a domestic violence app. It will be a resource for survivors, as well as a resource to help educate anyone who wants to learn more about this issue and help the cause. The app has a game-like name to avoid causing any suspicions from the abuser. The homepage will appear as a game and a pin will be needed to get to the “real” homepage of the app. Every page of the app will have an emergency button that will immediately call 911 and the call won't be ended unless the user’s pin is entered.The app will have a main menu page with option for all of the information it will have: how to be an advocate/ally (which will explainhow to help, where to volunteer, what to know, etc.), information on different types of abuse, general info for all survivors (legal, health, etc.), information for undocumented survivors, information for mothers/survivors with children, and shelters in the user’s local area with their contact information. The app will also have different language options as well as information on interpreters.</p> 2. Bored & Broke (continuation fo 401) <p>A possible extension of the current features available on last semester's application, or the possibility of turning Bored&Broke into a mobile app.</p> <file_sep>/SDF/5.0 Requirements Specification Document.md ## 5.0 Requirements Specification Table of contents: 5.1 Introduction 5.2 Functional Requirements 5.3 Performance Requirements 5.4 Environment Requirements ### 5.1 Introduction This Software Requirements Specifcation (SRS) outlines the software requirements for the PurpleRun iOS app. PurpleRun is a domestic violence app. It will be a resource for survivors of domestic abuse, as well as a resource to help educate anyone who wants to learn more about this issue and help the cause. The app is careful to avoid raising any suspicion from an abuser, with a game-like name and homescreen. A pin will be needed to get to the “real” homepage of the app. Every page of the app will have an emergency button that will immediately call 911. The app will be a source of informatoin, giving users the opportunity to select from the main menu information on: how to be an advocate, education on the different types of abuse, general legal information, what to do if you are an undocumented survivor, what to do if you are a survivor with children, and shelters in your area. The app will also have different language options as well as information on interpreters. The user only needs internet access and a smartphone. The app will will require API calls to gather the information shared on the app, a web server to call the APIs and to interact with the website, and a set of HTML webpages that will display all of the information to users. If the APIs change in their functionality, maintenance may be required. ![uml diagram](https://github.com/mackenzieTjogas/PurpleRun/blob/master/SDF/umlDiagram.png "UML Diagram") The remainder of this document is structured as follows: section 5.2 contains information about the Functional Requirements, which are specifications that the application should have, section 5.3 describes the Performance Requirements which outline the app's capabilities (once it's finished), and section 5.4 explains the Environment Requirements which are the resources needed to develop the application. ### 5.2 Functional Requirements 5.2.1 Mobile (Graphical) User Interface: The mobile user interface for the app shall allow the user to select which information they'd like to view from the main menu. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;5.2.1.1 The mobile user interface shall provide a menu system to access all functions of the application. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Application functions will include: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*login to the *real* homepage of the app &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*choose which topic to view from the app’s main menu &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*choose your language in which to view the app &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*make an emergency call &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;5.2.1.2 The mobile user interface shall provide a set of buttons to allow access to all functions of the application 5.2.2 Menu Selection: The app shall allow users to select which information they want to view from the main menu. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;5.2.2.1 The user shall be able to click on a menu item to be taken to a new page devoted to that item's topic 5.2.3 Emergency Call: Users shall be able to hit the phone icon (shown on each page of the app) to call 911. ### 5.3 Performance Requirements 5.3.1 Language Translation &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;5.3.1.1 The app shall return the translated text for the any language selected by a user (from the given language menu) within 10 seconds of the time the user submits the translation request. 5.3.2 Find a shelter Search &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;5.3.2.1 The app shall return the shelters in the area for the any area given by a user within 10 seconds of the time the user submits the request. ### 5.4 Environment Requirements 5.4.1 Development Environment Requirements &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;5.4.1.1 This application's frontend with use Swift 5.4.2 Execution Environment Requirements &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;5.4.2.1 This application shall run on Safari through iOS &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;5.4.2.2 To reach the app, the browser must have connection to the internet <file_sep>/402Proj/ViewController.swift // // ViewController.swift // 402Proj // // Created by <NAME> on 1/28/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit // import CoreLocation import Alamofire import SwiftyJSON class ViewController: UIViewController { // let APP_ID = "" // let API_URL = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // removed the below button: // @IBAction func showMessage(sender: UIButton) { // let alertController = UIAlertController(title: "You will now need to enter your pin", // message: "You will only get 2 trys", preferredStyle: UIAlertControllerStyle.alert) // alertController.addAction(UIAlertAction(title: "Enter", style: // UIAlertActionStyle.default, handler: nil)) // // call the enter function below in the handler ^^ // present(alertController, animated: true, completion: nil) // // Eventually, when 'Enter' is hit, a pin code/password input // // box needs to appear. Then when the password is inputted and the user // // clicks 'submit' they should be taken to the second page. Right now this is done // // by the 'ChangeLater' button on the top right of homepage. This button won't be // // needed once this is implemented correctly. // } func enter() { performSegue(withIdentifier: "testSegue", sender: self) } func makeCall(phoneNum: String) { if let url = URL(string: "tel://\(phoneNum)"), UIApplication.shared.canOpenURL(url) { if #available(iOS 10, *) { UIApplication.shared.open(url) } else { UIApplication.shared.openURL(url) } } } @IBAction func showEmergencyMessage(sender: UIButton) { let phoneNumber : String = "911" makeCall(phoneNum : phoneNumber) } } <file_sep>/SDF/3.0 Project Proposal Document.md # PurpleRun ### 3.0 Project Proposal Document ###### Description PurpleRun is a domestic violence app. It will be a resource for survivors, as well as a resource to help educate anyone who wants to learn more about this issue and help the cause. The app has a game-like name to avoid causing any suspicions from the abuser. The homepage will appear as a game and a pin will be needed to get to the “real” homepage of the app. Every page of the app will have an emergency button that will immediately call 911. The app will have a main menu page with option for all of the information it will have: how to be an advocate/ally (which will explainhow to help, where to volunteer, what to know, etc.), information on different types of abuse, general info for all survivors (legal, health, etc.), information for undocumented survivors, information for mothers/survivors with children, and shelters in the user’s local area with their contact information. The app will also have different language options as well as information on interpreters. The end user for PurpleRun is anyone who wants to access more information about domestic violence-whether because they themselves are a victim or because they want to help the cause. The user only needs internet access and a smartphone. The app will will require API calls to gather the information shared on the app, a web server to call the APIs and to interact with the database and website, and a set of HTML webpages that will display all of the information to users. If the APIs change in their functionality, maintenance may be required. There are other domestic violence apps in existence but all have a slightly different set of features. ###### Justification I decided to pursue this as my 402 project because it encompasses so much of my experience at LMU. I’ve been a part of Belles Service Organization since freshman year, and through this I’ve been serving at a domestic violence shelter on a weekly basis for a few years. Being able to work with women and children who have been affected by domestic violence has given me perspective and experience on the issue that will help me to make this app, as well as made me incredibly passionate about the cause. The project will pull from all of my previous computer science courses, and will challenge me to do my best work. It will have a very wide target audience, which means it will need to be usable for users of all different backgrounds, languages, ethnicities, etc, which is a task I haven’t encountered to this scale ever before in my CS career. The app will demonstrate my abilities and the knowledge I’ve gained from interaction design, as I strive for usability, programming language as I work with Swift for the first time, 401 as I complete another project but this time individually, and so on with all of the CS classes. Although the project will be difficult I believe the classes and internship experience I’ve had so far have prepared me to do it. It will be a lot of work but since it will call APIs to gather information and won’t need a database I believe I will have enough time to complete it. Another reason I feel compelled to complete this project is because domestic violence is an epidemic in America and it needs more attention then it is getting. According to the NCADV (National Coalition Against Domestic Violence): * 1 in 3 women and 1 in 4 men have been victims of physical violence by an intimate partner * 1 in 4 women and 1 in 7 men have been victims of severe physical violence by an intimate partner * Women between the ages of 18-24 are the most commonly abused by an intimate partner * Approx. 75% of women who are killed by their abusers are murdered when they attempt to leave or have left abusive relationship. So this project and more like it need to be done. Being an LMU student means being a person with and for others, to me this project is a way to do so. <file_sep>/homework/Homework Assignments.md ### Homework Assignments: Assignment #1 — due on Week 4 Assignment #2 — due on Week 6 Assignment #3 — due on Week 10 <file_sep>/README.md ![logo text](https://github.com/mackenzieTjogas/PurpleRun/blob/master/PurpleRunLogo.png "Logo Title") # PurpleRun Senior Project for 402 PurpleRun is a domestic violence iOS app. It will be a resource for survivors of domestic abuse, as well as a resource to help educate anyone who wants to learn more about this issue and help the cause. Note this app will provide information for survivors and allies **who are in the United States**. The app is careful to avoid raising any suspicion from an abuser, with a game-like name and homescreen. A password will be needed to get to the “real” homepage of the app. Every page of the app will have an emergency button that will immediately call 911. The app will be a source of information, giving users the opportunity to select from the main menu information on: how to be an advocate, education on the different types of abuse, general legal information, what to do if you are an undocumented survivor, what to do if you are a survivor with children, and shelters in your area. The app will also have different language options as well as information on interpreters. The user only needs internet access and a smartphone. Please note: This app does not use Apple's new "Emergency SOS" feature because it is triggered in different ways for different iPhone versions and requires a software update to iOS 11. This app is intended to be as simple as possible for users who have differing levels of familiarity with iPhones, and since the Emergency SOS feature is relatively new, it is unlikely that all users would know what it is (or feel comfortable using it). Likewise, it is unknown how many users will have done the software update to iOS 11 before using PurpleRun. Additionally, this app does not require users to make accounts. Research shows that this can make a user less likely to use a resource if they fear they will be caught. Even if the threat is nonexistent and making an account will not cause them to recieve emails (or leave any other trail of suspicion), the fear itself may deter users from using the app. ## Simulation -Install xcode -Clone this repo -Open the repo as a project on xcode -Run XCode's simulator <file_sep>/SDF/4.0 Software Development Plan.md # 4.0 Software Development Plan ### 4.1 Plan Introduction This Software Development Plan provides the details of the planned development for the PurpleRun iOS app which provides an application that provides information and resources to domestic violence survivors in the U.S. and those who want to educate themselves on the issue. Domestic violence affects nearly 20 people per minute in the United States (https://ncadv.org/statistics). PurpleRun aims to both educate society on this epidemic, as well as provide resources and information for survivors of intimate partner violence. PurpleRun is a domestic violence iOS app. It will be a resource for survivors of domestic abuse in the U.S., as well as a resource to help educate anyone who wants to learn more about this issue and help the cause. The app is careful to avoid raising any suspicion from an abuser, with a game-like name and homescreen. A pin will be needed to get to the “real” homepage of the app. Every page of the app will have an emergency button that will immediately call 911. The app will be a source of informatoin, giving users the opportunity to select from the main menu information on: how to be an advocate, education on the different types of abuse, general legal information, what to do if you are an undocumented survivor, what to do if you are a survivor with children, and shelters in your area. The app will also have different language options as well as information on interpreters. The projects sub task include (and have included): * An updated and finalized Software Development Plan in week eleven * An updated and finalized Requirements Specification Document in week thirteen * A Preliminary demo presentations during weeks thirteen - fifteen * A final product delivery (both project code and report) and presentation during week seventeen ### 4.1.1 Project Deliverables The projects sub task include (and have included): * **Project Proposal** *week two:* -This document provides a verbal description of the project, as well as a justification of the project. * **Initial Requirements Specification Document** *week five* -This is intended as a contract between the customer (instructor) and the solution provider. The document specifies exactly what is being built. -It includes Functional Requirements, Performance Requirements, and Environment Requirements. * **Initial Software Development Plan** *week nine* -A plan that is intended to describe the process that will be used during the semester, leading to the production of all required documents and software for your project. -Includes: Plan Introduction, Project Deliverables, Project Resources, Hardware Resources, Software Resources, Project Organization, Project Schedule, PERT / GANTT Chart, Task / Resource Table, and a Class Schedule (optional). * **Updated Software Development Plan** *week eleven* -The same as the document abovem just with updates and finalizations to the plan. * **Oral Status Reports** *every week from week nine onward* -Given in the form of SCRUMs in class -Explains what you have accomplished, where you currently are, what you plan to accomplish by the next SCRUM, and any possible roadblocks you may be dealing with * **Written Status Reports** *every other week from week nine onward* -Outlines the accomplishments since the last report, the tasks scheduled to be done by the next report, and notworthy risks/concerns/problems. * **Updated Requirements Specification Document** *week thirteen* -The same Requirements Specification Document that is listed above, just with updates and finalizations. * **Preliminary Demo Presentations** *weeks thirteen - fifteen* -A demonstration of the project/product in front of the class * **Final Product Delivery and Presentation** *week seventeen* -Both the code for the project and the final report are due ### 4.2 Project Resources ### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 4.2.1 Hardware Resources Resource | Development | Execution ------------------ | ------------- | ----------- macOS Machine | ✓ | ✓ iOS Machine | ✓ | ✓ 2 GB RAM (Minimum) | ✓ | ✓ Display | ✓ | ✓ Internet Connection | ✓ | ✓ ### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 4.2.2 Software Resources Resource | Development | Execution ---------------------------------------- | ------------- | --------- macOS | ✓ | ✓ Windows 10 | ✓ | ✓ Xcode (version 9.2) | ✓ | Web Broswers (Chrome, Firefox, IE) | ✓ | ✓ GitHub | ✓ | Google Drive | ✓ | ### 4.3 Project Organization **Major Functions of the app:** * Frontend/making the pages: * homepage * settings page * main menu page * "how to be an ally/advocate" page * "education on the different types of abuse" page * "general legal information" page * "info for undocumented survivors" page * "info for survivors with children" page * "shelters in the area" page *The pages have all been made and stubbed out. As I find the information (from the researched sources explained below) for each of the topic pages, I will add the information to that page. The routing between pages has been done as well.* * UI design *With Swift the design is easy to do as I go. With each new page I was able to create the design. I will continue to complete it page-by-page.* *As I add the content to each topic page I will style it accordingly. I plan to keep every page as uniform/similar to the others as possible. Since this app is meant to be usable for as many different types of users as possible, the simplicity and usability is incredibly important.* * Research different sources to use to provide the information on the app * Poplulate the pages with this information *During the early stages of the project when I was deciding which topics to make pages in the main menu, I made sure each topic I wanted to include had enough information on a reliable site to include the topic. I kept all of these sources and will include them page-by-page for each of the topics.* * Find and Implement the language translation API *I have found the best-suited API for my app and plan to have it implemented by week eight, the latest it can be implemented is week ten.* *Since I am unfamiliar with Swift I am doing an online course which includes API implementation, so that should help me acomplish this task.* * Implement the emergency calling function *I have implemented the emergency calling function.* * First time users need to get the app-wide password * Then it can never be shown to them again *The logic for this needs to be implemented by week eleven/twelve.* *Since I am unfamiliar with Swift I am doing an online course which includes logic to identify first time users and route them accodingly, so that should help me acomplish this task.* * Unless they are a fist time user, users cannot get past the homescreen unless you input the correct password *The logic for this needs to be implemented by week eleven/twelve.* *Since I am unfamiliar with Swift I am doing an online course which includes logic to identify first time users and route them accodingly, so that should help me acomplish this task.* ### 4.4 Project Schedule This section provides schedule information for the PurpleRun project. ### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 4.4.1 PERT / GANTT Chart ![Gant chart](https://github.com/mackenzieTjogas/PurpleRun/blob/master/SDF/GANTTchart.png "GANTT Chart") ### &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 4.4.2 Task / Resource Table *Note: I did not include a "team" column here because this is an individual project so the value for each box in the column would have been me!* Task | Hardware | Software ------------------------------ | ------------- | ----------- UI Design | Macbook, iPhone | Atom, Xcode API implementation (1) | Macbook | Xcode, Chrome, Github Passwords: first-time users | Macbook | Xcode, Chrome, Github Find reliable sources | Macbook | Chrome Populate pages with info | Macbook | Xcode, Chrome, Github Frontend | Macbook, iPhone | Xcode, Chrome, Github Homepage block (w/o password)| Macbook | Xcode, Chrome, Github 911 call | Macbook | Xcode, Chrome, Github
b51be05f4189e871228bdc45e926a4cef364be6b
[ "Swift", "Markdown" ]
8
Swift
mackenzieTjogas/PurpleRun
152e35061d8109072f87354d8793e80d3f2ffb96
705579f0ecede8261f2f1794e82d5af202f4b219
refs/heads/main
<repo_name>DougHess/DSA-Labwork<file_sep>/DSA_Midterm/src/QueueSLS.java public class QueueSLS<T> implements ExtendedQueueInterface{ private Node<T> head; private Node<T> tail; protected int numitems; public QueueSLS() { head=null; tail=null; numitems =0; } @Override public boolean isEmpty() { boolean empty= true; if(numitems>0) { empty=false; } return empty; } @Override public void enqueue(Object newItem) throws QueueException { if (isEmpty()) { Node<T> n = new Node(newItem); head= n; tail=n; } else { Node<T> n = new Node(newItem); tail.setNext(n); tail= tail.getNext(); } numitems++; } @Override public Object dequeue() throws QueueException { if (isEmpty()) { throw new QueueException("no array"); } Object result = head.getItem(); head=head.getNext(); numitems--; return result; } @Override public void dequeueAll() { head=null; tail=null; numitems=0; } @Override public Object peek() throws QueueException { Object result = head.getItem(); return result; } @Override public void enqueueFirst(Object newItem) throws ExtendedQueueException { head = new Node(newItem, head); numitems++; } @Override public Object dequeueLast() throws ExtendedQueueException { if (isEmpty()) { throw new ExtendedQueueException("empty Queue"); } Object result = tail.getItem(); Node<T> n = head; while(!(n.getNext()==tail)) { n=n.getNext(); } tail=n; n.setNext(null); numitems--; return result; } @Override public Object peekLast() throws ExtendedQueueException { Object result= tail.getItem(); return result; } public String toString() { String s= ""; if (isEmpty()) { s="no queue"; } Node<T> n = head; for (int i = 0; i<numitems; i++) { s+=n.getItem()+", "; n=n.getNext(); } return s; } } <file_sep>/DSA_Lab4/src/Driver4.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Driver4 { static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public static void main(String args[]) throws IOException { MyListReferenceBased myArray = new MyListReferenceBased(); System.out.println("Select from the following menu\r\n" + " 1. Insert item to list.\r\n" + " 2. Remove item from list.\r\n" + " 3. Get item from list.\r\n" + " 4. Clear list.\r\n" + " 5. Print size and content of list.\r\n" + " 6. Delete largest item of list.\r\n" + " 7. Reverse list.\r\n" + " 8. Exit."); String s = in.readLine().trim(); while(!s.equals("8")) { if (s.equals("1")) { System.out.println("Enter item"); String item = in.readLine().trim(); System.out.println("Enter index"); String b = in.readLine().trim(); int index =Integer.parseInt(b); try { myArray.add(index, item); } catch (Exception e) { System.out.println(e.getMessage()); } System.out.println("Make selection now"); s = in.readLine().trim(); } else if (s.equals("2")) { System.out.println("Enter index"); String b = in.readLine().trim(); int x =Integer.parseInt(b); myArray.remove(x); System.out.println("Make selection now"); s = in.readLine().trim(); } else if (s.equals("3")) { System.out.println("Enter index"); String b = in.readLine().trim(); int x =Integer.parseInt(b); System.out.println(myArray.get(x)); System.out.println("Make selection now"); s = in.readLine().trim(); } else if (s.equals("4")) { System.out.println("List has been removed"); myArray.removeAll(); System.out.println("Make selection now"); s = in.readLine().trim(); } else if (s.equals("5")) { System.out.println("The Array has " + myArray.size()+" :"+myArray.toString()); System.out.println("Make selection now"); s = in.readLine().trim(); } else if (s.equals("6")) { myArray.deleteLL(); System.out.println("the largest string deleted"); s = in.readLine().trim(); } else if (s.equals("7")) { System.out.print(myArray.reverse()); System.out.println("List order has been revesed"); s = in.readLine().trim(); } } System.out.println("You have left the program goodbye"); } } <file_sep>/DSA_Lab5/src/StackRA.java public class StackRA<T> implements StackInterface<T>{ private T[] list; protected int top; public StackRA() { list =(T[]) new Object[3]; top=-1; } public boolean isEmpty() { boolean isempty=false; if(top ==-1) { isempty=true; } return isempty; } public void popAll() { list = (T[]) new Object[3]; top=-1; } protected void resize() { Object[] newlist = new Object[(list.length)*2]; for (int i=0;i<=top;i++) { newlist[i] = list[i]; } list = (T[]) newlist; } public void push(T item) throws StackException { if (top==list.length) { resize(); } list[++top]=item; } public T pop() throws StackException { Object o=list[top]; list[top--]=null; return (T) o; } public T peek() throws StackException { T result = (T) list[top]; return result; } public String toString() { String s=""; if (top==-1) { s="no array"; } else if(top==0) { s=list[0].toString(); } else if(top>0) { for(int i=top;i>=0;i--) { s+=list[i]+", "; } } return s; } } <file_sep>/DSA_lab7/src/Driver2.java /* * Recursive call for binomial coefficient */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Driver2 { static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public static void main(String args[]) throws IOException { String s= ""; while((s = in.readLine())!=null) { String d = in.readLine().trim(); int n = Integer.parseInt(s); int k = Integer.parseInt(d); //System.out.println(s+" "+d); System.out.println(rpascal(n,k)); } } public static int rpascal(int n, int k) { int result = 1; if(k==0||n==k) { result=1; } else { result = rpascal(n-1,k-1)+rpascal(n-1,k); } return result; } } <file_sep>/DSA_lab7/src/Driver5.java /* * formulaic Pascal non-reduced (no falling factorials) */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Driver5 { static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public static void main(String args[]) throws IOException { String s= ""; while((s = in.readLine())!=null) { String d = in.readLine().trim(); int n = Integer.parseInt(s); int k = Integer.parseInt(d); System.out.println(formulaicpascal(n,k)); } } public static int rfac(int n) { int result = 1; if (n==0) { result = 1; } else { result = n * rfac(n-1); } return result; } public static int formulaicpascal(int n, int k) { int result=1; int nf = rfac(n); int kf = rfac(k); int nkf = rfac(n-k); result = nf / (kf * nkf); return result; } } <file_sep>/DSA_Lab5/src/Lab5Driver2.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Lab5Driver2 { static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); static int numbagitems=0; static int bagweight=0; public static <T> void main(String args[]) throws IOException { StackInterface<Package> bag = new StackSLS<Package>(); StackInterface<Item> sample = new StackRA<Item>(); System.out.println("Select from the following menu\r\n" + " 0. Exit.\r\n" + " 1. Pick up an order.\r\n" + " 2. Drop off an order.\r\n" + " 3. Display number of packages and weight of bag.\r\n" + " 4. Display number of items in sample bag.\r\n" + " 5. enjoy an item form the samples.\r\n" + " 6. empty sample bag."); String s = in.readLine().trim(); while(!s.equals("0")) { switch(s) { case "1" : System.out.println("Enter item"); String item = in.readLine().trim(); System.out.println(item); System.out.println("Enter item weight"); String weight = in.readLine().trim(); System.out.println("weight"); System.out.println("Enter numer of items"); String num = in.readLine().trim(); System.out.println("num"); System.out.println("Enter name of sender"); String send = in.readLine().trim(); System.out.println(send); System.out.println("Enter name of recipient"); String rec = in.readLine().trim(); Package<T> i = new Package<T>((T)item, (T)weight, (T)num, (T)send, (T)rec); try { bag.push(i); numbagitems++; } catch(Exception e) { System.out.println(e.getMessage()); } System.out.println("Make selection now"); s = in.readLine().trim(); break; case"2": System.out.println("May I keep a sample?"); String keep = in.readLine().trim(); try { if (keep.equals('Y')) { sample.push(bag.pop()); numbagitems--; } else { bag.pop(); numbagitems--; } } catch(Exception e) { System.out.println(e.getMessage()); } System.out.println("Make selection now"); s = in.readLine().trim(); break; case "3": System.out.println("The Array has : "+numbagitems+" and a weight of" +bagweight(bag)); System.out.println("Make selection now"); s = in.readLine().trim(); break; case "4": System.out.println("The Array has :"+sample.toString()); System.out.println("The Array weighs :"); System.out.println("Make selection now"); s = in.readLine().trim(); break; case "5": System.out.println("List has been removed"); try { sample.pop(); } catch(Exception e) { System.out.println(e.getMessage()); } System.out.println("Make selection now"); s = in.readLine().trim(); break; case"6": System.out.println("List has been removed"); sample.popAll(); numbagitems=0; System.out.println("Make selection now"); s = in.readLine().trim(); break; } } System.out.println("You have left the program goodbye"); } public String toString(StackInterface list, int numitems) { StackInterface<Package> newlist = new StackRA<Package>(); newlist=list; Object[] item=new Object[numitems]; for(int i=0; i<numitems;i++) { item[i]= newlist.pop().getName(); } return item.toString(); } public static int bagweight(StackInterface list) { StackInterface<Package> newlist = new StackRA<Package>(); newlist=list; Object[] item=new Object[numbagitems]; for(int i=0; i<numbagitems;i++) { item[i]= newlist.pop().getweight(); bagweight+=(int)item[i]; } return bagweight; } } <file_sep>/DSA_Lab8/src/Driver1.java /* * Lab 8 problems 1 and 2 searching unordered lists. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; public class Driver1 { static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] agrs) throws IOException { System.out.println("Make your selection from the menu.\n" + "1. Insert item into the list.\n" + "2. Remove item from the list.\n" + "3. Get item from the list.\n" + "4. Search for an item in the list.\n" + "5. Clear the list.\n" + "6. Print size and content of the list.\n" + "7. Exit the program."); String s=in.readLine().trim(); System.out.println("You have selected: " + s); ArrayBasePlus list = new ArrayBasePlus(); while (!s.equals("7")) { switch(s) { case "1" : System.out.println("Enter item to be inserted"); String a=in.readLine().trim(); System.out.println("You have entered: " + a); System.out.println("Enter index to insert at"); String b = in.readLine().trim(); int i =Integer.parseInt(b); System.out.println("You have entered: " + i); list.add(i, a); System.out.println("You have added "+list.get(i)+" to index "+i); System.out.println("Make selection now"); s=in.readLine().trim(); System.out.println("You have selected: " + s); break; case "2" : System.out.println("Enter index to remove at"); String r = in.readLine().trim(); int j =Integer.parseInt(r); System.out.println("You have entered: " + j); System.out.println("Removing "+list.get(j)); list.remove(j); System.out.println("Make selection now"); s=in.readLine().trim(); System.out.println("You have selected: " + s); break; case "3" : System.out.println("Enter index to get item"); s = in.readLine().trim(); int x =Integer.parseInt(s); System.out.println("You have "+list.get(x)); System.out.println("Make selection now"); s=in.readLine().trim(); System.out.println("You have selected: " + s); break; case "4" : System.out.println("Enter item to be searched for"); s=in.readLine().trim(); System.out.println("Searching for: " + s); int k = search(s, list); if (k<0) { System.out.println("you have not found any matches"); } else if (k==list.size()) { System.out.println("you have found "+ list.get(0)+" at index 0"); } else { System.out.println("you have found "+ list.get(k)+" at index "+k); } System.out.println("Make selection now"); s=in.readLine().trim(); System.out.println("You have selected: " + s); break; case "6" : int size = 0; System.out.println("Prining list: "); for (int l =0; l <list.size(); l++) { System.out.println(list.get(l)+" "+size+++" "); } System.out.println("Make selection now"); s=in.readLine().trim(); System.out.println("You have selected: " + s); break; } } System.out.println("Goodbye"); } public static int search(String s, ArrayBasePlus o) { int found = -1; int result = 0; for (int i =0; i<o.size()&&found==-1; i++) { if (o.get(i).equals(s)) { result = i; found = 1; } } if(result == 0) { result = o.size(); } result = result * found; return result; } } <file_sep>/DSA_Lab5/src/Package.java public class Package<T> extends Item<T> { private T sender; private T reciever; private T amount; public Package(T weight, T name, T sender, T reciever, T amount) { super(weight, name); this.sender=sender; this.reciever=reciever; this.amount=amount; } public T getSender() { return sender; } public T getReciever() { return reciever; } public T getAmount() { return amount; } }<file_sep>/DSA_Lab4/src/MyListReferenceBased.java import java.util.Iterator; public class MyListReferenceBased implements ListInterface { private DNode tail; private int numitems; public MyListReferenceBased() { tail = null; numitems=0; } public MyListReferenceBased(DNode tail, int numitems) { this.tail=tail; this.numitems=numitems; } public boolean isEmpty() { return tail==null; } public int size() { return numitems; } public int oldsize() { int size =0; if (tail==null) { size =0; } else if (!(tail==null)){ size=1; DNode n =tail.getNext(); while(!(n==tail)) { size++; n=n.getNext(); } } return size; } protected DNode oldfind(int index) {//Inefficient DNode current = tail; for (int i =0; i<index;i++) { current=current.getNext(); } return current; } protected DNode find(int index) { DNode current = tail.getNext(); if (index==size()) { current=tail.getNext(); } else if (index <=size()/2) { for (int i =0; i<index;i++) { current=current.getNext(); } } else { int moddedindex = size() % index; for (int i =0; i<moddedindex;i++) { current=current.getBack(); } } return current; } protected boolean isValid(int index) { if (index>=0&&index<size()+1) { return true; } return false; } public Object get(int index) throws ListIndexOutOfBoundsException { if(isValid(index)) { DNode current =find(index); return current.getItem(); } throw new ListIndexOutOfBoundsException("out of bounds"); } public void oldadd(int index, Object item) throws ListIndexOutOfBoundsException {//broken if (isValid(index)) { if(index==0) { DNode newNode = new DNode(item); tail= newNode; } else { DNode prev = find(index-1); DNode newNode = new DNode(item, prev.getNext(), prev); prev.setNext(newNode); } numitems+=1; } else { throw new ListIndexOutOfBoundsException("cannot add to this index"); } } public void add(int index, Object item) throws ListIndexOutOfBoundsException { if (isValid(index)) { if (numitems==0) { tail= new DNode(item); } else { DNode prev= find(index-1); DNode newnode = new DNode(item, prev.getNext(), prev); prev.setNext(newnode); newnode.getNext().setBack(newnode); } numitems++; } else { throw new ListIndexOutOfBoundsException("cannot add to this index"); } } public void oldremove(int index) throws ListIndexOutOfBoundsException{//broken if(isValid(index)) { if(index==0) { tail=tail.getNext(); } find(index-1).setNext(find(index+1)); numitems-=1; } throw new ListIndexOutOfBoundsException("cannot remove from index"); } public void remove(int index) throws ListIndexOutOfBoundsException{ if(isValid(index)) { if (numitems==1) { tail=null; } else if(numitems==2) { DNode prev = find(index-1); prev.setNext(prev); } else { DNode prev= find(index-1); DNode n= prev.getNext().getNext(); prev.setNext(n); n.setBack(prev); } numitems--; } else { throw new ListIndexOutOfBoundsException("cannot remove from index"); } } public void removeAll() { tail = null; numitems=0; } public String oldtoString() { int size = size(); System.out.println(size); String s = "no array"; if (size ==1) { s=tail.getItem().toString(); } else if(size > 1) { DNode n = tail.getNext(); String a = n.getItem().toString()+", "; s=a; while (!(n.getNext()==n)) { a +=n.getNext().getItem().toString()+", "; s = a; n=n.getNext(); } } return s; } public String toString() { String array=""; if (numitems == 0) { array = "no array"; } else { DNode n = tail; for (int i=0; i<numitems; i++) { array += n.getItem().toString()+", "; n = n.getNext(); } } return array; } public void oldreverse() {//broken int size = size(); DNode last = find(size-1); if (size>1) { for (int i =size-1; i>0; i--) { last.setNext(find((size-1)-i)); } DNode n = find(size-1); n.setNext(null); } tail = last; System.out.println(size); } public String reverse() { String array=""; if (numitems == 0) { array = "no array"; } else { DNode n = tail; for (int i=0; i<numitems; i++) { array += n.getItem().toString()+", "; n = n.getBack(); } } return array; } public void deleteLL() { //this method deletes the first longest occurrence DNode n = tail; int size = size(); if (size==1) { tail = null; } else if (size>1){ int i; for (i=0; i<size;i++) { if (n.getItem().toString().compareTo(n.getNext().getItem().toString())<0) { n= n.getNext(); } } DNode prev = find(i-1); prev.setNext(n.getNext()); n=null; } } public int getNumitems() { return numitems; } public class LRBIterator implements Iterator<DNode>{ public boolean hasNext() { if (tail.getNext()==null) { return false; } return true; } public DNode next() { return tail.getNext(); } } }<file_sep>/DSA_Lab5/src/StackSLS.java public class StackSLS<T> implements StackInterface<T>{ private Node<T> top; public StackSLS() { top = null; } public boolean isEmpty() { boolean empty=false; if (top==null){ empty = true; } return empty; } public void popAll() { top=null; } public void push(T item) throws StackException { top = new Node(item, top); } public T pop() throws StackException { Object oldtop = top.getItem(); top=top.getNext(); return (T) oldtop; } public T peek() throws StackException { return top.getItem(); } public String toString() { String s=""; if (!(top==null)) { s+=(String) top.getItem(); Node<T> n = top.getNext(); while(!(n==null)) { s+=", "+n.getItem(); n=n.getNext(); } } return s; } } <file_sep>/DSA_Lab2/src/ListArrayListPlus.java import java.util.ArrayList; public class ListArrayListPlus extends ListArrayListBased { protected ArrayList<Object> newArray; public void reverse() { int j=0; for (int i=array.size(); i>=0;i--) { newArray.add(j++, array.get(i)); } array = newArray; } public String toString() { String s; if (array.isEmpty()) { s= "no array"; } else { s=", "; for(Object item : array){ s+=item.toString(); } } return s; } } <file_sep>/DSA_Lab11/src/Item.java public class Item <KT extends Comparable<? super KT>> extends KeyedItem<KT> { private String name; private int assocint; private boolean assocboolean; public Item(KT name) { super(name); this.name=(String) name; // TODO Auto-generated constructor stub } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAssocint() { return assocint; } public void setAssocint(int assocint) { this.assocint = assocint; } public boolean isAssocboolean() { return assocboolean; } public void setAssocboolean(boolean assocboolean) { this.assocboolean = assocboolean; } } <file_sep>/DSA_Midterm/src/DNode.java public class DNode { private Object item; private DNode next; private DNode back; public DNode(Object newItem) { item = newItem; next = this; setBack(this); } public DNode(Object newItem, DNode nextNode, DNode back) { item = newItem; next = nextNode; this.back=back; } public void setItem(Object newItem) { item = newItem; } public Object getItem() { return item; } public void setNext(DNode nextNode) { next = nextNode; } public DNode getNext() { return next; } public DNode getBack() { return back; } public void setBack(DNode back) { this.back = back; } } // end class Node <file_sep>/DSA_Midterm/src/DEQ.java public class DEQ<T> extends QueueRA<T> implements ExtendedQueueInterface{ @Override public void enqueueFirst(Object newItem) throws ExtendedQueueException { if(numitems==que.length) { resize(); } front=(front+que.length-1)%que.length; que[front]=newItem; numitems++; } @Override public Object dequeueLast() throws ExtendedQueueException { if(isEmpty()) { throw new ExtendedQueueException("Queue empty"); } back=(back+que.length-1)%que.length; Object result=que[back]; que[back]=null; return result; } @Override public Object peekLast() throws ExtendedQueueException { int temp=(back+que.length-1)%que.length; Object result=que[temp]; return result; } } <file_sep>/README.md # DSA-Labwork Lab work pertaining to data structure algorithms at Rowan University under Dr. <NAME>. <file_sep>/DSA_Lab2/src/ok.java public class ok { public static void main(String[] args) { char c='d'; int rank = Character.getNumericValue(c)-9; System.out.println(rank); } } <file_sep>/DSA_Lab12/src/Rank.java public class Rank { public int rank(char c) { c = Character.toUpperCase(c); int rank = c-'A'+1; return rank; } } <file_sep>/DSA_Lab2/src/Driver.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Driver { static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] agrs) throws IOException { ListArrayBased myArray = new ArrayBasePlus(); System.out.println("Select from the following menu\r\n" + " 0. Exit program.\r\n" + " 1. Insert item to list.\r\n" + " 2. Remove item from list.\r\n" + " 3. Get item from list.\r\n" + " 4. Clear list.\r\n" + " 5. Print size and content of list.\r\n" + " 6. Reverse list."); String s = in.readLine().trim(); while(!s.equals("0")) { if (s.equals("1")) { System.out.println("Enter item"); String a = in.readLine().trim(); System.out.println("Enter index"); String b = in.readLine().trim(); int x =Integer.parseInt(b); myArray.add(x, a); System.out.println("Make selection now"); s = in.readLine().trim(); } if (s.equals("2")) { System.out.println("Enter index"); String b = in.readLine().trim(); int x =Integer.parseInt(b); myArray.remove(x); System.out.println("Make selection now"); s = in.readLine().trim(); } if (s.equals("3")) { System.out.println("Enter index"); String b = in.readLine().trim(); int x =Integer.parseInt(b); myArray.get(x); System.out.println("Make selection now"); s = in.readLine().trim(); } if (s.equals("4")) { System.out.println("Are you sure you want to delete entire list? Y/N"); String b = in.readLine().trim(); if (b.equals("Y")){ myArray.removeAll(); System.out.println("Make selection now"); s = in.readLine().trim(); } System.out.println("Make selection now"); s = in.readLine().trim(); } if (s.equals("5")) { System.out.println("The Array has " + myArray.numItems+" :"+myArray.toString()); System.out.println("Make selection now"); s = in.readLine().trim(); } if (s.equals("6")) { ((ArrayBasePlus) myArray).reverse(); System.out.println("Make selection now"); s = in.readLine().trim(); } } } } <file_sep>/DSA_Lab11/src/Driver.java public class Driver { public static <T> void main(String args[]) { MyBinarySearchTree<Item<String>, ?> ahri = new MyBinarySearchTree(); Item a = new Item("apple"); Item b = new Item("orange"); Item c = new Item("grape"); Item d = new Item("pear"); ahri.insert(a); ahri.insert(b); ahri.insert(c); ahri.insert(d); System.out.println(ahri.retrieve("apple")); } } <file_sep>/DSA_Lab2/src/ListArrayListBased.java import java.util.ArrayList; public class ListArrayListBased implements ListInterface{ protected ArrayList<Object> array; protected int numItems; public ListArrayListBased() { array = new ArrayList<Object>(); numItems=0; } public int size() { return numItems; } public void add(int index, Object item) throws ListIndexOutOfBoundsException { array.add(index, item); numItems++; } public Object get(int index) throws ListIndexOutOfBoundsException { return array.get(index); } public void remove(int index) throws ListIndexOutOfBoundsException { array.remove(index); numItems--; } public void removeAll() { array=null; } public boolean isEmpty() { return (numItems == 0); } } <file_sep>/DSA_Lab9/src/Driver.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Driver { private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args) throws IOException { System.out.println("Enter number of ranks:"); String s = in.readLine().trim(); int i = Integer.parseInt(s); int array[] = new int[i]; int arrCopy[] = new int[i]; if (i != 0) { for (int j = 0; j < i; j++) { System.out.print("Please enter rank: "); String a = in.readLine().trim(); int k = Integer.parseInt(a); System.out.println(k); array[j] = k; } } System.out.println("\n"); System.out.println("Running Bubble Sort I:"); System.out.println(Arrays.toString(array)); arrCopy = Arrays.copyOf(array, i); array = bubbleSort(array); System.out.println(Arrays.toString(array)); System.out.println("\n"); array = Arrays.copyOf(arrCopy, i); System.out.println("Running Bubble Sort II:"); System.out.println(Arrays.toString(array)); arrCopy = Arrays.copyOf(array, i); System.out.println(Arrays.toString(bubbleSortII(array))); System.out.println("\n"); array = Arrays.copyOf(arrCopy, i); System.out.println("Running Selection Sort:"); System.out.println(Arrays.toString(array)); arrCopy = Arrays.copyOf(array, i); System.out.println(Arrays.toString(selectionSort(array))); System.out.println("\n"); array = Arrays.copyOf(arrCopy, i); System.out.println("Running Insertion Sort:"); System.out.println(Arrays.toString(array)); arrCopy = Arrays.copyOf(array, i); System.out.println(Arrays.toString(insertionSort(array))); System.out.println("\n"); array = Arrays.copyOf(arrCopy, i); } public static int[] selectionSort(int[] ahri) { int i = 0; int k = ahri.length - 1; int[] temp = new int[k + 1]; int comparison = 0; int swap = 0; for (i = 0; i <= k; i++) { while (k > i) { if (ahri[i] > ahri[k]) { temp[0] = ahri[k]; ahri[k] = ahri[i]; ahri[i] = temp[0]; ++swap; } ++comparison; k--; } k = ahri.length - 1; } System.out.println("swaps = " + swap + " comparisons = " + comparison); return ahri; } public static int[] bubbleSortII(int[] ahri) { int i = 0; int k = ahri.length - 1; int[] temp = new int[k + 1]; int comparison = 0; int swap = 0; int newSwaps = 0; for (i = 0; i <= k; i++) { while (k > i) { if (ahri[i] > ahri[k]) { temp[0] = ahri[k]; ahri[k] = ahri[i]; ahri[i] = temp[0]; ++swap; } ++comparison; k--; } if (swap==newSwaps) { break; } else {newSwaps=swap;} k = ahri.length - 1; } System.out.println("swaps = " + swap + " comparisons = " + comparison); return ahri; } public static int[] insertionSort(int[] ahri) { int k = ahri.length-1; int i = 0; int largestIndex = 0; int swap =0; int count =0; for ( ; k>=0;k--) { largestIndex=0; for (i =0; i<=k;i++) { count++; if (ahri[i]>ahri[largestIndex]) { largestIndex = i; swap++; } } int temp = ahri[k]; ahri[k]=ahri[largestIndex]; ahri[largestIndex]=temp; } System.out.println("shifts = "+swap+" comparisons = "+count); return ahri; } public static int[] bubbleSort(int[] ahri) { int i =0; int swap=0; int count=0; for (i = 1; i<ahri.length; i++) { for (int k = i; k>0;k--) { count++; if (ahri[k-1]>ahri[k]) { int temp = ahri[k-1]; ahri[k-1]=ahri[k]; ahri[k]= temp; swap++; } } } System.out.println("swaps = "+swap+" comparisons = "+count); return ahri; } }
65999d6759a4f43dd959087f68e3d0f94d755be2
[ "Markdown", "Java" ]
21
Java
DougHess/DSA-Labwork
f971fa9eedc68f7eafc5ce37a997b718f4454311
55a5fff14fd9525dfcd6d51721f35490c95ad660
refs/heads/master
<repo_name>uwburn/not-found-express<file_sep>/README.md # Not found middleware A simple Express middleware to return `HTTP 404 - Not found` when no route matches the request. ### Usage ```javascript var Express = require('express'); var notFoundExpress = require('not-found-express'); var express = Express(); express.use(notFoundExpress({ message: 'Not found' })); ``` ### Notes The message it's optional and will default to `Not found`. The error generated is an `http-error` and can be dealt by `http-error-express` (see related modules). <file_sep>/notFound.js var HttpError = require('http-error-prototype'); module.exports = function(options) { options = options || {}; options.message = options.message || 'Not found'; return function(req, res, next) { next(HttpError.notFound(options.message)); } }
78780c7035b763377446be6c9e2f0d8b073fe866
[ "Markdown", "JavaScript" ]
2
Markdown
uwburn/not-found-express
3190370aab28abef8250821c52f7c34599adbf3c
6fe4a70e97091cb7a7f6ed997113ef728ef258cd
refs/heads/master
<file_sep>################################################################################ # Automatically-generated file. Do not edit! ################################################################################ USER_OBJS := ../Tools/googletest-release-1.7.0/make/libgtest.a LIBS := <file_sep>/* * Counter.h * * Created on: Mar 14, 2016 * Author: asma */ #ifndef COUNTER_HPP_ #define COUNTER_HPP_ class Counter { private: int mCounter; public: Counter() : mCounter(0) {} int Increment(); }; #endif /* COUNTER_HPP_ */ <file_sep> # Google Test/Mock Cygwin Eclipse Starter - Instructions for Windows Users Basic template for C++ development using Google [Test](http://code.google.com/p/googletest/)/[Mock](http://code.google.com/p/googlemock/) and [Cygwin](https://cygwin.com/install.html) With [Eclipse-CDT](https://eclipse.org/cdt/downloads.php). ## Usage 1. Install [Cygwin](https://cygwin.com/install.html) as described in this [blog](http://www2.warwick.ac.uk/fac/sci/moac/people/students/peter_cock/cygwin/part2/) ![Alt text](doc/cygwinselectdevel.png?raw=true "Title") 2. Install latest [Eclipse-CDT](https://eclipse.org/cdt/downloads.php) 3. Download latest [Google-Test](https://github.com/google/googletest/releases) ### [Prepare Google-Test](http://stackoverflow.com/questions/3951808/using-googletest-in-eclipse-how) a. Open Cygwin (find the install directory for Cygwin and double-click on Cygwin.bat). b. Change the current working directory to the unzipped GoogleTest make directory: cd c:/<<yourpath>>/gtest-1.7.0/make/ c. Build the project: make d. Create an archived library out of the gtest-all.o file: ar -rv libgtest.a gtest-all.o 4. Clone this repository with `git clone ..` 5. Open the Project with Eclipse and configure the setting as in: ![Alt text](doc/gtest_include.png?raw=true "Title") ![Alt text](doc/gtest_lib.png?raw=true "Title") <file_sep>################################################################################ # Automatically-generated file. Do not edit! ################################################################################ # Add inputs and outputs from these tool invocations to the build variables CPP_SRCS += \ ../src/Counter.cpp C_SRCS += \ ../src/SquareRoot.c OBJS += \ ./src/Counter.o \ ./src/SquareRoot.o C_DEPS += \ ./src/SquareRoot.d CPP_DEPS += \ ./src/Counter.d # Each subdirectory must supply rules for building sources it contributes src/%.o: ../src/%.cpp @echo 'Building file: $<' @echo 'Invoking: Cygwin C++ Compiler' g++ -I"../Tools/googletest-release-1.7.0/include" -I"../src" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<" @echo 'Finished building: $<' @echo ' ' src/%.o: ../src/%.c @echo 'Building file: $<' @echo 'Invoking: Cygwin C Compiler' gcc -I"../Tools/googletest-release-1.7.0/include" -I"../src" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<" @echo 'Finished building: $<' @echo ' '
d44c2a763b6e9095a2264e6f0084202f7fb24446
[ "Markdown", "Makefile", "C++" ]
4
Makefile
essamabas/TestGTestCygwin
a662fe73272283f4ca18650f779607e4b47aaa9b
8bdc9af80a0de66f8f8a277435044c9e2cd5678f
refs/heads/master
<repo_name>anton1307/PO_const<file_sep>/PO_cosnt/Test Complete/Script/Unit1.js function Test1() { TestedApps.WF.Run(1, true); let form1 = Aliases.WF.Form1; let splitContainer = form1.splitContainer1.SplitterPanel.groupBox1.splitContainer2; let dataGridView = splitContainer.SplitterPanel.splitContainer3.SplitterPanel.dataGridView1; dataGridView.ClickCell(0, "ph"); let dataGridViewTextBoxEditingControl = dataGridView.Panel.DataGridViewTextBoxEditingControl; dataGridViewTextBoxEditingControl.Click(27, 8); dataGridViewTextBoxEditingControl.SetText("3,02"); dataGridViewTextBoxEditingControl.Keys("[Down]"); dataGridView.Keys("3"); dataGridViewTextBoxEditingControl.SetText("3,57"); dataGridViewTextBoxEditingControl.Keys("[Down]"); dataGridView.Keys("3"); dataGridViewTextBoxEditingControl.SetText("3,91"); dataGridViewTextBoxEditingControl.Keys("[Down]"); dataGridView.Keys("4"); dataGridViewTextBoxEditingControl.SetText("4,28"); dataGridViewTextBoxEditingControl.Keys("[Down]"); dataGridView.Keys("4"); dataGridViewTextBoxEditingControl.SetText("4,46"); dataGridViewTextBoxEditingControl.Keys("[Down]"); dataGridView.Keys("4"); dataGridViewTextBoxEditingControl.SetText("4,63"); dataGridView.DblClickCell(0, "Dx"); dataGridView.ClickCell(0, "Dx"); dataGridViewTextBoxEditingControl.Click(29, 1); dataGridViewTextBoxEditingControl.SetText("0,149"); dataGridViewTextBoxEditingControl.Keys("[Down]"); dataGridView.Keys("0"); dataGridViewTextBoxEditingControl.SetText("0,254"); dataGridViewTextBoxEditingControl.Keys("[Down]"); dataGridView.Keys("0"); dataGridViewTextBoxEditingControl.SetText("0,397"); dataGridViewTextBoxEditingControl.Keys("[Down]"); dataGridView.Keys("0"); dataGridViewTextBoxEditingControl.SetText("0,56"); dataGridViewTextBoxEditingControl.Keys("[Down]"); dataGridView.Keys("0"); dataGridViewTextBoxEditingControl.SetText("0,62"); dataGridViewTextBoxEditingControl.Keys("[Down]"); dataGridView.Keys("0"); dataGridViewTextBoxEditingControl.SetText("0,681"); splitContainer.SplitterPanel2.button1.ClickButton(); form1.Close(); }
145ea8234889176c15cbfbf64ba2870d54aa6492
[ "JavaScript" ]
1
JavaScript
anton1307/PO_const
a19db64c7587a5a0d58578656ab1b28d0416f5c8
ba1c6b13aebfbf984e35fa3600b170bd0c922b44
refs/heads/master
<file_sep># Ordometry Ordometry robot with error correction. Using an MD25 library. Have fun using, tweaking, improving on this code. It took me a while to get the error correction but I could have also used arduino's PID library. However a friend of mine tried this and it never came to fruition due to the difficulty of finding the correct constants for their specific system. Turned out hard coding was more time efficient. Enjoy. <file_sep>#include<Servo.h> #include <SoftwareSerial.h> #include <Wire.h> #define SOFTWAREREG 0x0D //Byte to read the software version. Values of 0 sent using 'write' have to be cast as a byte not to be misinterperted as NULL #define MD25ADDRESS 0x58 //Address of the MD25 #define CMD 0x10 //Byte to 'write' to the CMD #define SPEEDR 0x00 //Byte to send speed to first motor #define SPEEDL 0x01 //Byte to send speed to second motor #define ENCODER1 0x02 //Highest byte of motor encoder 1 #define ENCODER2 0x06 //Highest byte of motor encoder 2 #define VOLTREAD 0x0A //Byte to read battery volts #define RESETENCODERS 0x20 //Byte to reset encode registers to 0 #define ACCELERATION 0xE int pos3 = 0; //initialising position of servo //array of 2 leds int counter = 0; //counter initialiser long poss2 = Wire.read(); //reads the poss2 from the i2c Servo myservo; int ledPin12 = 12;//giving the servo a variable name void setup(){ myservo.attach(10); //attaching servo to pin 10 myservo.write(pos3); //sets up the servo to pos3 (0); Wire.begin(); //begin wire library delay(200); byte softVer = getSoft(); //byte to software version encodeReset(); Serial.begin(9600);//resetsEncoder at the start ledBlink(); pinMode(ledPin12, OUTPUT); } void encodeReset(){ //Function to set the encoder values to 0 Wire.beginTransmission(MD25ADDRESS); //MD25 address Wire.write(CMD); //'Write' to the CMD Wire.write(RESETENCODERS); //Reset the encode registers to 0 Wire.endTransmission(); } void accelerate() { Wire.beginTransmission(MD25ADDRESS); Wire.write(ACCELERATION); Wire.write(10); Wire.endTransmission(); } // //void decelerate(int d) { // long poss2 = encoder2(); // if(abs(poss2) > 0.5*abs(d)) { // // Wire.beginTransmission(MD25ADDRESS); // Wire.write(SPEEDR); // Wire.write(148); // Wire.endTransmission(); // // Wire.beginTransmission(MD25ADDRESS); // Wire.write(SPEEDL); // Wire.write(148); // Wire.endTransmission(); // delay(300); // } //} byte getSoft(){ //Function to get the software version Wire.beginTransmission(MD25ADDRESS); //MD25 address Wire.write(SOFTWAREREG); //Send byte to read software version as a single byte Wire.endTransmission(); Wire.requestFrom(MD25ADDRESS, 1); //Request one byte from MD25 while(Wire.available() < 1); //Wait for it to arrive byte software = Wire.read(); //Read it in return(software); } long encoder1(){ Wire.beginTransmission(MD25ADDRESS); //address of MD25 Wire.write(ENCODER1); //Send byte to read the position of encoder 1 Wire.endTransmission(); Wire.requestFrom(MD25ADDRESS, 4); //Requesting 4 bytes from MD25 while(Wire.available() < 4); //Wait for 4 bytes to arrive long poss1 = Wire.read(); //First byte for encoder 1, HH. poss1 <<= 8; poss1 += Wire.read(); //Second byte for encoder 1, HL poss1 <<= 8; poss1 += Wire.read(); //Third byte for encoder 1, LH poss1 <<= 8; poss1 +=Wire.read(); //Final byte for encoder 1, LL//Wait for everything to make sure everything is sent; return(poss1);//Return poss1 as a long } void ledBlink() { //led blink function over ten leds digitalWrite(ledPin12, HIGH); //led pin HIGH delay(100); digitalWrite(ledPin12, LOW); //led pin LOW delay(100); } long stopMotor(){ //Function to stop motors Wire.beginTransmission(MD25ADDRESS); //MD25 address Wire.write(SPEEDR); //'Write' to motor 1 Wire.write(128); //Send a value of 128 to motor 1 to stop it Wire.endTransmission(); Wire.beginTransmission(MD25ADDRESS); //MD25 address Wire.write(SPEEDL); //'Write' to motor 2 Wire.write(128); //Send a value of 128 to motor 2 to stop it Wire.endTransmission(); } void servo() { //runs the servo function and will be called within the loop counter++; //will count plus one every time servo is called if(counter % 1 == 0) { //if counter / 1 then add 34 degrees to servo pos3 = pos3 + 34; myservo.write(pos3); //new value of pos3. Servo modified delay(200); } } long encoder2(){ //Function to read and display value of encoder 2 as a long Wire.beginTransmission(MD25ADDRESS); //MD25 address Wire.write(ENCODER2); //Send byte to read the position of encoder 2 Wire.endTransmission(); Wire.requestFrom(MD25ADDRESS, 4); //Request 4 bytes from MD25 while(Wire.available() < 4); //Wait for 4 bytes to become available long poss2 = Wire.read(); //First byte for encoder 2, HH poss2 <<= 8; poss2 += Wire.read(); //Second byte for encoder 2, HL poss2 <<= 8; poss2 += Wire.read(); //Third byte for encoder 2, LH poss2 <<= 8; poss2 +=Wire.read();//Final byte for encoder 2, LL Serial.println(poss2); return(poss2); } void Rwheelforward(int R, int L, double d){//Function to drive motors forward, setting motor 1 speed to R, motor 2 speed to L and turning the wheels by d degrees encodeReset(); do { Wire.beginTransmission(MD25ADDRESS); //Start connection to MD25 for motor 1 (right wheel) Wire.write(SPEEDR); //'Write' to motor 1 Wire.write(R + 128); //Set right wheel to speed R + 128 (giving base as zero) Wire.endTransmission(); Wire.beginTransmission(MD25ADDRESS); //Start connection to MD25 for motor 2 (left wheel) Wire.write(SPEEDL); //'Write' to motor 2 Wire.write(L + 128); //Set left wheel to speed L + 128 (giving base as zero) Wire.endTransmission(); delay(50); }while(encoder2() < d); //while encoder if less than d perform above do statement otherwise go to next if statement below long poss4 = abs(encoder2())-abs(d); //correction code, if the enocder goes too far then it will call RwheelturnCorrect. if(poss4 > 0 && R < 0) { RwheelturnCorrect((R+(-1.5*R)), (L-((1.5)*L)), -d); stopMotor(); delay(50); } stopMotor(); //stops motor at the end of while loop. delay(50); } void RwheelturnCorrect(int R, int L, double d) { //uses the difference in values to correct itself. if(abs(encoder2()) - abs(d) > 0) { Wire.beginTransmission(MD25ADDRESS); //Start connection to MD25 for motor 1 (right wheel) Wire.write(SPEEDR); //'Write' to motor 1 Wire.write(R + 128); //Set right wheel to speed R + 128 (giving base as zero) Wire.endTransmission(); Wire.beginTransmission(MD25ADDRESS); //Start connection to MD25 for motor 2 (left wheel) Wire.write(SPEEDL); //'Write' to motor 2 Wire.write(L + 128); //Set left wheel to speed L + 128 (giving base as zero) Wire.endTransmission(); RwheelturnCorrect(R,L,d); //call function until statement is no longer true }else { stopMotor(); delay(200); } } void Rwheelbackward(int R, int L, double d){ //Function to drive motors backwards, setting motor 1 speed to R, motor 2 speed to L and turning the wheels by d degrees encodeReset(); do{ //acceleration(); // decelerate(d); Wire.beginTransmission(MD25ADDRESS); Wire.write(SPEEDR); //'Write' to motor 1 Wire.write(R + 128); //Set right wheel to speed R + 128 (giving base as zero) Wire.endTransmission(); Wire.beginTransmission(MD25ADDRESS); //Start connection to MD25 for motor 2 (left wheel) Wire.write(SPEEDL); //'Write' to motor 2 Wire.write(L + 128); //Set left wheel to speed L + 128 (giving base as zero) Wire.endTransmission(); delay(50); } while(encoder2() > d); //same error correction as above but for turning the other way long poss3 = abs(encoder2())-abs(d); if(poss3 > 0 && R > 0 && L < 0) { RwheelturnCorrect(-(0.5*R), -(0.5*L), -d); stopMotor(); delay(200); } stopMotor(); delay(200); } void Rwheelcorrect(int d) { //error correction for going forwards or backwards if(abs(encoder2())-abs(d) > 0) { Wire.beginTransmission(MD25ADDRESS); Wire.write(SPEEDR); Wire.write(120); Wire.endTransmission(); Wire.beginTransmission(MD25ADDRESS); Wire.write(SPEEDL); Wire.write(120); Wire.endTransmission(); Rwheelcorrect(d); stopMotor(); } } void RwheelcorrectBack(int d) { long poss2 = encoder2(); if(abs(poss2-d) > 0) { Wire.beginTransmission(MD25ADDRESS); Wire.write(SPEEDR); Wire.write(168); Wire.endTransmission(); Wire.beginTransmission(MD25ADDRESS); Wire.write(SPEEDL); Wire.write(168); Wire.endTransmission(); RwheelcorrectBack(d); stopMotor(); } } void arccorrect(int R, int L, int d) { //arc turn error correction which takes 3 parameters and reverses the error on arcs if(abs(encoder2()) - abs(d) > 0) { // same logic as above. If difference is greater than 0 perform logic. Wire.beginTransmission(MD25ADDRESS); Wire.write(SPEEDR); Wire.write(-(R)+128); Wire.endTransmission(); Wire.beginTransmission(MD25ADDRESS); Wire.write(SPEEDL); Wire.write(-(L)+128); Wire.endTransmission(); arccorrect(R, L, d); } stopMotor(); //else stopMotor() } void loop(){ //loops through all our functions delay(25); Rwheelforward(60, 60, 390); //0 to 1 delay(25); Rwheelcorrect(390); delay(25); ledBlink(); delay(25); Rwheelbackward(30,-30, -245); //turn at 1 delay(25); //light led Rwheelforward(60, 60, 298.2); //1 to 2 delay(25); Rwheelcorrect(298.2); delay(25); Rwheelforward(-30, 30, 245); //turn 2 delay(25); servo(); //drop m&m delay(25); ledBlink(); delay(25);//light led Rwheelforward(60, 60, 565); //2 to 3 delay(25); Rwheelcorrect(565); delay(25); ledBlink(); //light led delay(25); Rwheelforward(-30, 30, 245); //turn 3 delay(25); Rwheelforward(32, 10, 202); //arc 3 to 4 delay(25); arccorrect(32, 10, 202); //drop m&m delay(25); Rwheelforward(10,10,20); delay(25); Rwheelcorrect(20); delay(25); servo(); delay(50); Rwheelbackward(30,-30,-245); //turn 4 \ delay(50); ledBlink(); // light led delay(25); Rwheelforward(60, 60, 730); //4 to 5 delay(25); Rwheelcorrect(730); delay(25); ledBlink(); //light led Rwheelforward(-30, 30, 245); // turn 5 delay(25); Rwheelforward(50,50,458.8); delay(25); Rwheelcorrect(458.8); delay(25); servo(); ledBlink(); // led light up Rwheelbackward(-30,-30, 60); delay(25);//drop m&m Rwheelforward(-30, 30, 245); //turn at 6 delay(25); Rwheelforward(60, 60, 458.8); delay(25); Rwheelcorrect(458.8); //at 7 delay(25); Rwheelforward(-30, 30, 245); //turn 7 delay(25); Rwheelforward(60, 60, 458.8); //7 - 8 delay(25); Rwheelcorrect(458.8); delay(25); ledBlink(); //light led delay(25); servo(); //drop m&m delay(25); Rwheelforward(-30, 30, 115); //turn 8 delay(25); Rwheelforward(60, 60, 680); //8-9 delay(25); Rwheelcorrect(680); delay(25); Rwheelbackward(30, -30, -80); //turn 9 delay(25); Rwheelbackward(-30, -30, -210); //9-10 delay(25); ledBlink(); //light blink delay(25); servo(); //drop m&m delay(25); Rwheelbackward(40,-40, -245); //turn at 10 delay(25); Rwheelbackward(-10, -50, -1760); // 10 - 11 delay(25); Rwheelbackward(-10,-10,-10); delay(25); Rwheelbackward(40,-40, -90.6); //turn 11 delay(25); Rwheelforward(60,60,383.3); //11-12 delay(25); Rwheelcorrect(383.3); delay(25); ledBlink(); //12-13 Rwheelforward(60,60,453.2); //13-14 delay(25); Rwheelcorrect(453.2); delay(25); ledBlink(); //light led //delay(10000); //stopMotor(); }
f887f2e59184913b8d33d67b1a2908ca3c25b14d
[ "Markdown", "C++" ]
2
Markdown
lvh1g15/Ordometry
42f94003803df5d9aac69a175edd24559adb45e0
b9f61ad2741b6ccab1d2dde3543bc7d41eb2ee51
refs/heads/shirhatti/docfx
<repo_name>shirhatti/EntityFramework.Docs<file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Query/ExpressionTranslators/Internal/MyRelationalCompositeMethodCallTranslator.cs using Microsoft.EntityFrameworkCore.Query.ExpressionTranslators; using Microsoft.Extensions.Logging; namespace EntityFrameworkCore.RelationalProviderStarter.Query.ExpressionTranslators.Internal { public class MyRelationalCompositeMethodCallTranslator : RelationalCompositeMethodCallTranslator { public MyRelationalCompositeMethodCallTranslator(ILogger logger) : base(logger) { } } }<file_sep>/samples/Platforms/AspNetCore/AspNetCore.ExistingDb/Models/Blog.cs using System; using System.Collections.Generic; namespace EFGetStarted.AspNetCore.ExistingDb.Models { public partial class Blog { public Blog() { Post = new HashSet<Post>(); } public int BlogId { get; set; } public string Url { get; set; } public virtual ICollection<Post> Post { get; set; } } } <file_sep>/ef/modeling/relational/default-schema.md --- uid: modeling/relational/default-schema --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). Note: The configuration in this section is applicable to relational databases in general. The extension methods shown here will become available when you install a relational database provider (due to the shared *Microsoft.EntityFrameworkCore.Relational* package). # Default Schema The default schema is the database schema that objects will be created in if a schema is not explicitly configured for that object. ## Conventions By convention, the database provider will choose the most appropriate default schema. For example, Microsoft SQL Server will use the `dbo` schema and SQLite will not use a schema (since schemas are not supported in SQLite). ## Data Annotations You can not set the default schema using Data Annotations. ## Fluent API You can use the Fluent API to specify a default schema. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/FluentAPI/Samples/Relational/DefaultSchema.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [7], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasDefaultSchema("blogging"); } } ```` <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/ValueGeneration/MyValueGeneratorCache.cs using Microsoft.EntityFrameworkCore.ValueGeneration; namespace EntityFrameworkCore.RelationalProviderStarter.ValueGeneration { public class MyValueGeneratorCache : ValueGeneratorCache { } }<file_sep>/ef/miscellaneous/logging.md --- uid: miscellaneous/logging --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Logging Tip: You can view this article's [sample](https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/Miscellaneous/Logging) on GitHub. ## Create a logger The first step is to create an implementation of `ILoggerProvider` and `ILogger`. * `ILoggerProvider` is the component that decides when to create instances of your logger(s). The provider may choose to create different loggers in different situations. * `ILogger` is the component that does the actual logging. It will be passed information from the framework when certain events occur. Here is a simple implementation that logs a human readable representation of every event to a text file and the Console. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "csharp", "highlight_args": {"linenostart": 1}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/miscellaneous/Miscellaneous/Logging/Logging/MyLoggerProvider.cs"} --> ````csharp using Microsoft.Extensions.Logging; using System; using System.IO; namespace EFLogging { public class MyLoggerProvider : ILoggerProvider { public ILogger CreateLogger(string categoryName) { return new MyLogger(); } public void Dispose() { } private class MyLogger : ILogger { public bool IsEnabled(LogLevel logLevel) { return true; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { File.AppendAllText(@"C:\temp\log.txt", formatter(state, exception)); Console.WriteLine(formatter(state, exception)); } public IDisposable BeginScope<TState>(TState state) { return null; } } } } ```` Tip: The arguments passed to the Log method are: * `logLevel` is the level (e.g. Warning, Info, Verbose, etc.) of the event being logged * `eventId` is a library/assembly specific id that represents the type of event being logged * `state` can be any object that holds state relevant to what is being logged * `exception` gives you the exception that occurred if an error is being logged * `formatter` uses state and exception to create a human readable string to be logged ## Register your logger ### ASP.NET Core In an ASP.NET Core application, you register your logger in the Configure method of Startup.cs: <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "dupnames": [], "names": []} --> ```` public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddProvider(new MyLoggerProvider()); ... } ```` ### Other applications In your application startup code, create and instance of you context and register your logger. Note: You only need to register the logger with a single context instance. Once you have registered it, it will be used for all other instances of the context in the same AppDomain. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "csharp", "highlight_args": {"linenostart": 1}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/miscellaneous/Miscellaneous/Logging/Logging.ConsoleApp/Program.cs"} --> ````csharp using (var db = new BloggingContext()) { var serviceProvider = db.GetInfrastructure<IServiceProvider>(); var loggerFactory = serviceProvider.GetService<ILoggerFactory>(); loggerFactory.AddProvider(new MyLoggerProvider()); } ```` ## Filtering what is logged The easiest way to filter what is logged, is to adjust your logger provider to only return your logger for certain categories of events. For EF, the category passed to your logger provider will be the type name of the component that is logging the event. For example, here is a logger provider that returns the logger only for events related to executing SQL against a relational database. For all other categories of events, a null logger (which does nothing) is returned. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "csharp", "highlight_args": {"linenostart": 1, "hl_lines": [9, 10, 11, 12, 13, 17, 18, 19, 20, 21, 22]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/miscellaneous/Miscellaneous/Logging/Logging/MyFilteredLoggerProvider.cs"} --> ````csharp using Microsoft.Extensions.Logging; using System; using System.Linq; namespace EFLogging { public class MyFilteredLoggerProvider : ILoggerProvider { private static string[] _categories = { typeof(Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilderFactory).FullName, typeof(Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection).FullName }; public ILogger CreateLogger(string categoryName) { if( _categories.Contains(categoryName)) { return new MyLogger(); } return new NullLogger(); } public void Dispose() { } private class MyLogger : ILogger { public bool IsEnabled(LogLevel logLevel) { return true; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { Console.WriteLine(formatter(state, exception)); } public IDisposable BeginScope<TState>(TState state) { return null; } } private class NullLogger : ILogger { public bool IsEnabled(LogLevel logLevel) { return false; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { } public IDisposable BeginScope<TState>(TState state) { return null; } } } } ```` <file_sep>/ef/modeling/generated-properties.md --- uid: modeling/generated-properties --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Generated Properties ## Value Generation Patterns There are three value generation patterns that can be used for properties. ### No value generation No value generation means that you will always supply a valid value to be saved to the database. This valid value must be assigned to new entities before they are added to the context. ### Value generated on add Value generated on add means that a value is generated for new entities. Caution: How the value is generated for added entities will depend on the database provider being used. Database providers may automatically setup value generation for some property types, but others may require you to manually setup how the value is generated.For example, when using SQL Server, values will be automatically generated for *GUID* properties (using the SQL Server sequential GUID algorithm). However, if you specify that a *DateTime* property is generated on add, then you must setup a way for the values to be generated (such as setting default value SQL of *GETDATE()*, see [Default Values](relational/default-values.md)). If you add an entity to the context that has a value assigned to the primary key property, then EF will attempt to insert that value rather than generating a new one. A property is considered to have a value assigned if it is not assigned the CLR default value (`null` for `string`, `0` for `int`, `Guid.Empty` for `Guid`, etc.). Depending on the database provider being used, values may be generated client side by EF or in the database. If the value is generated by the database, then EF may assign a temporary value when you add the entity to the context. This temporary value will then be replaced by the database generated value during `SaveChanges`. ### Value generated on add or update Value generated on add or update means that a new value is generated every time the record is saved (insert or update). Caution: How the value is generated for added and updated entities will depend on the database provider being used. Database providers may automatically setup value generation for some property types, while others will require you to manually setup how the value is generated.For example, when using SQL Server, *byte[]* properties that are set as generated on add or update and marked as concurrency tokens, will be setup with the *rowversion* data type - so that values will be generated in the database. However, if you specify that a *DateTime* property is generated on add or update, then you must setup a way for the values to be generated (such as a database trigger). Like 'value generated on add', if you specify a value for the property on a newly added instance of an entity, that value will be inserted rather than a value being generated. Also, if you explicitly change the value assigned to the property (thus marking it as modified) then that new value will be set in the database rather than a value being generated. ## Conventions By convention, primary keys that are of an integer or GUID data type will be setup to have values generated on add. All other properties will be setup with no value generation. ## Data Annotations ### No value generation (Data Annotations) <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/DataAnnotations/Samples/ValueGeneratedNever.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [3], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# public class Blog { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int BlogId { get; set; } public string Url { get; set; } } ```` ### Value generated on add (Data Annotations) <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/DataAnnotations/Samples/ValueGeneratedOnAdd.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [5], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# public class Blog { public int BlogId { get; set; } public string Url { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public DateTime Inserted { get; set; } } ```` Caution: This just lets EF know that values are generated for added entities, it does not guarantee that EF will setup the actual mechanism to generate values. See [Value generated on add](#value-generated-on-add) section for more details. ### Value generated on add or update (Data Annotations) <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/DataAnnotations/Samples/ValueGeneratedOnAddOrUpdate.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [5], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# public class Blog { public int BlogId { get; set; } public string Url { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public DateTime LastUpdated { get; set; } } ```` Caution: This just lets EF know that values are generated for added or updated entities, it does not guarantee that EF will setup the actual mechanism to generate values. See [Value generated on add or update](#value-generated-on-add-or-update) section for more details. ## Fluent API You can use the Fluent API to change the value generation pattern for a given property. ### No value generation (Fluent API) <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/FluentAPI/Samples/ValueGeneratedNever.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [7, 8, 9], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .Property(b => b.BlogId) .ValueGeneratedNever(); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } } ```` ### Value generated on add (Fluent API) <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/FluentAPI/Samples/ValueGeneratedOnAdd.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [7, 8, 9], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .Property(b => b.Inserted) .ValueGeneratedOnAdd(); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public DateTime Inserted { get; set; } } ```` Caution: This just lets EF know that values are generated for added entities, it does not guarantee that EF will setup the actual mechanism to generate values. See [Value generated on add](#value-generated-on-add) section for more details. ### Value generated on add or update (Fluent API) <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/FluentAPI/Samples/ValueGeneratedOnAddOrUpdate.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [7, 8, 9], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .Property(b => b.LastUpdated) .ValueGeneratedOnAddOrUpdate(); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public DateTime LastUpdated { get; set; } } ```` Caution: This just lets EF know that values are generated for added or updated entities, it does not guarantee that EF will setup the actual mechanism to generate values. See [Value generated on add or update](#value-generated-on-add-or-update) section for more details. <file_sep>/ef/efcore-vs-ef6/side-by-side.md --- uid: efcore-vs-ef6/side-by-side --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # EF6.x and EF Core in the Same Application It is possible to use EF Core and EF6.x in the same application. EF Core and EF6.x have the same type names that differ only by namespace, so this may complicate code that attempts to use both EF Core and EF6.x in the same code file. If you are porting an existing application that has multiple EF models, then you can selectively port some of them to EF Core, and continue using EF6.x for the others. <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.ProviderStarter/Storage/MyTransactionManager.cs using System; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.Storage; namespace EntityFrameworkCore.ProviderStarter.Storage { public class MyTransactionManager : IDbContextTransactionManager { public IDbContextTransaction BeginTransaction() { throw new NotImplementedException(); } public Task<IDbContextTransaction> BeginTransactionAsync( CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public void CommitTransaction() { throw new NotImplementedException(); } public void RollbackTransaction() { throw new NotImplementedException(); } } }<file_sep>/ef/modeling/relational/data-types.md --- uid: modeling/relational/data-types --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). Note: The configuration in this section is applicable to relational databases in general. The extension methods shown here will become available when you install a relational database provider (due to the shared *Microsoft.EntityFrameworkCore.Relational* package). # Data Types Data type refers to the database specific type of the column to which a property is mapped. ## Conventions By convention, the database provider selects a data type based on the CLR type of the property. It also takes into account other metadata, such as the configured [Maximum Length](../max-length.md), whether the property is part of a primary key, etc. For example, SQL Server uses `datetime2(7)` for `DateTime` properties, and `nvarchar(max)` for `string` properties (or `nvarchar(450)` for `string` properties that are used as a key). ## Data Annotations You can use Data Annotations to specify an exact data type for the column. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/DataAnnotations/Samples/Relational/DataType.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [4], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# public class Blog { public int BlogId { get; set; } [Column(TypeName = "varchar(200)")] public string Url { get; set; } } ```` ## Fluent API You can use the Fluent API to specify an exact data type for the column. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/FluentAPI/Samples/Relational/DataType.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [7, 8, 9], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .Property(b => b.Url) .HasColumnType("varchar(200)"); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } } ```` If you are targeting more than one relational provider with the same model then you probably want to specify a data type for each provider rather than a global one to be used for all relational providers. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/FluentAPI/Samples/Relational/DataTypeForProvider.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [3], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# modelBuilder.Entity<Blog>() .Property(b => b.Url) .ForSqlServerHasColumnType("varchar(200)"); ```` <file_sep>/samples/Modeling/FluentAPI/Samples/Relationships/CompositePrincipalKey.cs using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; namespace EFModeling.Configuring.DataAnnotations.Samples.Relationships.CompositePrincipalKey { class MyContext : DbContext { public DbSet<Car> Cars { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<RecordOfSale>() .HasOne(s => s.Car) .WithMany(c => c.SaleHistory) .HasForeignKey(s => new { s.CarState, s.CarLicensePlate }) .HasPrincipalKey(c => new { c.State, c.LicensePlate }); } } public class Car { public int CarId { get; set; } public string State { get; set; } public string LicensePlate { get; set; } public string Make { get; set; } public string Model { get; set; } public List<RecordOfSale> SaleHistory { get; set; } } public class RecordOfSale { public int RecordOfSaleId { get; set; } public DateTime DateSold { get; set; } public decimal Price { get; set; } public string CarState { get; set; } public string CarLicensePlate { get; set; } public Car Car { get; set; } } } <file_sep>/ef/platforms/netcore/index.md --- uid: platforms/netcore/index --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Getting Started on .NET Core (Windows, OSX, Linux, etc.) These 101 tutorials require no previous knowledge of Entity Framework (EF) or Visual Studio. They will take you step-by-step through creating a simple application that queries and saves data from a database. EF can be used on all platforms (Windows, OSX, Linux, etc.) that support .NET Core. ## Available Tutorials * [.NET Core Application to New SQLite Database](new-db-sqlite.md) <file_sep>/ef/modeling/keys.md --- uid: modeling/keys --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Keys (primary) A key serves as the primary unique identifier for each entity instance. When using a relational database this maps to the concept of a *primary key*. You can also configure a unique identifier that is not the primary key (see [Alternate Keys](alternate-keys.md) for more information). ## Conventions By convention, a property named `Id` or `<type name>Id` will be configured as the key of an entity. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [3]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/Conventions/Samples/KeyId.cs"} --> ````c# class Car { public string Id { get; set; } public string Make { get; set; } public string Model { get; set; } } ```` <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [3]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/Conventions/Samples/KeyTypeNameId.cs"} --> ````c# class Car { public string CarId { get; set; } public string Make { get; set; } public string Model { get; set; } } ```` ## Data Annotations You can use Data Annotations to configure a single property to be the key of an entity. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [3, 4]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/DataAnnotations/Samples/KeySingle.cs"} --> ````c# class Car { [Key] public string LicensePlate { get; set; } public string Make { get; set; } public string Model { get; set; } } ```` ## Fluent API You can use the Fluent API to configure a single property to be the key of an entity. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [7, 8]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/FluentAPI/Samples/KeySingle.cs"} --> ````c# class MyContext : DbContext { public DbSet<Car> Cars { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Car>() .HasKey(c => c.LicensePlate); } } class Car { public string LicensePlate { get; set; } public string Make { get; set; } public string Model { get; set; } } ```` You can also use the Fluent API to configure multiple properties to be the key of an entity (known as a composite key). Composite keys can only be configured using the Fluent API - conventions will never setup a composite key and you can not use Data Annotations to configure one. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [7, 8]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/FluentAPI/Samples/KeyComposite.cs"} --> ````c# class MyContext : DbContext { public DbSet<Car> Cars { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Car>() .HasKey(c => new { c.State, c.LicensePlate }); } } class Car { public string State { get; set; } public string LicensePlate { get; set; } public string Make { get; set; } public string Model { get; set; } } ```` <file_sep>/ef/miscellaneous/testing.md --- uid: miscellaneous/testing --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Testing with InMemory This article covers how to use the InMemory provider to write efficient tests with minimal impact to the code being tested. Caution: Currently you need to use `ServiceCollection` and `IServiceProvider` to control the scope of the InMemory database, which adds complexity to your tests. In the next release after RC2, there will be improvements to make this easier, [see issue #3253](https://github.com/aspnet/EntityFramework/issues/3253) for more details. Tip: You can view this article's [sample](https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/Miscellaneous/Testing) on GitHub. ## When to use InMemory for testing The InMemory provider is useful when you want to test components using something that approximates connecting to the real database, without the overhead of actual database operations. For example, consider the following service that allows application code to perform some operations related to blogs. Internally it uses a `DbContext` that connects to a SQL Server database. It would be useful to swap this context to connect to an InMemory database so that we can write efficient tests for this service without having to modify the code, or do a lot of work to create a test double of the context. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "csharp", "highlight_args": {"linenostart": 1}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/miscellaneous/Miscellaneous/Testing/BusinessLogic/BlogService.cs"} --> ````csharp public class BlogService { private BloggingContext _context; public BlogService(BloggingContext context) { _context = context; } public void Add(string url) { var blog = new Blog { Url = url }; _context.Blogs.Add(blog); _context.SaveChanges(); } public IEnumerable<Blog> Find(string term) { return _context.Blogs .Where(b => b.Url.Contains(term)) .OrderBy(b => b.Url) .ToList(); } } ```` ### InMemory is not a relational database EF Core database providers do not have to be relational databases. InMemory is designed to be a general purpose database for testing, and is not designed to mimic a relational database. Some examples of this include: * InMemory will allow you to save data that would violate referential integrity constraints in a relational database. * If you use DefaultValueSql(string) for a property in your model, this is a relational database API and will have no effect when running against InMemory. Tip: For many test purposes these difference will not matter. However, if you want to test against something that behaves more like a true relational database, then consider using [SQLite in-memory mode](http://www.sqlite.org/inmemorydb.html). ## Get your context ready ### Avoid configuring two database providers In your tests you are going to externally configure the context to use the InMemory provider. If you are configuring a database provider by overriding `OnConfiguring` in your context, then you need to add some conditional code to ensure that you only configure the database provider if one has not already been configured. Note: If you are using ASP.NET Core, then you should not need this code since your database provider is configured outside of the context (in Startup.cs). <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "csharp", "highlight_args": {"linenostart": 1, "hl_lines": [3]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/miscellaneous/Miscellaneous/Testing/BusinessLogic/BloggingContext.cs"} --> ````csharp protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFProviders.InMemory;Trusted_Connection=True;"); } ```` ### Add a constructor for testing The simplest way to enable testing with the InMemory provider is to modify your context to expose a constructor that accepts a `DbContextOptions<TContext>`. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "csharp", "highlight_args": {"linenostart": 1, "hl_lines": [6, 7, 8]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/miscellaneous/Miscellaneous/Testing/BusinessLogic/BloggingContext.cs"} --> ````csharp public class BloggingContext : DbContext { public BloggingContext() { } public BloggingContext(DbContextOptions<BloggingContext> options) : base(options) { } ```` Note: `DbContextOptions<TContext>` tells the context all of its settings, such as which database to connect to. This is the same object that is built by running the OnConfiguring method in your context. ## Writing tests The key to testing with this provider is the ability to tell the context to use the InMemory provider, and control the scope of the in-memory database. Typically you want a clean database for each test method. `DbContextOptions<TContext>` exposes a `UseInternalServiceProvider` method that allows us to control the `IServiceProvider` the context will use. `IServiceProvider` is the container that EF will resolve all its services from (including the InMemory database instance). Typically, EF creates a single `IServiceProvider` for all contexts of a given type in an AppDomain - meaning all context instances share the same InMemory database instance. By allowing one to be passed in, you can control the scope of the InMemory database. Here is an example of a test class that uses the InMemory database. Each test method creates a new `DbContextOptions<TContext>` with a new `IServiceProvider`, meaning each method has its own InMemory database. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "csharp", "highlight_args": {"linenostart": 1}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/miscellaneous/Miscellaneous/Testing/TestProject/BlogServiceTests.cs"} --> ````csharp using BusinessLogic; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Linq; namespace TestProject { [TestClass] public class BlogServiceTests { private static DbContextOptions<BloggingContext> CreateNewContextOptions() { // Create a fresh service provider, and therefore a fresh // InMemory database instance. var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); // Create a new options instance telling the context to use an // InMemory database and the new service provider. var builder = new DbContextOptionsBuilder<BloggingContext>(); builder.UseInMemoryDatabase() .UseInternalServiceProvider(serviceProvider); return builder.Options; } [TestMethod] public void Add_writes_to_database() { // All contexts that share the same service provider will share the same InMemory database var options = CreateNewContextOptions(); // Run the test against one instance of the context using (var context = new BloggingContext(options)) { var service = new BlogService(context); service.Add("http://sample.com"); } // Use a separate instance of the context to verify correct data was saved to database using (var context = new BloggingContext(options)) { Assert.AreEqual(1, context.Blogs.Count()); Assert.AreEqual("http://sample.com", context.Blogs.Single().Url); } } [TestMethod] public void Find_searches_url() { // All contexts that share the same service provider will share the same InMemory database var options = CreateNewContextOptions(); // Insert seed data into the database using one instance of the context using (var context = new BloggingContext(options)) { context.Blogs.Add(new Blog { Url = "http://sample.com/cats" }); context.Blogs.Add(new Blog { Url = "http://sample.com/catfish" }); context.Blogs.Add(new Blog { Url = "http://sample.com/dogs" }); context.SaveChanges(); } // Use a clean instance of the context to run the test using (var context = new BloggingContext(options)) { var service = new BlogService(context); var result = service.Find("cat"); Assert.AreEqual(2, result.Count()); } } } } ```` ## Sharing a database instance for read-only tests If a test class has read-only tests that share the same seed data, then you can share the InMemory database instance for the whole class (rather than a new one for each method). This means you have a single `DbContextOptions<TContext>` and `IServiceProvider` for the test class, rather than one for each test method. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "csharp", "highlight_args": {"linenostart": 1}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/miscellaneous/Miscellaneous/Testing/TestProject/BlogServiceTestsReadOnly.cs"} --> ````csharp using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.Extensions.DependencyInjection; using BusinessLogic; using Microsoft.EntityFrameworkCore; using System.Linq; using System; namespace TestProject { [TestClass] public class BlogServiceTestsReadOnly { private DbContextOptions<BloggingContext> _contextOptions; public BlogServiceTestsReadOnly() { // Create a service provider to be shared by all test methods var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); // Create options telling the context to use an // InMemory database and the service provider. var builder = new DbContextOptionsBuilder<BloggingContext>(); builder.UseInMemoryDatabase() .UseInternalServiceProvider(serviceProvider); _contextOptions = builder.Options; // Insert the seed data that is expected by all test methods using (var context = new BloggingContext(_contextOptions)) { context.Blogs.Add(new Blog { Url = "http://sample.com/cats" }); context.Blogs.Add(new Blog { Url = "http://sample.com/catfish" }); context.Blogs.Add(new Blog { Url = "http://sample.com/dogs" }); context.SaveChanges(); } } [TestMethod] public void Find_with_empty_term() { using (var context = new BloggingContext(_contextOptions)) { var service = new BlogService(context); var result = service.Find(""); Assert.AreEqual(3, result.Count()); } } [TestMethod] public void Find_with_unmatched_term() { using (var context = new BloggingContext(_contextOptions)) { var service = new BlogService(context); var result = service.Find("horse"); Assert.AreEqual(0, result.Count()); } } [TestMethod] public void Find_with_some_matched() { using (var context = new BloggingContext(_contextOptions)) { var service = new BlogService(context); var result = service.Find("cat"); Assert.AreEqual(2, result.Count()); } } } } ```` <file_sep>/samples/Querying/Querying/Tracking/Sample.cs using Microsoft.EntityFrameworkCore; using System.Linq; namespace EFQuerying.Tracking { public class Sample { public static void Run() { using (var context = new BloggingContext()) { var blog = context.Blogs.SingleOrDefault(b => b.BlogId == 1); blog.Rating = 5; context.SaveChanges(); } using (var context = new BloggingContext()) { var blogs = context.Blogs .AsNoTracking() .ToList(); } using (var context = new BloggingContext()) { context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; var blogs = context.Blogs.ToList(); } using (var context = new BloggingContext()) { var blog = context.Blogs .Select(b => new { Blog = b, Posts = b.Posts.Count() }); } using (var context = new BloggingContext()) { var blog = context.Blogs .Select(b => new { Id = b.BlogId, Url = b.Url }); } } } } <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Storage/MyRelationalDatabase.cs using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Update; namespace EntityFrameworkCore.RelationalProviderStarter.Storage { public class MyRelationalDatabase : RelationalDatabase { public MyRelationalDatabase(IQueryCompilationContextFactory queryCompilationContextFactory, ICommandBatchPreparer batchPreparer, IBatchExecutor batchExecutor, IRelationalConnection connection) : base(queryCompilationContextFactory, batchPreparer, batchExecutor, connection) { } } }<file_sep>/ef/modeling/required-optional.md --- uid: modeling/required-optional --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Required/optional properties A property is considered optional if it is valid for it to contain `null`. If `null` is not a valid value to be assigned to a property then it is considered to be a required property. ## Conventions By convention, a property whose CLR type can contain null will be configured as optional (`string`, `int?`, `byte[]`, etc.). Properties whose CLR type cannot contain null will be configured as required (`int`, `decimal`, `bool`, etc.). Note: A property whose CLR type cannot contain null cannot be configured as optional. The property will always be considered required by Entity Framework. ## Data Annotations You can use Data Annotations to indicate that a property is required. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/DataAnnotations/Samples/Required.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [4], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# public class Blog { public int BlogId { get; set; } [Required] public string Url { get; set; } } ```` ## Fluent API You can use the Fluent API to indicate that a property is required. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/FluentAPI/Samples/Required.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [7, 8, 9], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .Property(b => b.Url) .IsRequired(); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } } ```` <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.ProviderStarter/Storage/MyDatabaseCreator.cs using System; using System.Threading; using System.Threading.Tasks; using EntityFrameworkCore.ProviderStarter.Infrastructure; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage; namespace EntityFrameworkCore.ProviderStarter.Storage { public class MyDatabaseCreator : IDatabaseCreator { private MyProviderOptionsExtension _myOptions; public MyDatabaseCreator(IDbContextOptions options) { _myOptions = options.FindExtension<MyProviderOptionsExtension>(); } public bool EnsureCreated() { throw new NotImplementedException(); } public Task<bool> EnsureCreatedAsync(CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public bool EnsureDeleted() { throw new NotImplementedException(); } public Task<bool> EnsureDeletedAsync(CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } } }<file_sep>/samples/Saving/Saving/ExplicitValuesGenerateProperties/Employee.cs using System; namespace EFSaving.ExplicitValuesGenerateProperties { public class Employee { public int EmployeeId { get; set; } public string Name { get; set; } public DateTime EmploymentStarted { get; set; } } } <file_sep>/ef/efcore-vs-ef6/choosing.md --- uid: efcore-vs-ef6/choosing --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Which One Is Right for You The following information will help you choose between Entity Framework Core and Entity Framework 6.x. ## What is EF6.x Entity Framework 6.x (EF6.x) is a tried and tested data access technology with many years of features and stabilization. It first released in 2008, as part of .NET Framework 3.5 SP1 and Visual Studio 2008 SP1. Starting with the EF4.1 release it has shipped as the [EntityFramework NuGet package](https://www.nuget.org/packages/EntityFramework/) - currently the most popular package on NuGet.org. EF6.x continues to be a supported product, and will continue to see bug fixes and minor improvements for some time to come. ## What is EF Core Entity Framework Core (EF Core) is a lightweight, extensible, and cross-platform version of Entity Framework. EF Core introduces many improvements and new features when compared with EF6.x. At the same time, EF Core is a new code base and very much a v1 product. EF Core keeps the developer experience from EF6.x, and most of the top-level APIs remain the same too, so EF Core will feel very familiar to folks who have used EF6.x. At the same time, EF Core is built over a completely new set of core components. This means EF Core doesn't automatically inherit all the features from EF6.x. Some of these features will show up in future releases (such as lazy loading and connection resiliency), other less commonly used features will not be implemented in EF Core. The new, extensible, and lightweight core has also allowed us to add some features to EF Core that will not be implemented in EF6.x (such as alternate keys and mixed client/database evaluation in LINQ queries). See [Feature Comparison](features.md) for a detailed comparison of how the feature set in EF Core compares to EF6.x. ## Guidance for new applications Because EF Core is a new product, and still lacks some critical O/RM features, EF6.x will still be the most suitable choice for many applications. These are the types of applications we would recommend using EF Core for. * New applications that do not require features that are not yet implemented in EF Core. Review [Feature Comparison](features.md) to see if EF Core may be a suitable choice for your application. * Applications that target .NET Core, such as Universal Windows Platform (UWP) and ASP.NET Core applications. These applications can not use EF6.x as it requires the Full .NET Framework (i.e. .NET Framework 4.5). ## Guidance for existing EF6.x applications Because of the fundamental changes in EF Core we do not recommend attempting to move an EF6.x application to EF Core unless you have a compelling reason to make the change. If you want to move to EF Core to make use of new features, then make sure you are aware of its limitations before you start. Review [Feature Comparison](features.md) to see if EF Core may be a suitable choice for your application. **You should view the move from EF6.x to EF Core as a port rather than an upgrade.** See [Porting from EF6.x to EF Core](porting/index.md) for more information. <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Infrastructure/MyModelSource.cs using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal; namespace EntityFrameworkCore.RelationalProviderStarter.Infrastructure { public class MyModelSource : ModelSource { public MyModelSource(IDbSetFinder setFinder, ICoreConventionSetBuilder coreConventionSetBuilder, IModelCustomizer modelCustomizer, IModelCacheKeyFactory modelCacheKeyFactory) : base(setFinder, coreConventionSetBuilder, modelCustomizer, modelCacheKeyFactory) { } } }<file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Storage/MyRelationalConnection.cs using System; using System.Data.Common; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.Logging; namespace EntityFrameworkCore.RelationalProviderStarter.Storage { public class MyRelationalConnection : RelationalConnection { public MyRelationalConnection(IDbContextOptions options, ILogger logger) : base(options, logger) { } protected override DbConnection CreateDbConnection() { throw new NotImplementedException(); } } }<file_sep>/samples/Miscellaneous/Internals/WritingAProvider/README.md Entity Framework Core Sample Provider ===================================== Templated project for creating a new provider for [Entity Framework Core](https://github.com/aspnet/EntityFramework). See the EF Core wiki for a guide on [Writing an EF Provider](https://github.com/aspnet/EntityFramework/wiki/Writing-an-EF7-Provider). Use the MyGet feed (found in Nuget.config) to download EF Core Prerelease. <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.ProviderStarter/Query/ExpressionVisitors/MyEntityQueryableExpressionVisitorFactory.cs using System.Linq.Expressions; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors; using Remotion.Linq.Clauses; namespace EntityFrameworkCore.ProviderStarter.Query.ExpressionVisitors { public class MyEntityQueryableExpressionVisitorFactory : IEntityQueryableExpressionVisitorFactory { public ExpressionVisitor Create(EntityQueryModelVisitor queryModelVisitor, IQuerySource querySource) => new MyEntityQueryableExpressionVisitor(queryModelVisitor, querySource); } }<file_sep>/samples/Modeling/FluentAPI/Samples/Relationships/ManyToMany.cs using Microsoft.EntityFrameworkCore; using System.Collections.Generic; namespace EFModeling.Configuring.FluentAPI.Samples.Relationships.ManyToMany { class MyContext : DbContext { public DbSet<Post> Posts { get; set; } public DbSet<Tag> Tags { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<PostTag>() .HasKey(t => new { t.PostId, t.TagId }); modelBuilder.Entity<PostTag>() .HasOne(pt => pt.Post) .WithMany(p => p.PostTags) .HasForeignKey(pt => pt.PostId); modelBuilder.Entity<PostTag>() .HasOne(pt => pt.Tag) .WithMany(t => t.PostTags) .HasForeignKey(pt => pt.TagId); } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public List<PostTag> PostTags { get; set; } } public class Tag { public string TagId { get; set; } public List<PostTag> PostTags { get; set; } } public class PostTag { public int PostId { get; set; } public Post Post { get; set; } public string TagId { get; set; } public Tag Tag { get; set; } } } <file_sep>/ef/modeling/relational/unique-constraints.md --- uid: modeling/relational/unique-constraints --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). Note: The configuration in this section is applicable to relational databases in general. The extension methods shown here will become available when you install a relational database provider (due to the shared *Microsoft.EntityFrameworkCore.Relational* package). # Alternate Keys (Unique Constraints) A unique constraint is introduced for each alternate key in the model. ## Conventions By convention, the index and constraint that are introduced for an alternate key will be named `AK_<type name>_<property name>`. For composite alternate keys `<property name>` becomes an underscore separated list of property names. ## Data Annotations Unique constraints can not be configured using Data Annotations. ## Fluent API You can use the Fluent API to configure the index and constraint name for an alternate key. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/FluentAPI/Samples/Relational/AlternateKeyName.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [9], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Car> Cars { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Car>() .HasAlternateKey(c => c.LicensePlate) .HasName("AlternateKey_LicensePlate"); } } class Car { public int CarId { get; set; } public string LicensePlate { get; set; } public string Make { get; set; } public string Model { get; set; } ```` <file_sep>/ef/modeling/inheritance.md --- uid: modeling/inheritance --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Inheritance Inheritance in the EF model is used to control how inheritance in the entity classes is represented in the database. ## Conventions By convention, it is up to the database provider to determine how inheritance will be represented in the database. See [Inheritance (Relational Database)](relational/inheritance.md) for how this is handled with a relational database provider. EF will only setup inheritance if two or more inherited types are explicitly included in the model. EF will not scan for base or derived types that were not otherwise included in the model. You can include types in the model by exposing a *DbSet<TEntity>* for each type in the inheritance hierarchy. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [3, 4]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/Conventions/Samples/InheritanceDbSets.cs"} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<RssBlog> RssBlogs { get; set; } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } } public class RssBlog : Blog { public string RssUrl { get; set; } } ```` If you don't want to expose a *DbSet<TEntity>* for one or more entities in the hierarchy, you can use the Fluent API to ensure they are included in the model. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [7]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/Conventions/Samples/InheritanceModelBuilder.cs"} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<RssBlog>(); } } ```` ## Data Annotations You cannot use Data Annotations to configure inheritance. ## Fluent API The Fluent API for inheritance depends on the database provider you are using. See [Inheritance (Relational Database)](relational/inheritance.md) for the configuration you can perform for a relational database provider. <file_sep>/ef/efcore-vs-ef6/porting/toc.md # [Ensure EF Core Will Work for Your Application](ensure-requirements.md) # [Porting an EDMX-Based Model (Model First & Database First)](port-edmx.md) # [Porting a Code-Based Model (Code First & Code First to Existing Database)](port-code.md) <file_sep>/ef/modeling/relational/tables.md --- uid: modeling/relational/tables --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). Note: The configuration in this section is applicable to relational databases in general. The extension methods shown here will become available when you install a relational database provider (due to the shared *Microsoft.EntityFrameworkCore.Relational* package). # Table Mapping Table mapping identifies which table data should be queried from and saved to in the database. ## Conventions By convention, each entity will be setup to map to a table with the same name as the `DbSet<TEntity>` property that exposes the entity on the derived context. If no `DbSet<TEntity>` is included for the given entity, the class name is used. ## Data Annotations You can use Data Annotations to configure the table that a type maps to. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/DataAnnotations/Samples/Relational/Table.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [1], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# [Table("blogs")] public class Blog { public int BlogId { get; set; } public string Url { get; set; } } ```` You can also specify a schema that the table belongs to. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/DataAnnotations/Samples/Relational/TableAndSchema.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [1], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# [Table("blogs", Schema = "blogging")] public class Blog { public int BlogId { get; set; } public string Url { get; set; } } ```` ## Fluent API You can use the Fluent API to configure the table that a type maps to. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/FluentAPI/Samples/Relational/Table.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [7, 8], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .ToTable("blogs"); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } } ```` You can also specify a schema that the table belongs to. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/FluentAPI/Samples/Relational/TableAndSchema.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [2], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# modelBuilder.Entity<Blog>() .ToTable("blogs", schema: "blogging"); ```` <file_sep>/samples/Modeling/Conventions/Samples/Relationships/OneToOne.cs using Microsoft.EntityFrameworkCore; using System.Collections.Generic; namespace EFModeling.Conventions.Samples.Relationships.OneToOne { class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<BlogImage> BlogImages { get; set; } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public BlogImage BlogImage { get; set; } } public class BlogImage { public int BlogImageId { get; set; } public byte[] Image { get; set; } public string Caption { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } } } <file_sep>/ef/modeling/max-length.md --- uid: modeling/max-length --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Maximum Length Configuring a maximum length provides a hint to the data store about the appropriate data type to use for a given property. Maximum length only applies to array data types, such as `string` and `byte[]`. Note: Entity Framework does not do any validation of maximum length before passing data to the provider. It is up to the provider or data store to validate if appropriate. For example, when targeting SQL Server, exceeding the maximum length will result in an exception as the data type of the underlying column will not allow excess data to be stored. ## Conventions By convention, it is left up to the database provider to choose an appropriate data type for properties. For properties that have a length, the database provider will generally choose a data type that allows for the longest length of data. For example, Microsoft SQL Server will use `nvarchar(max)` for `string` properties (or `nvarchar(450)` if the column is used as a key). ## Data Annotations You can use the Data Annotations to configure a maximum length for a property. In this example, targeting SQL Server this would result in the `nvarchar(500)` data type being used. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [4]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/DataAnnotations/Samples/MaxLength.cs"} --> ````c# public class Blog { public int BlogId { get; set; } [MaxLength(500)] public string Url { get; set; } } ```` ## Fluent API You can use the Fluent API to configure a maximum length for a property. In this example, targeting SQL Server this would result in the `nvarchar(500)` data type being used. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [7, 8, 9]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/FluentAPI/Samples/MaxLength.cs"} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .Property(b => b.Url) .HasMaxLength(500); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } } ```` <file_sep>/ef/platforms/full-dotnet/index.md --- uid: platforms/full-dotnet/index --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Getting Started on Full .NET (Console, WinForms, WPF, etc.) These 101 tutorials require no previous knowledge of Entity Framework (EF) or Visual Studio. They will take you step-by-step through creating a simple application that queries and saves data from a database. Entity Framework can create a model based on an existing database, or create a database for you based on your model. The following tutorials will demonstrate both of these approaches using a Console Application. You can use the techniques learned in these tutorials in any application that targets Full .NET, including WPF and WinForms. ## Available Tutorials * [Console Application to New Database](new-db.md) * [Console Application to Existing Database (Database First)](existing-db.md) <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.ProviderStarter/Storage/MyDatabase.cs using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Update; namespace EntityFrameworkCore.ProviderStarter.Storage { public class MyDatabase : Database { public MyDatabase(IQueryCompilationContextFactory queryCompilationContextFactory) : base(queryCompilationContextFactory) { } public override int SaveChanges(IReadOnlyList<IUpdateEntry> entries) { throw new NotImplementedException(); } public override Task<int> SaveChangesAsync(IReadOnlyList<IUpdateEntry> entries, CancellationToken cancellationToken = new CancellationToken()) { throw new NotImplementedException(); } } }<file_sep>/ef/efcore-vs-ef6/porting/ensure-requirements.md --- uid: efcore-vs-ef6/porting/ensure-requirements --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Ensure EF Core Will Work for Your Application Before you start the porting process it is important to validate that EF Core meets the data access requirements for your application. ## Missing features Make sure that EF Core has all the features you need to use in your application. See [Feature Comparison](../features.md) for a detailed comparison of how the feature set in EF Core compares to EF6.x. If any required features are missing, ensure that you can compensate for the lack of these features before porting to EF Core. ## Behavior changes This is a non-exhaustive list of some changes in behavior between EF6.x and EF Core. It is important to keep these in mind as your port your application as they may change the way your application behaves, but will not show up as compilation errors after swapping to EF Core. ### DbSet.Add/Attach and graph behavior In EF6.x, calling `DbSet.Add()` on an entity results in a recursive search for all entities referenced in its navigation properties. Any entities that are found, and are not already tracked by the context, are also be marked as added. `DbSet.Attach()` behaves the same, except all entities are marked as unchanged. EF Core performs a similar recursive search, but with some slightly different rules. * The root entity is always in the requested state (added for `DbSet.Add` and unchanged for `DbSet.Attach`). * For entities that are found during the recursive search of navigation properties: * If the primary key of the entity is store generated * If the primary key is not set to a value, the state is set to added. The primary key value is considered "not set" if it is assigned the CLR default value for the property type (i.e. `0` for `int`, `null` for `string`, etc.). * If the primary key is set to a value, the state is set to unchanged. * If the primary key is not database generated, the entity is put in the same state as the root. ### Code First database initialization EF6.x has a significant amount of magic it performs around selecting the database connection and initializing the database. Some of these rules include: * If no configuration is performed, EF6.x will select a database on SQL Express or LocalDb. * If a connection string with the same name as the context is in the applications `App/Web.config` file, this connection will be used. * If the database does not exist, it is created. * If none of the tables from the model exist in the database, the schema for the current model is added to the database. If migrations are enabled, then they are used to create the database. * If the database exists and EF6.x had previously created the schema, then the schema is checked for compatibility with the current model. An exception is thrown if the model has changed since the schema was created. EF Core does not perform any of this magic. * The database connection must be explicitly configured in code. * No initialization is performed. You must use `DbContext.Database.Migrate()` to apply migrations (or `DbContext.Database.EnsureCreated()` and `EnsureDeleted()` to create/delete the database without using migrations). ### Code First table naming convention EF6.x runs the entity class name through a pluralization service to calculate the default table name that the entity is mapped to. EF Core uses the name of the `DbSet` property that the entity is exposed in on the derived context. If the entity does not have a `DbSet` property, then the class name is used. <file_sep>/samples/Modeling/FluentAPI/Samples/Relational/SequenceConfigured.cs using Microsoft.EntityFrameworkCore; namespace EFModeling.Configuring.FluentAPI.Samples.Relational.SequenceConfigured { class MyContext : DbContext { public DbSet<Order> Orders { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasSequence<int>("OrderNumbers", schema: "shared") .StartsAt(1000) .IncrementsBy(5); } } public class Order { public int OrderId { get; set; } public int OrderNo { get; set; } public string Url { get; set; } } } <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Query/ExpressionTranslators/Internal/MyRelationalCompositeMemberTranslator.cs using Microsoft.EntityFrameworkCore.Query.ExpressionTranslators; namespace EntityFrameworkCore.RelationalProviderStarter.Query.ExpressionTranslators.Internal { public class MyRelationalCompositeMemberTranslator : RelationalCompositeMemberTranslator { } }<file_sep>/ef/miscellaneous/internals/writing-a-provider.md --- uid: miscellaneous/internals/writing-a-provider --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Writing a Database Provider EF Core is designed to be extensible. It provides general purpose building blocks that are intended for use in multiple providers. The purpose of this article is to provide basic guidance on creating a new provider that is compatible with EF Core. Tip: [EF Core source code is open-source](https://github.com/aspnet/EntityFramework). The best source of information is the code itself. Tip: This article shows snippets from an empty EF provider. You can view the [full stubbed-out provider](https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/Miscellaneous/Internals/WritingAProvider) on GitHub. <a name=entry-point></a> ## DbContext Initialization A user's interaction with EF begins with the `DbContext` constructor. Before the context is available for use, it initializes **options** and **services**. We will example both of these to understand what they represent and how EF configures itself to use different providers. ### Options `Microsoft.EntityFrameworkCore.Infrastructure.DbContextOptions` is the API surface for **users** to configure `DbContext`. Provider writers are responsible for creating API to configure options and to make services responsive to these options. For example, most providers require a connection string. These options are typically created using `DbContextOptionsBuilder`. ### Services `System.IServiceProvider` is the main interface used for interaction with services. EF makes heavy use of [dependency injection (DI)](https://wikipedia.org/wiki/Dependency_injection). The `ServiceProvider` contains a collection of services available for injection. Initialization uses `DbContextOptions` to add additional services if needed and select a scoped set of services that all EF operations will use during execution. See also [Understanding EF Services](services.md). Note: EF uses [Microsoft.Extensions.DependencyInjection](https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection/) to implement dependency injection. Documentation for this project [is available on docs.asp.net](https://docs.asp.net/en/latest/fundamentals/dependency-injection.html). ## Plugging in a Provider As explained above, EF uses options and services. Each provider must create API so users to add provider-specific options and services. This API is best created by using extension methods. Tip: When defining an extension method, define it in the namespace of the object being extended so Visual Studio auto-complete will include the extension method as a possible completion. ### The *Use* Method By convention, providers define a `UseX()` extension on `DbContextOptionsBuilder`. This configures **options** which it typically takes as arguments to method. <!-- literal_block {"xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "ids": []} --> ```` optionsBuilder.UseMyProvider("Server=contoso.com") ```` The `UseX()` extension method creates a provider-specific implementation of `IDbContextOptionsExtension` which is added to the collection of extensions stored within `DbContextOptions`. This is done by a call to the API `IDbContextOptionsBuilderInfrastructure.AddOrUpdateExtension`. An example implementation of the "Use" method <!-- literal_block {"language": "csharp", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/miscellaneous/internals/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.ProviderStarter/Extensions/MyProviderDbContextOptionsExtensions.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ````csharp public static class MyProviderDbContextOptionsExtensions { public static DbContextOptionsBuilder UseMyProvider(this DbContextOptionsBuilder optionsBuilder, string connectionString) { ((IDbContextOptionsBuilderInfrastructure) optionsBuilder).AddOrUpdateExtension( new MyProviderOptionsExtension { ConnectionString = connectionString }); return optionsBuilder; } } ```` Tip: The `UseX()` method can also be used to return a special wrapper around `DbContextOptionsBuilder` that allows users to configure multiple options with chained calls. See `SqlServerDbContextOptionsBuilder` as an example. ### The *Add* Method By convention, providers define a `AddX()` extension on `EntityFrameworkServicesBuilder`. This configures **services** and does not take arguments. `EntityFrameworkServicesBuilder` is a wrapper around `ServiceCollection` which is accessible by calling `GetInfrastructure()`. The `AddX()` method should register services in this collection to be available for dependency injection. In some cases, users may call the *Add* method directly. This is done when users are configuring a service provider manually and use this service provider to resolve an instance of `DbContext`. In other cases, the *Add* method is called by EF upon service initialization. For more details on service initialization, see [Understanding EF Services](services.md). A provider *must register* an implementation of `IDatabaseProvider`. Implementing this in-turn requires configuring several more required services. Read more about working with services in [Understanding EF Services](services.md). EF provides many complete or partial implementations of the required services to make it easier for provider-writers. For example, EF includes a class `DatabaseProvider<TProviderServices, TOptionsExtension>` which can be used in service registration to hook up a provider. An example implementation of the "Add" method <!-- literal_block {"language": "csharp", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/miscellaneous/internals/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.ProviderStarter/Extensions/MyProviderServiceCollectionExtensions.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ````csharp public static class MyProviderServiceCollectionExtensions { public static IServiceCollection AddEntityFrameworkMyProvider(this IServiceCollection services) { services.AddEntityFramework(); services.TryAddEnumerable(ServiceDescriptor .Singleton<IDatabaseProvider, DatabaseProvider<MyDatabaseProviderServices, MyProviderOptionsExtension>>()); services.TryAdd(new ServiceCollection() // singleton services .AddSingleton<MyModelSource>() .AddSingleton<MyValueGeneratorCache>() // scoped services .AddScoped<MyDatabaseProviderServices>() .AddScoped<MyDatabaseCreator>() .AddScoped<MyDatabase>() .AddScoped<MyEntityQueryableExpressionVisitorFactory>() .AddScoped<MyEntityQueryModelVisitorFactory>() .AddScoped<MyQueryContextFactory>() .AddScoped<MyTransactionManager>()); return services; } } ```` ## Next Steps With these two extensibility APIs now defined, users can now configure their "DbContext" to use your provider. To make your provider functional, you will need to implement other services. Reading the source code of other providers is an excellent way to learn how to create a new EF provider. See [Database Providers](../../providers/index.md) for a list of current EF providers and to find links to their source code (if applicable). `Microsoft.EntityFrameworkCore.Relational` includes an extensive library of services designed for relational providers. In many cases, these services need little or no modification to work for multiple relational databases. For more information on other internal parts of EF, see [Internals](index.md). <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Infrastructure/MyRelationalProviderOptionsExtension.cs using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; namespace EntityFrameworkCore.RelationalProviderStarter.Infrastructure { public class MyRelationalProviderOptionsExtension : IDbContextOptionsExtension { public string ConnectionString { get; set; } public void ApplyServices(IServiceCollection services) { services.AddMyRelationalProvider(); } } }<file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Storage/MyRelationalSqlGenerationHelper.cs using Microsoft.EntityFrameworkCore.Storage; namespace EntityFrameworkCore.RelationalProviderStarter.Storage { public class MyRelationalSqlGenerationHelper : RelationalSqlGenerationHelper { } }<file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Update/MyModificationCommandBatchFactory.cs using System; using Microsoft.EntityFrameworkCore.Update; namespace EntityFrameworkCore.RelationalProviderStarter.Update { public class MyModificationCommandBatchFactory : IModificationCommandBatchFactory { public ModificationCommandBatch Create() { throw new NotImplementedException(); } } }<file_sep>/samples/Modeling/FluentAPI/Samples/KeySingle.cs using Microsoft.EntityFrameworkCore; namespace EFModeling.Configuring.FluentAPI.Samples.KeySingle { class MyContext : DbContext { public DbSet<Car> Cars { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Car>() .HasKey(c => c.LicensePlate); } } class Car { public string LicensePlate { get; set; } public string Make { get; set; } public string Model { get; set; } } } <file_sep>/ef/platforms/full-dotnet/toc.md # [Console Application to New Database](new-db.md) # [Console Application to Existing Database (Database First)](existing-db.md) <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.ProviderStarter/Infrastructure/MyProviderOptionsExtension.cs using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; namespace EntityFrameworkCore.ProviderStarter.Infrastructure { public class MyProviderOptionsExtension : IDbContextOptionsExtension { public string ConnectionString { get; set; } public void ApplyServices(IServiceCollection builder) { builder.AddEntityFrameworkMyProvider(); } } }<file_sep>/ef/modeling/relational/columns.md --- uid: modeling/relational/columns --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). Note: The configuration in this section is applicable to relational databases in general. The extension methods shown here will become available when you install a relational database provider (due to the shared *Microsoft.EntityFrameworkCore.Relational* package). # Column Mapping Column mapping identifies which column data should be queried from and saved to in the database. ## Conventions By convention, each property will be setup to map to a column with the same name as the property. ## Data Annotations You can use Data Annotations to configure the column to which a property is mapped. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/DataAnnotations/Samples/Relational/Column.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [3], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# public class Blog { [Column("blog_id")] public int BlogId { get; set; } public string Url { get; set; } } ```` ## Fluent API You can use the Fluent API to configure the column to which a property is mapped. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/FluentAPI/Samples/Relational/Column.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [7, 8, 9], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .Property(b => b.BlogId) .HasColumnName("blog_id"); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } } ```` <file_sep>/ef/platforms/uwp/index.md --- uid: platforms/uwp/index --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Getting Started on Universal Windows Platform (UWP) These 101 tutorials require no previous knowledge of Entity Framework (EF) or Visual Studio. They will take you step-by-step through creating a simple application that queries and saves data from a database. Entity Framework can be used to access a local SQLite database in Universal Windows Platform applications. ## Available Tutorials * [Local SQLite on UWP](getting-started.md) <file_sep>/ef/efcore-vs-ef6/features.md --- uid: efcore-vs-ef6/features --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Feature Comparison The following information will help you choose between Entity Framework Core and Entity Framework 6.x. ## Features not in EF Core This is a list of features not currently implemented in EF Core that are likely to impact your ability to use it in a given application. This is by no means an exhaustive list of possible O/RM features, but the features that we feel have the highest impact on developers. * Creating a Model * **Complex/value types** are types that do not have a primary key and are used to represent a set of properties on an entity type. * **Visualizing a model** to see a graphical representation of the code-based model. * **Simple type conversions** such as string => xml. * **Spatial data types** such as SQL Server's *geography* & *geometry*. * **Many-to-many relationships** without join entity. You can already model a many-to-many relationship with a join entity, see [Relationships](../modeling/relationships.md) for details. * **Alternate inheritance mapping patterns** for relational databases, such as table per type (TPT) and table per concrete type (TPC). Table per hierarchy (TPH) is already supported. * Querying Data * **Improved translation** to enable more queries to successfully execute, with more logic being evaluated in the database (rather than in-memory). * **GroupBy translation** in particular will move translation of the LINQ GroupBy operator to the database, rather than in-memory. * **Lazy loading** enables navigation properties to be automatically populated from the database when they are accessed. * **Explicit Loading** allows you to trigger population of a navigation property on an entity that was previously loaded from the database. * **Raw SQL queries for non-model types** allows a raw SQL query to be used to populate types that are not part of the model (typically for denormalized view-model data). * Saving Data * **Simple command interception** provides an easy way to read/write commands before/after they are sent to the database. * **Missing EntityEntry APIs from EF6.x** such as `Reload`, `GetModifiedProperties`, `GetDatabaseValues` etc. * **Stored procedure mapping** allows EF to use stored procedures to persist changes to the database (`FromSql` already provides good support for using a stored procedure to query, see [Raw SQL Queries](../querying/raw-sql.md) for details). * **Connection resiliency** automatically retries failed database commands. This is especially useful when connection to SQL Azure, where transient failures are common. * Database Schema Management * **Visual Studio wizard for reverse engineer** that allows you to visually configure connection, select tables, etc. when creating a model from an existing database. * **Update model from database** allows a model that was previously reverse engineered from the database to be refreshed with changes made to the schema. * **Seed data** allows a set of data to be easily upserted to the database. ## Side-by-side comparison The following table compares the features available in EF Core and EF6.x. It is intended to give a high level comparison and does not list every feature, or attempt to give details on possible differences between how the same feature works. <!-- Creating a Model EF6.x EF Core 1.0.0 Basic modelling (classes, properties, etc.) Yes Yes Conventions Yes Yes Custom conventions Yes Partial Data annotations Yes Yes Fluent API Yes Yes Inheritance: Table per hierarchy (TPH) Yes Yes Inheritance: Table per type (TPT) Yes Inheritance: Table per concrete class (TPC) Yes Shadow state properties Yes Alternate keys Yes Many-to-many: With join entity Yes Yes Many-to-many: Without join entity Yes Key generation: Database Yes Yes Key generation: Client Yes Complex/value types Yes Spatial data Yes Graphical visualization of model Yes Graphical drag/drop editor Yes Model format: Code Yes Yes Model format: EDMX (XML) Yes Reverse engineer model from database: Command line Yes Reverse engineer model from database: VS wizard Yes Incremental update model from database Yes Querying Data EF6.x EF Core 1.0.0 LINQ: Simple queries Stable Stable LINQ: Moderate queries Stable Stabilizing LINQ: Complex queries Stable In-Progress LINQ: Queries using navigation properties Stable In-Progress "Pretty" SQL generation Poor Yes Mixed client/server evaluation Yes Loading related data: Eager Yes Yes Loading related data: Lazy Yes Loading related data: Explicit Yes Raw SQL queries: Model types Yes Yes Raw SQL queries: Un-mapped types Yes Raw SQL queries: Composing with LINQ Yes Saving Data EF6.x EF Core 1.0.0 SaveChanges Yes Yes Change tracking: Snapshot Yes Yes Change tracking: Notification Yes Yes Accessing tracked state Yes Partial Optimistic concurrency Yes Yes Transactions Yes Yes Batching of statements Yes Stored procedure Yes Detached graph support (N-Tier): Low level APIs Poor Yes Detached graph support (N-Tier): End-to-end Poor Other Features EF6.x EF Core 1.0.0 Migrations Yes Yes Database creation/deletion APIs Yes Yes Seed data Yes Connection resiliency Yes Lifecycle hooks (events, command interception, ...) Yes Database Providers EF6.x EF Core 1.0.0 SQL Server Yes Yes MySQL Yes Paid only, unpaid coming soon 1 PostgreSQL Yes Yes Oracle Yes Paid only, unpaid coming soon 1 SQLite Yes Yes SQL Compact Yes Yes DB2 Yes Yes InMemory (for testing) Yes Azure Table Storage Prototype Redis Prototype Application Models EF6.x EF Core 1.0.0 WinForms Yes Yes WPF Yes Yes Console Yes Yes ASP.NET Yes Yes ASP.NET Core Yes Xamarin Coming soon 2 UWP Yes --> Footnotes: * ^1 Paid providers are available, unpaid providers are being worked on. The teams working on the unpaid providers have not shared public details of timeline etc. * ^2 EF Core is built to work on Xamarin when support for .NET Standard is enabled in Xamarin. <file_sep>/samples/Modeling/DataAnnotations/Samples/Concurrency.cs using Microsoft.EntityFrameworkCore; using System.ComponentModel.DataAnnotations; namespace EFModeling.Configuring.DataAnnotations.Samples.Concurrency { class MyContext : DbContext { public DbSet<Person> People { get; set; } } public class Person { public int PersonId { get; set; } [ConcurrencyCheck] public string LastName { get; set; } public string FirstName { get; set; } } } <file_sep>/ef/modeling/relational/index.md --- uid: modeling/relational/index --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). Note: The configuration in this section is applicable to relational databases in general. The extension methods shown here will become available when you install a relational database provider (due to the shared *Microsoft.EntityFrameworkCore.Relational* package). # Relational Database Modeling This section covers aspects of modeling that are specific to relational databases. * [Table Mapping](tables.md) * [Column Mapping](columns.md) * [Data Types](data-types.md) * [Primary Keys](primary-keys.md) * [Default Schema](default-schema.md) * [Computed Columns](computed-columns.md) * [Sequences](sequences.md) * [Default Values](default-values.md) * [Indexes](indexes.md) * [Foreign Key Constraints](fk-constraints.md) * [Alternate Keys (Unique Constraints)](unique-constraints.md) * [Inheritance (Relational Database)](inheritance.md) <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.ProviderStarter/Storage/MyDatabaseProviderServices.cs using System; using EntityFrameworkCore.ProviderStarter.Infrastructure; using EntityFrameworkCore.ProviderStarter.Query; using EntityFrameworkCore.ProviderStarter.Query.ExpressionVisitors; using EntityFrameworkCore.ProviderStarter.ValueGeneration; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.ValueGeneration; namespace EntityFrameworkCore.ProviderStarter.Storage { public class MyDatabaseProviderServices : DatabaseProviderServices { public MyDatabaseProviderServices(IServiceProvider services) : base(services) { } public override string InvariantName => "MyProvider"; public override IDatabaseCreator Creator => GetService<MyDatabaseCreator>(); public override IDatabase Database => GetService<MyDatabase>(); public override IEntityQueryableExpressionVisitorFactory EntityQueryableExpressionVisitorFactory => GetService<MyEntityQueryableExpressionVisitorFactory>(); public override IEntityQueryModelVisitorFactory EntityQueryModelVisitorFactory => GetService<MyEntityQueryModelVisitorFactory>(); public override IModelSource ModelSource => GetService<MyModelSource>(); public override IQueryContextFactory QueryContextFactory => GetService<MyQueryContextFactory>(); public override IDbContextTransactionManager TransactionManager => GetService<MyTransactionManager>(); public override IValueGeneratorCache ValueGeneratorCache => GetService<MyValueGeneratorCache>(); } }<file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Extensions/MyRelationalProviderServiceCollectionExtensions.cs using EntityFrameworkCore.RelationalProviderStarter.Infrastructure; using EntityFrameworkCore.RelationalProviderStarter.Metadata; using EntityFrameworkCore.RelationalProviderStarter.Migrations; using EntityFrameworkCore.RelationalProviderStarter.Query.ExpressionTranslators.Internal; using EntityFrameworkCore.RelationalProviderStarter.Query.Sql; using EntityFrameworkCore.RelationalProviderStarter.Storage; using EntityFrameworkCore.RelationalProviderStarter.Update; using EntityFrameworkCore.RelationalProviderStarter.ValueGeneration; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection.Extensions; namespace Microsoft.Extensions.DependencyInjection { public static class MyRelationalProviderServiceCollectionExtensions { public static IServiceCollection AddMyRelationalProvider(this IServiceCollection services) { services.AddRelational(); services.TryAddEnumerable(ServiceDescriptor .Singleton <IDatabaseProvider, DatabaseProvider<MyRelationalDatabaseProviderServices, MyRelationalProviderOptionsExtension>>()); services.TryAdd(new ServiceCollection() // all singleton services .AddSingleton<MyValueGeneratorCache>() .AddSingleton<MyRelationalAnnotationProvider>() .AddSingleton<MyRelationalCompositeMemberTranslator>() .AddSingleton<MyRelationalCompositeMethodCallTranslator>() .AddSingleton<MyRelationalSqlGenerationHelper>() .AddSingleton<MyModelSource>() // all scoped services .AddScoped<MyRelationalDatabaseCreator>() .AddScoped<MyRelationalDatabaseProviderServices>() .AddScoped<MyHistoryRepository>() .AddScoped<MyModificationCommandBatchFactory>() .AddScoped<MyQuerySqlGeneratorFactory>() .AddScoped<MyRelationalConnection>() .AddScoped<MyRelationalDatabaseCreator>() .AddScoped<MyUpdateSqlGenerator>()); return services; } } }<file_sep>/samples/Querying/Querying/RelatedData/Sample.cs using Microsoft.EntityFrameworkCore; using System.Linq; namespace EFQuerying.RelatedData { public class Sample { public static void Run() { using (var context = new BloggingContext()) { var blogs = context.Blogs .Include(blog => blog.Posts) .ToList(); } using (var context = new BloggingContext()) { var blogs = context.Blogs .Include(blog => blog.Posts) .Select(blog => new { Id = blog.BlogId, Url = blog.Url }) .ToList(); } using (var context = new BloggingContext()) { var blogs = context.Blogs .Include(blog => blog.Posts) .Include(blog => blog.Owner) .ToList(); } using (var context = new BloggingContext()) { var blogs = context.Blogs .Include(blog => blog.Posts) .ThenInclude(post => post.Author) .ToList(); } using (var context = new BloggingContext()) { var blogs = context.Blogs .Include(blog => blog.Posts) .ThenInclude(post => post.Author) .ThenInclude(author => author.Photo) .ToList(); } using (var context = new BloggingContext()) { var blogs = context.Blogs .Include(blog => blog.Posts) .ThenInclude(post => post.Author) .ThenInclude(author => author.Photo) .Include(blog => blog.Owner) .ThenInclude(owner => owner.Photo) .ToList(); } using (var context = new BloggingContext()) { var blog = context.Blogs .Single(b => b.BlogId == 1); context.Posts .Where(p => p.BlogId == blog.BlogId) .Load(); } } } } <file_sep>/ef/providers/npgsql/index.md --- uid: providers/npgsql/index --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Npgsql (PostgreSQL) This database provider allows Entity Framework Core to be used with PostgreSQL. The provider is maintained as part of the [Npgsql project](http://www.npgsql.org). Note: This provider is not maintained as part of the Entity Framework Core project. When considering a third party provider, be sure to evaluate quality, licensing, support, etc. to ensure they meet your requirements. ## Install Install the [Npgsql.EntityFrameworkCore.PostgreSQL NuGet package](https://www.nuget.org/packages/Npgsql.EntityFrameworkCore.PostgreSQL). <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": false, "dupnames": [], "language": "text", "highlight_args": {}, "names": []} --> ````text PM> Install-Package Npgsql.EntityFrameworkCore.PostgreSQL ```` ## Get Started See the [Npgsql documentation](http://www.npgsql.org/doc/efcore.html) to get started. ## Supported Database Engines * PostgreSQL ## Supported Platforms * Full .NET (4.5.1 onwards) * .NET Core * Mono (4.2.0 onwards) <file_sep>/ef/miscellaneous/cli/dotnet.md --- uid: miscellaneous/cli/dotnet --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # .NET Core CLI EF command-line tools for .NET Core Command Line Interface (CLI). Note: Command-line tools for .NET Core CLI has known issues. See [Preview 2 Known Issues](#preview-2-known-issues) for more details. ## Installation ### Prerequisites EF command-line tools requires .NET Core CLI Preview 2 or newer. See the [.NET Core](https://www.microsoft.com/net/core) website for installation instructions. ### Supported Frameworks EF supports .NET Core CLI commands on these frameworks: * .NET Framework 4.5.1 and newer. ("net451", "net452", "net46", etc.) * .NET Core App 1.0. ("netcoreapp1.0") ### Install by editing project.json EF command-line tools for .NET Core CLI are installed by manually editing `project.json`. 1. Add `Microsoft.EntityFrameworkCore.Tools` as a "tool" and `Microsoft.EntityFrameworkCore.Design` as a build-only dependency under "dependencies". See sample project.json below. 2. Execute `dotnet restore`. If restore does not succeed, the command-line tools may not have installed correctly. The resulting project.json should include these items (in addition to your other project dependencies). <!-- literal_block {"language": "json", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````json { "dependencies": { "Microsoft.EntityFrameworkCore.Design": { "type": "build", "version": "1.0.0-preview2-final" } }, "tools": { "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final" }, "frameworks": { "netcoreapp1.0": { } } } ```` Tip: A build-only dependency (`"type": "build"`) means this dependency is local to the current project. For example, if Project A has a build only dependency and Project B depends on A, `dotnet restore` will not add A's build-only dependencies into Project B. ## Usage Commands can be run from the command line by navigating to the project directory and executing `dotnet ef [subcommand]`. To see usage, add `--help` to any command to see more information about parameters and subcommands. ### dotnet-ef <!-- literal_block {"language": "none", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````none Usage: dotnet ef [options] [command] Options: -h|--help Show help information -p|--project <PROJECT> The project to target (defaults to the project in the current directory). Can be a path to a project.json or a project directory. -s|--startup-project <PROJECT> The path to the project containing Startup (defaults to the target project). Can be a path to a project.json or a project directory. -c|--configuration <CONFIGURATION> Configuration under which to load (defaults to Debug) -f|--framework <FRAMEWORK> Target framework to load from the startup project (defaults to the framework most compatible with .NETCoreApp,Version=v1.0). -b|--build-base-path <OUTPUT_DIR> Directory in which to find temporary outputs. -o|--output <OUTPUT_DIR> Directory in which to find outputs Commands: database Commands to manage your database dbcontext Commands to manage your DbContext types migrations Commands to manage your migrations ```` ### dotnet-ef-database <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text Usage: dotnet ef database [options] [command] Options: -h|--help Show help information -v|--verbose Enable verbose output Commands: drop Drop the database for specific environment update Updates the database to a specified migration ```` ### dotnet-ef-database-drop <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text Usage: dotnet ef database drop [options] Options: -e|--environment <environment> The environment to use. If omitted, "Development" is used. -c|--context <context> The DbContext to use. If omitted, the default DbContext is used -f|--force Drop without confirmation -h|--help Show help information -v|--verbose Enable verbose output ```` ### dotnet-ef-database-update <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text Usage: dotnet ef database update [arguments] [options] Arguments: [migration] The target migration. If '0', all migrations will be reverted. If omitted, all pending migrations will be applied Options: -c|--context <context> The DbContext to use. If omitted, the default DbContext is used -e|--environment <environment> The environment to use. If omitted, "Development" is used. -h|--help Show help information -v|--verbose Enable verbose output ```` ### dotnet-ef-dbcontext <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text Usage: dotnet ef dbcontext [options] [command] Options: -h|--help Show help information -v|--verbose Enable verbose output Commands: list List your DbContext types scaffold Scaffolds a DbContext and entity type classes for a specified database ```` ### dotnet-ef-dbcontext-list <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text Usage: dotnet ef dbcontext list [options] Options: -e|--environment <environment> The environment to use. If omitted, "Development" is used. --json Use json output. JSON is wrapped by '//BEGIN' and '//END' -h|--help Show help information -v|--verbose Enable verbose output ```` ### dotnet-ef-dbcontext-scaffold <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text Usage: dotnet ef dbcontext scaffold [arguments] [options] Arguments: [connection] The connection string of the database [provider] The provider to use. For example, Microsoft.EntityFrameworkCore.SqlServer Options: -a|--data-annotations Use DataAnnotation attributes to configure the model where possible. If omitted, the output code will use only the fluent API. -c|--context <name> Name of the generated DbContext class. -f|--force Force scaffolding to overwrite existing files. Otherwise, the code will only proceed if no output files would be overwritten. -o|--output-dir <path> Directory of the project where the classes should be output. If omitted, the top-level project directory is used. --schema <schema> Selects a schema for which to generate classes. -t|--table <schema.table> Selects a table for which to generate classes. -e|--environment <environment> The environment to use. If omitted, "Development" is used. -h|--help Show help information -v|--verbose Enable verbose output ```` ### dotnet-ef-migrations <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text Usage: dotnet ef migrations [options] [command] Options: -h|--help Show help information -v|--verbose Enable verbose output Commands: add Add a new migration list List the migrations remove Remove the last migration script Generate a SQL script from migrations ```` ### dotnet-ef-migrations-add <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text Usage: dotnet ef migrations add [arguments] [options] Arguments: [name] The name of the migration Options: -o|--output-dir <path> The directory (and sub-namespace) to use. If omitted, "Migrations" is used. Relative paths are relative the directory in which the command is executed. -c|--context <context> The DbContext to use. If omitted, the default DbContext is used -e|--environment <environment> The environment to use. If omitted, "Development" is used. --json Use json output. JSON is wrapped by '//BEGIN' and '//END' -h|--help Show help information -v|--verbose Enable verbose output ```` ### dotnet-ef-migrations-list <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text Usage: dotnet ef migrations list [options] Options: -c|--context <context> The DbContext to use. If omitted, the default DbContext is used -e|--environment <environment> The environment to use. If omitted, "Development" is used. --json Use json output. JSON is wrapped by '//BEGIN' and '//END' -h|--help Show help information -v|--verbose Enable verbose output ```` ### dotnet-ef-migrations-remove <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text Usage: dotnet ef migrations remove [options] Options: -c|--context <context> The DbContext to use. If omitted, the default DbContext is used -e|--environment <environment> The environment to use. If omitted, "Development" is used. -f|--force Removes the last migration without checking the database. If the last migration has been applied to the database, you will need to manually reverse the changes it made. -h|--help Show help information -v|--verbose Enable verbose output ```` ### dotnet-ef-migrations-script <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text Usage: dotnet ef migrations script [arguments] [options] Arguments: [from] The starting migration. If omitted, '0' (the initial database) is used [to] The ending migration. If omitted, the last migration is used Options: -o|--output <file> The file to write the script to instead of stdout -i|--idempotent Generates an idempotent script that can used on a database at any migration -c|--context <context> The DbContext to use. If omitted, the default DbContext is used -e|--environment <environment> The environment to use. If omitted, "Development" is used. -h|--help Show help information -v|--verbose Enable verbose output ```` ## Common Errors ### Error: "No parameterless constructor was found" Design-time tools attempt to automatically find how your application creates instances of your DbContext type. If EF cannot find a suitable way to initialize your DbContext, you may encounter this error. <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text No parameterless constructor was found on 'TContext'. Either add a parameterless constructor to 'TContext' or add an implementation of 'IDbContextFactory<TContext>' in the same assembly as 'TContext'. ```` As the error message suggests, one solution is to add an implementation of `IDbContextFactory<TContext>` to the current project. See [Using IDbContextFactory<TContext>](../configuring-dbcontext.md#use-idbcontextfactory.md) for an example of how to create this factory. <a name=dotnet-cli-issues></a> ## Preview 2 Known Issues ### Targeting class library projects is not supported .NET Core CLI does not support running commands on class libraries as of Preview 2. Despite being able to install EF tools, executing commands may throw this error message. <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text Could not invoke this command on the startup project '(your project name)'. This preview of Entity Framework tools does not support commands on class library projects in ASP.NET Core and .NET Core applications. ```` See issue [https://github.com/dotnet/cli/issues/2645](https://github.com/dotnet/cli/issues/2645). #### Explanation If `dotnet run` does not work in the startup project, then `dotnet ef` cannot run either. "dotnet ef" is invoked as an alternate entry point into an application. If the "startup" project is not an application, then it is not currently possible to run the project as an application with the "dotnet ef" alternate entry point. The "startup" project defaults to the current project, unless specified differently with the parameter `--startup-project`. #### Workaround 1 - Utilize a separate startup project Convert the class library project into an "app" project. This can either be a .NET Core app or a desktop .NET app. Example: <!-- literal_block {"language": "json", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````json { "frameworks": { "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.0-*" } } } } } ```` Be sure to register the EntityFramework Tools as a project dependency and in the tools section of your project.json. Example: <!-- literal_block {"language": "json", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````json { "dependencies": { "Microsoft.EntityFrameworkCore.Tools": { "version": "1.0.0-preview2-final", "type": "build" } }, "tools": { "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final" } } ```` Finally, specify a startup project that is a "runnable app." Example: <!-- literal_block {"language": "console", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````console dotnet ef --startup-project ../MyConsoleApplication/ migrations list ```` #### Workaround 2 - Modify your class library to be a startup application Convert the class library project into an "app" project. This can either be a .NET Core app or a desktop .NET app. To make the project a .NET Core App, add the "netcoreapp1.0" framework to project.json along with the other settings in the sample below: <!-- literal_block {"language": "json", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````json { "buildOptions": { "emitEntryPoint": true }, "frameworks": { "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.0-*" } } } } } ```` To make a desktop .NET app, ensure you project targets "net451" or newer (example "net461" also works) and ensure the build option `"emitEntryPoint"` is set to true. <!-- literal_block {"language": "json", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````json { "buildOptions": { "emitEntryPoint": true }, "frameworks": { "net451": { } } } ```` <file_sep>/samples/Saving/Saving/Basics/Sample.cs using System; using System.Collections.Generic; using System.Linq; namespace EFSaving.Basics { public class Sample { public static void Run() { using (var db = new BloggingContext()) { db.Database.EnsureDeleted(); db.Database.EnsureCreated(); } using (var db = new BloggingContext()) { var blog = new Blog { Url = "http://sample.com" }; db.Blogs.Add(blog); db.SaveChanges(); Console.WriteLine(blog.BlogId + ": " + blog.Url); } using (var db = new BloggingContext()) { var blog = db.Blogs.First(); blog.Url = "http://sample.com/blog"; db.SaveChanges(); } using (var db = new BloggingContext()) { var blog = db.Blogs.First(); db.Blogs.Remove(blog); db.SaveChanges(); } // Insert some seed data for the final example using (var db = new BloggingContext()) { db.Blogs.Add(new Blog { Url = "http://sample.com/blog" }); db.Blogs.Add(new Blog { Url = "http://sample.com/another_blog" }); db.SaveChanges(); } using (var db = new BloggingContext()) { db.Blogs.Add(new Blog { Url = "http://sample.com/blog_one" }); db.Blogs.Add(new Blog { Url = "http://sample.com/blog_two" }); var firstBlog = db.Blogs.First(); firstBlog.Url = ""; var lastBlog = db.Blogs.Last(); db.Blogs.Remove(lastBlog); db.SaveChanges(); } } } } <file_sep>/CONTRIBUTING.md Contributing ============ Information on contributing to this repo is in the [Contributing Guide](https://github.com/aspnet/Home/blob/dev/CONTRIBUTING.md) in the Home repo. The documentation is built using [Sphinx](http://sphinx-doc.org) and [reStructuredText](http://sphinx-doc.org/rest.html), and then hosted by [ReadTheDocs](http://aspnet.readthedocs.org). This project shares the same process as the ASP.NET Core project for building and contributing documentation. Please review the following resources from the ASP.NET Core project: * [Building and contributing documentation](https://github.com/aspnet/Docs/blob/master/CONTRIBUTING.md) * [Style guide](http://docs.asp.net/en/latest/contribute/style-guide.html) <file_sep>/ef/querying/tracking.md --- uid: querying/tracking --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Tracking vs. No-Tracking Tracking behavior controls whether or not Entity Framework Core will keep information about an entity instance in its change tracker. If an entity is tracked, any changes detected in the entity will be persisted to the database during `SaveChanges()`. Entity Framework Core will also fix-up navigation properties between entities that are obtained from a tracking query and entities that were previously loaded into the DbContext instance. Tip: You can view this article's [sample](https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/Querying) on GitHub. ## Tracking queries By default, queries that return entity types are tracking. This means you can make changes to those entity instances and have those changes persisted by `SaveChanges()`. In the following example, the change to the blogs rating will be detected and persisted to the database during `SaveChanges()`. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/querying/Querying/Querying/Tracking/Sample.cs"} --> ````c# using (var context = new BloggingContext()) { var blog = context.Blogs.SingleOrDefault(b => b.BlogId == 1); blog.Rating = 5; context.SaveChanges(); } ```` ## No-tracking queries No tracking queries are useful when the results are used in a read-only scenario. They are quicker to execute because there is no need to setup change tracking information. You can swap an individual query to be no-tracking: <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [4]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/querying/Querying/Querying/Tracking/Sample.cs"} --> ````c# using (var context = new BloggingContext()) { var blogs = context.Blogs .AsNoTracking() .ToList(); } ```` You can also change the default tracking behavior at the context instance level: <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [3]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/querying/Querying/Querying/Tracking/Sample.cs"} --> ````c# using (var context = new BloggingContext()) { context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; var blogs = context.Blogs.ToList(); } ```` ## Tracking and projections Even if the result type of the query isn't an entity type, if the result contains entity types they will still be tracked by default. In the following query, which returns an anonymous type, the instances of `Blog` in the result set will be tracked. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [7]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/querying/Querying/Querying/Tracking/Sample.cs"} --> ````c# using (var context = new BloggingContext()) { var blog = context.Blogs .Select(b => new { Blog = b, Posts = b.Posts.Count() }); } ```` If the result set does not contain any entity types, then no tracking is performed. In the following query, which returns an anonymous type with some of the values from the entity (but no instances of the actual entity type), there is no tracking performed. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/querying/Querying/Querying/Tracking/Sample.cs"} --> ````c# using (var context = new BloggingContext()) { var blog = context.Blogs .Select(b => new { Id = b.BlogId, Url = b.Url }); } ```` <file_sep>/ef/modeling/relational/fk-constraints.md --- uid: modeling/relational/fk-constraints --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). Note: The configuration in this section is applicable to relational databases in general. The extension methods shown here will become available when you install a relational database provider (due to the shared *Microsoft.EntityFrameworkCore.Relational* package). # Foreign Key Constraints A foreign key constraint is introduced for each relationship in the model. ## Conventions By convention, foreign key constraints are named `FK_<dependent type name>_<principal type name>_<foreign key property name>`. For composite foreign keys `<foreign key property name>` becomes an underscore separated list of foreign key property names. ## Data Annotations Foreign key constraint names cannot be configured using data annotations. ## Fluent API You can use the Fluent API to configure the foreign key constraint name for a relationship. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/FluentAPI/Samples/Relational/RelationshipConstraintName.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [12], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Post>() .HasOne(p => p.Blog) .WithMany(b => b.Posts) .HasForeignKey(p => p.BlogId) .HasConstraintName("ForeignKey_Post_Blog"); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List<Post> Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } ```` <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Update/MyUpdateSqlGenerator.cs using System; using System.Text; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Update; namespace EntityFrameworkCore.RelationalProviderStarter.Update { public class MyUpdateSqlGenerator : UpdateSqlGenerator { public MyUpdateSqlGenerator(ISqlGenerationHelper sqlGenerationHelper) : base(sqlGenerationHelper) { } protected override void AppendIdentityWhereCondition(StringBuilder commandStringBuilder, ColumnModification columnModification) { throw new NotImplementedException(); } protected override void AppendRowsAffectedWhereCondition(StringBuilder commandStringBuilder, int expectedRowsAffected) { throw new NotImplementedException(); } } }<file_sep>/samples/Miscellaneous/Testing/TestProject/BlogServiceTestsReadOnly.cs using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.Extensions.DependencyInjection; using BusinessLogic; using Microsoft.EntityFrameworkCore; using System.Linq; using System; namespace TestProject { [TestClass] public class BlogServiceTestsReadOnly { private DbContextOptions<BloggingContext> _contextOptions; public BlogServiceTestsReadOnly() { // Create a service provider to be shared by all test methods var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); // Create options telling the context to use an // InMemory database and the service provider. var builder = new DbContextOptionsBuilder<BloggingContext>(); builder.UseInMemoryDatabase() .UseInternalServiceProvider(serviceProvider); _contextOptions = builder.Options; // Insert the seed data that is expected by all test methods using (var context = new BloggingContext(_contextOptions)) { context.Blogs.Add(new Blog { Url = "http://sample.com/cats" }); context.Blogs.Add(new Blog { Url = "http://sample.com/catfish" }); context.Blogs.Add(new Blog { Url = "http://sample.com/dogs" }); context.SaveChanges(); } } [TestMethod] public void Find_with_empty_term() { using (var context = new BloggingContext(_contextOptions)) { var service = new BlogService(context); var result = service.Find(""); Assert.AreEqual(3, result.Count()); } } [TestMethod] public void Find_with_unmatched_term() { using (var context = new BloggingContext(_contextOptions)) { var service = new BlogService(context); var result = service.Find("horse"); Assert.AreEqual(0, result.Count()); } } [TestMethod] public void Find_with_some_matched() { using (var context = new BloggingContext(_contextOptions)) { var service = new BlogService(context); var result = service.Find("cat"); Assert.AreEqual(2, result.Count()); } } } } <file_sep>/samples/Saving/Saving/ExplicitValuesGenerateProperties/EmployeeContext.cs using Microsoft.EntityFrameworkCore; namespace EFSaving.ExplicitValuesGenerateProperties { public class EmployeeContext : DbContext { public DbSet<Employee> Employees { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFSaving.ExplicitValuesGenerateProperties;Trusted_Connection=True;"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Employee>() .Property(b => b.EmploymentStarted) .HasDefaultValueSql("CONVERT(date, GETDATE())"); } } } <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Metadata/MyRelationalAnnotationProvider.cs using System; using Microsoft.EntityFrameworkCore.Metadata; namespace EntityFrameworkCore.RelationalProviderStarter.Metadata { public class MyRelationalAnnotationProvider : IRelationalAnnotationProvider { public IRelationalIndexAnnotations For(IIndex index) { throw new NotImplementedException(); } public IRelationalModelAnnotations For(IModel model) { throw new NotImplementedException(); } public IRelationalPropertyAnnotations For(IProperty property) { throw new NotImplementedException(); } public IRelationalKeyAnnotations For(IKey key) { throw new NotImplementedException(); } public IRelationalForeignKeyAnnotations For(IForeignKey foreignKey) { throw new NotImplementedException(); } public IRelationalEntityTypeAnnotations For(IEntityType entityType) { throw new NotImplementedException(); } } }<file_sep>/ef/miscellaneous/cli/index.md --- uid: miscellaneous/cli/index --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Command Line Reference Entity Framework provides command line tooling to automate common tasks such as code generation and database migrations. * [Package Manager Console (Visual Studio)](powershell.md) * [.NET Core CLI](dotnet.md) <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.ProviderStarter/Query/MyQueryContextFactory.cs using System; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Internal; namespace EntityFrameworkCore.ProviderStarter.Query { public class MyQueryContextFactory : QueryContextFactory { public MyQueryContextFactory(IStateManager stateManager, IConcurrencyDetector concurrencyDetector, IChangeDetector changeDetector) : base(stateManager, concurrencyDetector, changeDetector) { } public override QueryContext Create() { throw new NotImplementedException(); } } }<file_sep>/ef/modeling/relational/default-values.md --- uid: modeling/relational/default-values --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). Note: The configuration in this section is applicable to relational databases in general. The extension methods shown here will become available when you install a relational database provider (due to the shared *Microsoft.EntityFrameworkCore.Relational* package). # Default Values The default value of a column is the value that will be inserted if a new row is inserted but no value is specified for the column. ## Conventions By convention, a default value is not configured. ## Data Annotations You can not set a default value using Data Annotations. ## Fluent API You can use the Fluent API to specify the default value for a property. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/FluentAPI/Samples/Relational/DefaultValue.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [9], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .Property(b => b.Rating) .HasDefaultValue(3); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public int Rating { get; set; } } ```` You can also specify a SQL fragment that is used to calculate the default value. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/FluentAPI/Samples/Relational/DefaultValueSql.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [9], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .Property(b => b.Created) .HasDefaultValueSql("getdate()"); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public DateTime Created { get; set; } } ```` <file_sep>/ef/modeling/backing-field.md --- uid: modeling/backing-field --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Backing Fields When a backing field is configured, EF will write directly to that field when materializing entity instances from the database (rather than using the property setter). This is useful when there is no property setter, or the setter contains logic that should not be executed when setting initial property values for existing entities being loaded from the database. Caution: The `ChangeTracker` has not yet been enabled to use backing fields when it needs to set the value of a property. This is only an issue for foreign key properties and generated properties - as the change tracker needs to propagate values into these properties. For these properties, a property setter must still be exposed.[Issue #4461](https://github.com/aspnet/EntityFramework/issues/4461) is tracking enabling the `ChangeTracker` to write to backing fields for properties with no setter. ## Conventions By convention, the following fields will be discovered as backing fields for a given property (listed in precedence order): * <propertyName> differing only by case * _<propertyName> * m_<propertyName> <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [3, 7, 8, 9, 10, 11]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/Conventions/Samples/BackingField.cs"} --> ````c# public class Blog { private string _url; public int BlogId { get; set; } public string Url { get { return _url; } set { _url = value; } } } ```` ## Data Annotations Backing fields cannot be configured with data annotations. ## Fluent API There is no top level API for configuring backing fields, but you can use the Fluent API to set annotations that are used to store backing field information. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [7, 8, 9, 15, 18]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/FluentAPI/Samples/BackingField.cs"} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .Property(b => b.Url) .HasAnnotation("BackingField", "_blogUrl"); } } public class Blog { private string _blogUrl; public int BlogId { get; set; } public string Url => _blogUrl; } ```` <file_sep>/ef/platforms/netcore/new-db-sqlite.md --- uid: platforms/netcore/new-db-sqlite --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # .NET Core Application to New SQLite Database In this walkthrough, you will build a .NET Core console application that performs basic data access using Entity Framework. You will use migrations to create the database from your model. Tip: You can view this article's [sample](https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/Platforms/NetCore/ConsoleApp.SQLite) on GitHub. ## Prerequisites Minimum system requirements * An operating system that supports .NET Core * [.NET Core SDK Preview 2](https://www.microsoft.com/net/core) * A text editor Caution: **Known Issues** * Migrations on SQLite do not support more complex schema changes due to limitations in SQLite itself. See [SQLite Limitations](../../providers/sqlite/limitations.md) ### Install the .NET Core SDK The .NET Core SDK provides the command-line tool `dotnet` which will be used to build and run our sample application. See the [.NET Core website](https://www.microsoft.com/net/core) for instructions on installing the SDK on your operating system. ## Create a new project * Create a new folder `ConsoleApp/` for your project. All files for the project should be in this folder. <!-- literal_block {"language": "bash", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````bash mkdir ConsoleApp cd ConsoleApp/ ```` * Execute the following .NET Core CLI commands to create a new console application, download dependencies, and run the .NET Core app. <!-- literal_block {"language": "bash", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````bash dotnet new dotnet restore dotnet run ```` ## Install Entity Framework * To add EF to your project, modify `project.json` so it matches the following sample. <!-- literal_block {"language": "json", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/netcore/Platforms/NetCore/ConsoleApp.SQLite/project.json", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [8, 9, 10, 11, 12, 25, 26, 27], "linenostart": 1}, "ids": [], "linenos": true} --> ````json { "version": "1.0.0-*", "buildOptions": { "debugType": "portable", "emitEntryPoint": true }, "dependencies": { "Microsoft.EntityFrameworkCore.Sqlite": "1.0.0", "Microsoft.EntityFrameworkCore.Design": { "version": "1.0.0-preview2-final", "type": "build" } }, "frameworks": { "netcoreapp1.0": { "dependencies": { "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.0" } }, "imports": "dnxcore50" } }, "tools": { "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final" } } ```` * Run `dotnet restore` again to install the new packages. <!-- literal_block {"language": "bash", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````bash dotnet restore ```` * Verify that Entity Framework is installed by running `dotnet ef --help`. <!-- literal_block {"language": "bash", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````bash dotnet ef --help ```` ## Create your model With this new project, you are ready to begin using Entity Framework. The next steps will add code to configure and access a SQLite database file. * Create a new file called `Model.cs` All classes in the following steps will be added to this file. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/netcore/Platforms/NetCore/ConsoleApp.SQLite/Model.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ````c# using System.Collections.Generic; using System.IO; using Microsoft.EntityFrameworkCore; namespace ConsoleApp.SQLite { ```` * Add a new class to represent the SQLite database. We will call this `BloggingContext`. The call to `UseSqlite()` configures EF to point to a *.db file. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/netcore/Platforms/NetCore/ConsoleApp.SQLite/Model.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [1, 8], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# public class BloggingContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite("Filename=./blog.db"); } } ```` * Add classes to represent tables. Note that we will be using foreign keys to associate many posts to one blog. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/netcore/Platforms/NetCore/ConsoleApp.SQLite/Model.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ````c# public class Blog { public int BlogId { get; set; } public string Url { get; set; } public string Name { get; set; } public List<Post> Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } } ```` * To make sure the files are correct, you can compile the project on the command line by running `dotnet build` <!-- literal_block {"language": "bash", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````bash dotnet build ```` ## Create your database We can now use Entity Framework command line tools to create and manage the schema of the database. * Create the first migration. Execute the command below to generate your first migration. This will find our context and models, and generate a migration for us in a folder named `Migrations/` <!-- literal_block {"language": "bash", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````bash dotnet ef migrations add MyFirstMigration ```` * Apply the migrations. You can now begin using the existing migration to create the database file and creates the tables. <!-- literal_block {"language": "bash", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````bash dotnet ef database update ```` This should create a new file `blog.db` in the output path. This SQLite file should now contain two empty tables. Note: When using relative paths with SQLite, the path will be relative to the application's main assembly. In this sample, the main binary is `bin/Debug/netcoreapp1.0/ConsoleApp.dll`, so the SQLite database will be in `bin/Debug/netcoreapp1.0/blog.db` ## Use your model Now that we have configured our model and created the database schema, we can use BloggingContext to create, update, and delete objects. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/netcore/Platforms/NetCore/ConsoleApp.SQLite/Program.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ````c# using System; namespace ConsoleApp.SQLite { public class Program { public static void Main() { using (var db = new BloggingContext()) { db.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/adonet" }); var count = db.SaveChanges(); Console.WriteLine("{0} records saved to database", count); Console.WriteLine(); Console.WriteLine("All blogs in database:"); foreach (var blog in db.Blogs) { Console.WriteLine(" - {0}", blog.Url); } } } } } ```` ## Start your app Run the application from the command line. <!-- literal_block {"language": "bash", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````bash dotnet run ```` After adding the new post, you can verify the data has been added by inspecting the SQLite database file, `bin/Debug/netcoreapp1.0/blog.db`. <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Storage/MyRelationalDatabaseCreator.cs using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; namespace EntityFrameworkCore.RelationalProviderStarter.Storage { public class MyRelationalDatabaseCreator : RelationalDatabaseCreator { public MyRelationalDatabaseCreator( IModel model, IRelationalConnection connection, IMigrationsModelDiffer modelDiffer, IMigrationsSqlGenerator migrationsSqlGenerator, IMigrationCommandExecutor migrationCommandExecutor) : base(model, connection, modelDiffer, migrationsSqlGenerator, migrationCommandExecutor) { } public override void Create() { throw new NotImplementedException(); } public override void Delete() { throw new NotImplementedException(); } public override bool Exists() { throw new NotImplementedException(); } protected override bool HasTables() { throw new NotImplementedException(); } } }<file_sep>/ef/querying/basic.md --- uid: querying/basic --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Basic Query Entity Framework Core uses Language Integrate Query (LINQ) to query data from the database. LINQ allows you to use C# (or your .NET language of choice) to write strongly typed queries based on your derived context and entity classes. Tip: You can view this article's [sample](https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/Querying) on GitHub. ## 101 LINQ samples This page shows a few examples to achieve common tasks with Entity Framework Core. For an extensive set of samples showing what is possible with LINQ, see [101 LINQ Samples](https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b). ## Loading all data <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/querying/Querying/Querying/Basics/Sample.cs"} --> ````c# using (var context = new BloggingContext()) { var blogs = context.Blogs.ToList(); } ```` ## Loading a single entity <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/querying/Querying/Querying/Basics/Sample.cs"} --> ````c# using (var context = new BloggingContext()) { var blog = context.Blogs .Single(b => b.BlogId == 1); } ```` ## Filtering <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/querying/Querying/Querying/Basics/Sample.cs"} --> ````c# using (var context = new BloggingContext()) { var blogs = context.Blogs .Where(b => b.Url.Contains("dotnet")) .ToList(); } ```` <file_sep>/ef/modeling/concurrency.md --- uid: modeling/concurrency --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Concurrency Tokens If a property is configured as a concurrency token then EF will check that no other user has modified that value in the database when saving changes to that record. EF uses an optimistic concurrency pattern, meaning it will assume the value has not changed and try to save the data, but throw if it finds the value has been changed. For example we may want to configure `LastName` on `Person` to be a concurrency token. This means that if one user tries to save some changes to a `Person`, but another user has changed the `LastName` then an exception will be thrown. This may be desirable so that your application can prompt the user to ensure this record still represents the same actual person before saving their changes. ## How concurrency tokens work in EF Data stores can enforce concurrency tokens by checking that any record being updated or deleted still has the same value for the concurrency token that was assigned when the context originally loaded the data from the database. For example, relational database achieve this by including the concurrency token in the `WHERE` clause of any `UPDATE` or `DELETE` commands and checking the number of rows that were affected. If the concurrency token still matches then one row will be updated. If the value in the database has changed, then no rows are updated. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": false, "dupnames": [], "language": "sql", "highlight_args": {}, "names": []} --> ````sql UPDATE [Person] SET [FirstName] = @p1 WHERE [PersonId] = @p0 AND [LastName] = @p2; ```` ## Conventions By convention, properties are never configured as concurrency tokens. ## Data Annotations You can use the Data Annotations to configure a property as a concurrency token. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [4]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/DataAnnotations/Samples/Concurrency.cs"} --> ````c# public class Person { public int PersonId { get; set; } [ConcurrencyCheck] public string LastName { get; set; } public string FirstName { get; set; } } ```` ## Fluent API You can use the Fluent API to configure a property as a concurrency token. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [7, 8, 9]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/FluentAPI/Samples/Concurrency.cs"} --> ````c# class MyContext : DbContext { public DbSet<Person> People { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Person>() .Property(p => p.LastName) .IsConcurrencyToken(); } } public class Person { public int PersonId { get; set; } public string LastName { get; set; } public string FirstName { get; set; } } ```` ## Timestamp/row version A timestamp is a property where a new value is generated by the database every time a row is inserted or updated. The property is also treated as a concurrency token. This ensures you will get an exception if anyone else has modified a row that you are trying to update since you queried for the data. How this is achieved is up to the database provider being used. For SQL Server, timestamp is usually used on a *byte[]* property, which will be setup as a *ROWVERSION* column in the database. ### Conventions By convention, properties are never configured as timestamps. ### Data Annotations You can use Data Annotations to configure a property as a timestamp. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [6]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/DataAnnotations/Samples/Timestamp.cs"} --> ````c# public class Blog { public int BlogId { get; set; } public string Url { get; set; } [Timestamp] public byte[] Timestamp { get; set; } } ```` ### Fluent API You can use the Fluent API to configure a property as a timestamp. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [7, 8, 9, 10]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/FluentAPI/Samples/Timestamp.cs"} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .Property(p => p.Timestamp) .ValueGeneratedOnAddOrUpdate() .IsConcurrencyToken(); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public byte[] Timestamp { get; set; } } ```` <file_sep>/ef/saving/explicit-values-generated-properties.md --- uid: saving/explicit-values-generated-properties --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Setting explicit values for generated properties A generated property is a property whose value is generated (either by EF or the database) when the entity is added and/or updated. See [Generated Properties](../modeling/generated-properties.md) for more information. There may be situations where you want to set an explicit value for a generated property, rather than having one generated. Tip: You can view this article's [sample](https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/Saving/Saving/ExplicitValuesGenerateProperties/) on GitHub. ## The model The model used in this article contains a single `Employee` entity. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/saving/Saving/Saving/ExplicitValuesGenerateProperties/Employee.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ````c# public class Employee { public int EmployeeId { get; set; } public string Name { get; set; } public DateTime EmploymentStarted { get; set; } } ```` The context is setup to target SQL Server: * By convention the `Employee.EmployeeId` property will be a store generated `IDENTITY` column * The `Employee.EmploymentStarted` property has also been setup to have values generated by the database for new entities <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/saving/Saving/Saving/ExplicitValuesGenerateProperties/EmployeeContext.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ````c# public class EmployeeContext : DbContext { public DbSet<Employee> Employees { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFSaving.ExplicitValuesGenerateProperties;Trusted_Connection=True;"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Employee>() .Property(b => b.EmploymentStarted) .HasDefaultValueSql("CONVERT(date, GETDATE())"); } } ```` ## Saving an explicit value during add In the following code, two employees are being inserted into the database * For the first, no value is assigned to `Employee.EmploymentStarted` property, so it remains set to the CLR default value for `DateTime`. * For the second, we have set an explicit value of `1-Jan-2000`. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/saving/Saving/Saving/ExplicitValuesGenerateProperties/Sample.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [4], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# using (var db = new EmployeeContext()) { db.Employees.Add(new Employee { Name = "<NAME>" }); db.Employees.Add(new Employee { Name = "<NAME>", EmploymentStarted = new DateTime(2000, 1, 1) }); db.SaveChanges(); foreach (var employee in db.Employees) { Console.WriteLine(employee.EmployeeId + ": " + employee.Name + ", " + employee.EmploymentStarted); } } ```` The code results in the following output, showing that the database generated a value for the first employee and our explicit value was used for the second: <!-- literal_block {"xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "ids": []} --> ```` 1: <NAME>, 1/28/2016 12:00:00 AM 2: <NAME>, 1/1/2000 12:00:00 AM ```` ### Explicit values into SQL Server IDENTITY columns For most situations, the approach shown above will work for key properties. However, to insert explicit values into a SQL Server `IDENTITY` column, you need to manually enable `IDENTITY_INSERT` before calling `SaveChanges()`. Note: We have a [feature request](https://github.com/aspnet/EntityFramework/issues/703) on our backlog to do this automatically within the SQL Server provider. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/saving/Saving/Saving/ExplicitValuesGenerateProperties/Sample.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# using (var db = new EmployeeContext()) { db.Employees.Add(new Employee { EmployeeId = 100, Name = "<NAME>" }); db.Employees.Add(new Employee { EmployeeId = 101, Name = "<NAME>" }); db.Database.OpenConnection(); try { db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Employee ON"); db.SaveChanges(); db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Employee OFF"); } finally { db.Database.CloseConnection(); } foreach (var employee in db.Employees) { Console.WriteLine(employee.EmployeeId + ": " + employee.Name); } } ```` ## Setting an explicit values during update Caution: Due to various bugs, this scenario is not properly supported in the current pre-release of EF Core. See [documentation issue #122](https://github.com/aspnet/EntityFramework.Docs/issues/122) for more details. <file_sep>/samples/Miscellaneous/Testing/TestProject/BlogServiceTests.cs using BusinessLogic; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Linq; namespace TestProject { [TestClass] public class BlogServiceTests { private static DbContextOptions<BloggingContext> CreateNewContextOptions() { // Create a fresh service provider, and therefore a fresh // InMemory database instance. var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); // Create a new options instance telling the context to use an // InMemory database and the new service provider. var builder = new DbContextOptionsBuilder<BloggingContext>(); builder.UseInMemoryDatabase() .UseInternalServiceProvider(serviceProvider); return builder.Options; } [TestMethod] public void Add_writes_to_database() { // All contexts that share the same service provider will share the same InMemory database var options = CreateNewContextOptions(); // Run the test against one instance of the context using (var context = new BloggingContext(options)) { var service = new BlogService(context); service.Add("http://sample.com"); } // Use a separate instance of the context to verify correct data was saved to database using (var context = new BloggingContext(options)) { Assert.AreEqual(1, context.Blogs.Count()); Assert.AreEqual("http://sample.com", context.Blogs.Single().Url); } } [TestMethod] public void Find_searches_url() { // All contexts that share the same service provider will share the same InMemory database var options = CreateNewContextOptions(); // Insert seed data into the database using one instance of the context using (var context = new BloggingContext(options)) { context.Blogs.Add(new Blog { Url = "http://sample.com/cats" }); context.Blogs.Add(new Blog { Url = "http://sample.com/catfish" }); context.Blogs.Add(new Blog { Url = "http://sample.com/dogs" }); context.SaveChanges(); } // Use a clean instance of the context to run the test using (var context = new BloggingContext(options)) { var service = new BlogService(context); var result = service.Find("cat"); Assert.AreEqual(2, result.Count()); } } } } <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Query/Sql/MyQuerySqlGeneratorFactory.cs using System; using Microsoft.EntityFrameworkCore.Query.Expressions; using Microsoft.EntityFrameworkCore.Query.Sql; using Microsoft.EntityFrameworkCore.Storage; namespace EntityFrameworkCore.RelationalProviderStarter.Query.Sql { public class MyQuerySqlGeneratorFactory : QuerySqlGeneratorFactoryBase { public MyQuerySqlGeneratorFactory( IRelationalCommandBuilderFactory commandBuilderFactory, ISqlGenerationHelper sqlGenerationHelper, IParameterNameGeneratorFactory parameterNameGeneratorFactory, IRelationalTypeMapper relationalTypeMapper) : base( commandBuilderFactory, sqlGenerationHelper, parameterNameGeneratorFactory, relationalTypeMapper) { } public override IQuerySqlGenerator CreateDefault(SelectExpression selectExpression) { throw new NotImplementedException(); } } }<file_sep>/ef/modeling/included-types.md --- uid: modeling/included-types --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Including & Excluding Types Including a type in the model means that EF has metadata about that type and will attempt to read and write instances from/to the database. ## Conventions By convention, types that are exposed in `DbSet` properties on your context are included in your model. In addition, types that are mentioned in the `OnModelCreating` method are also included. Finally, any types that are found by recursively exploring the navigation properties of discovered types are also included in the model. For example, in the following code listing all three types are discovered: * `Blog` because it is exposed in a `DbSet` property on the context * `Post` because it is discovered via the `Blog.Posts` navigation property * `AuditEntry` because it is mentioned in `OnModelCreating` <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/Conventions/Samples/IncludedTypes.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [3, 7, 16], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<AuditEntry>(); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List<Post> Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public Blog Blog { get; set; } } public class AuditEntry { public int AuditEntryId { get; set; } public string Username { get; set; } public string Action { get; set; } } ```` ## Data Annotations You can use Data Annotations to exclude a type from the model. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/DataAnnotations/Samples/IgnoreType.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [9], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# public class Blog { public int BlogId { get; set; } public string Url { get; set; } public BlogMetadata Metadata { get; set; } } [NotMapped] public class BlogMetadata { public DateTime LoadedFromDatabase { get; set; } } ```` ## Fluent API You can use the Fluent API to exclude a type from the model. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/FluentAPI/Samples/IgnoreType.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [7], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Ignore<BlogMetadata>(); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public BlogMetadata Metadata { get; set; } } public class BlogMetadata { public DateTime LoadedFromDatabase { get; set; } } ```` <file_sep>/samples/Modeling/FluentAPI/Samples/Concurrency.cs using Microsoft.EntityFrameworkCore; namespace EFModeling.Configuring.FluentAPI.Samples.Concurrency { class MyContext : DbContext { public DbSet<Person> People { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Person>() .Property(p => p.LastName) .IsConcurrencyToken(); } } public class Person { public int PersonId { get; set; } public string LastName { get; set; } public string FirstName { get; set; } } } <file_sep>/samples/Querying/Querying/RawSQL/Sample.cs using Microsoft.EntityFrameworkCore; using System.Data.SqlClient; using System.Linq; namespace EFQuerying.RawSQL { public class Sample { public static void Run() { using (var context = new BloggingContext()) { var blogs = context.Blogs .FromSql("SELECT * FROM dbo.Blogs") .ToList(); } using (var context = new BloggingContext()) { var blogs = context.Blogs .FromSql("EXECUTE dbo.GetMostPopularBlogs") .ToList(); } using (var context = new BloggingContext()) { var user = "johndoe"; var blogs = context.Blogs .FromSql("EXECUTE dbo.GetMostPopularBlogsForUser {0}", user) .ToList(); } using (var context = new BloggingContext()) { var user = new SqlParameter("user", "johndoe"); var blogs = context.Blogs .FromSql("EXECUTE dbo.GetMostPopularBlogsForUser @user", user) .ToList(); } using (var context = new BloggingContext()) { var searchTerm = ".NET"; var blogs = context.Blogs .FromSql("SELECT * FROM dbo.SearchBlogs {0}", searchTerm) .Where(b => b.Rating > 3) .OrderByDescending(b => b.Rating) .ToList(); } using (var context = new BloggingContext()) { var searchTerm = ".NET"; var blogs = context.Blogs .FromSql("SELECT * FROM dbo.SearchBlogs {0}", searchTerm) .Include(b => b.Posts) .ToList(); } } } } <file_sep>/samples/Platforms/UWP/UWP.SQLite/MainPage.xaml.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace EFGetStarted.UWP { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } private void Page_Loaded(object sender, RoutedEventArgs e) { using (var db = new BloggingContext()) { Blogs.ItemsSource = db.Blogs.ToList(); } } private void Add_Click(object sender, RoutedEventArgs e) { using (var db = new BloggingContext()) { var blog = new Blog { Url = NewBlogUrl.Text }; db.Blogs.Add(blog); db.SaveChanges(); Blogs.ItemsSource = db.Blogs.ToList(); } } } } <file_sep>/samples/Querying/Querying/PersonPhoto.cs using System.Collections.Generic; namespace EFQuerying { public class PersonPhoto { public int PersonPhotoId { get; set; } public string Caption { get; set; } public byte[] Photo { get; set; } public Person Person { get; set; } } } <file_sep>/ef/platforms/aspnetcore/existing-db.md --- uid: platforms/aspnetcore/existing-db --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # ASP.NET Core Application to Existing Database (Database First) In this walkthrough, you will build an ASP.NET Core MVC application that performs basic data access using Entity Framework. You will use reverse engineering to create an Entity Framework model based on an existing database. Tip: You can view this article's [sample](https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/Platforms/AspNetCore/AspNetCore.ExistingDb) on GitHub. ## Prerequisites The following prerequisites are needed to complete this walkthrough: * [Visual Studio 2015 Update 3](https://go.microsoft.com/fwlink/?LinkId=691129) * [.NET Core for Visual Studio](https://go.microsoft.com/fwlink/?LinkId=817245) * [Blogging database](#blogging-database) ### Blogging database This tutorial uses a **Blogging** database on your LocalDb instance as the existing database. Note: If you have already created the **Blogging** database as part of another tutorial, you can skip these steps. * Open Visual Studio * Tools ‣ Connect to Database... * Select **Microsoft SQL Server** and click **Continue** * Enter **(localdb)\mssqllocaldb** as the **Server Name** * Enter **master** as the **Database Name** and click **OK** * The master database is now displayed under **Data Connections** in **Server Explorer** * Right-click on the database in **Server Explorer** and select **New Query** * Copy the script, listed below, into the query editor * Right-click on the query editor and select **Execute** <!-- literal_block {"language": "sql", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/_shared/create-blogging-database-script.sql", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ````sql CREATE DATABASE [Blogging] GO USE [Blogging] GO CREATE TABLE [Blog] ( [BlogId] int NOT NULL IDENTITY, [Url] nvarchar(max) NOT NULL, CONSTRAINT [PK_Blog] PRIMARY KEY ([BlogId]) ); GO CREATE TABLE [Post] ( [PostId] int NOT NULL IDENTITY, [BlogId] int NOT NULL, [Content] nvarchar(max), [Title] nvarchar(max), CONSTRAINT [PK_Post] PRIMARY KEY ([PostId]), CONSTRAINT [FK_Post_Blog_BlogId] FOREIGN KEY ([BlogId]) REFERENCES [Blog] ([BlogId]) ON DELETE CASCADE ); GO INSERT INTO [Blog] (Url) VALUES ('http://blogs.msdn.com/dotnet'), ('http://blogs.msdn.com/webdev'), ('http://blogs.msdn.com/visualstudio') GO ```` ## Create a new project * Open Visual Studio 2015 * File ‣ New ‣ Project... * From the left menu select Templates ‣ Visual C# ‣ Web * Select the **ASP.NET Core Web Application (.NET Core)** project template * Enter **EFGetStarted.AspNetCore.ExistingDb** as the name and click **OK** * Wait for the **New ASP.NET Core Web Application** dialog to appear * Select the **Web Application** template and ensure that **Authentication** is set to **No Authentication** * Click **OK** ## Install Entity Framework To use EF Core, install the package for the database provider(s) you want to target. This walkthrough uses SQL Server. For a list of available providers see [Database Providers](../../providers/index.md). * Tools ‣ NuGet Package Manager ‣ Package Manager Console * Run `Install-Package Microsoft.EntityFrameworkCore.SqlServer` Note: In ASP.NET Core projects the `Install-Package` will complete quickly and the package installation will occur in the background. You will see **(Restoring...)** appear next to **References** in **Solution Explorer** while the install occurs. To enable reverse engineering from an existing database we need to install a couple of other packages too. * Run `Install-Package Microsoft.EntityFrameworkCore.Tools –Pre` * Run `Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design` * Open **project.json** * Locate the `tools` section and add the highlighted lines as shown below <!-- literal_block {"source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/aspnetcore/Platforms/AspNetCore/AspNetCore.NewDb/project.json", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [2], "linenostart": 1}, "ids": [], "linenos": true} --> ```` "tools": { "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final", "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final", "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final" }, ```` ## Reverse engineer your model Now it's time to create the EF model based on your existing database. * Tools –> NuGet Package Manager –> Package Manager Console * Run the following command to create a model from the existing database. If you receive an error stating the term 'Scaffold-DbContext' is not recognized as the name of a cmdlet, then close and reopen Visual Studio. <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models ```` The reverse engineer process created entity classes and a derived context based on the schema of the existing database. The entity classes are simple C# objects that represent the data you will be querying and saving. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/aspnetcore/Platforms/AspNetCore/AspNetCore.ExistingDb/Models/Blog.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ````c# using System; using System.Collections.Generic; namespace EFGetStarted.AspNetCore.ExistingDb.Models { public partial class Blog { public Blog() { Post = new HashSet<Post>(); } public int BlogId { get; set; } public string Url { get; set; } public virtual ICollection<Post> Post { get; set; } } } ```` The context represents a session with the database and allows you to query and save instances of the entity classes. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/aspnetcore/Platforms/AspNetCore/AspNetCore.ExistingDb/Models/BloggingContextUnmodified.txt", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ````c# using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; namespace EFGetStarted.AspNetCore.ExistingDb.Models { public partial class BloggingContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings. optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>(entity => { entity.Property(e => e.Url).IsRequired(); }); modelBuilder.Entity<Post>(entity => { entity.HasOne(d => d.Blog) .WithMany(p => p.Post) .HasForeignKey(d => d.BlogId); }); } public virtual DbSet<Blog> Blog { get; set; } public virtual DbSet<Post> Post { get; set; } } } ```` ## Register your context with dependency injection The concept of dependency injection is central to ASP.NET Core. Services (such as `BloggingContext`) are registered with dependency injection during application startup. Components that require these services (such as your MVC controllers) are then provided these services via constructor parameters or properties. For more information on dependency injection see the [Dependency Injection](http://docs.asp.net/en/latest/fundamentals/dependency-injection.html) article on the ASP.NET site. ### Remove inline context configuration In ASP.NET Core, configuration is generally performed in **Startup.cs**. To conform to this pattern, we will move configuration of the database provider to **Startup.cs**. * Open **Models\BloggingContext.cs** * Delete the lines of code highlighted below <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/aspnetcore/Platforms/AspNetCore/AspNetCore.ExistingDb/Models/BloggingContextUnmodified.txt", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [3, 4, 5, 6, 7], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# public partial class BloggingContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings. optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;"); } ```` * Add the lines of code highlighted below <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/aspnetcore/Platforms/AspNetCore/AspNetCore.ExistingDb/Models/BloggingContext.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [3, 4, 5], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# public partial class BloggingContext : DbContext { public BloggingContext(DbContextOptions<BloggingContext> options) : base(options) { } ```` ### Register and configure your context in Startup.cs In order for our MVC controllers to make use of `BloggingContext` we are going to register it as a service. * Open **Startup.cs** * Add the following `using` statements at the start of the file <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/aspnetcore/Platforms/AspNetCore/AspNetCore.ExistingDb/Startup.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ````c# using EFGetStarted.AspNetCore.ExistingDb.Models; using Microsoft.EntityFrameworkCore; ```` Now we can use the `AddDbContext` method to register it as a service. * Locate the `ConfigureServices` method * Add the lines that are highlighted in the following code <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/aspnetcore/Platforms/AspNetCore/AspNetCore.ExistingDb/Startup.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [3, 4], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# public void ConfigureServices(IServiceCollection services) { var connection = @"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;"; services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection)); ```` ## Create a controller Next, we'll add an MVC controller that will use EF to query and save data. * Right-click on the **Controllers** folder in **Solution Explorer** and select Add ‣ New Item... * From the left menu select Installed ‣ Code * Select the **Class** item template * Enter **BlogsController.cs** as the name and click **OK** * Replace the contents of the file with the following code <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/aspnetcore/Platforms/AspNetCore/AspNetCore.ExistingDb/Controllers/BlogsController.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ````c# using EFGetStarted.AspNetCore.ExistingDb.Models; using Microsoft.AspNetCore.Mvc; using System.Linq; namespace EFGetStarted.AspNetCore.ExistingDb.Controllers { public class BlogsController : Controller { private BloggingContext _context; public BlogsController(BloggingContext context) { _context = context; } public IActionResult Index() { return View(_context.Blog.ToList()); } public IActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Create(Blog blog) { if (ModelState.IsValid) { _context.Blog.Add(blog); _context.SaveChanges(); return RedirectToAction("Index"); } return View(blog); } } } ```` You'll notice that the controller takes a `BloggingContext` as a constructor parameter. ASP.NET dependency injection will take care of passing an instance of `BloggingContext` into your controller. The controller contains an `Index` action, which displays all blogs in the database, and a `Create` action, which inserts a new blogs into the database. ## Create views Now that we have a controller it's time to add the views that will make up the user interface. We'll start with the view for our `Index` action, that displays all blogs. * Right-click on the **Views** folder in **Solution Explorer** and select Add ‣ New Folder * Enter **Blogs** as the name of the folder * Right-click on the **Blogs** folder and select Add ‣ New Item... * From the left menu select Installed ‣ ASP.NET * Select the **MVC View Page** item template * Enter **Index.cshtml** as the name and click **Add** * Replace the contents of the file with the following code <!-- literal_block {"source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/aspnetcore/Platforms/AspNetCore/AspNetCore.ExistingDb/Views/Blogs/Index.cshtml", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ```` @model IEnumerable<EFGetStarted.AspNetCore.ExistingDb.Models.Blog> @{ ViewBag.Title = "Blogs"; } <h2>Blogs</h2> <p> <a asp-controller="Blogs" asp-action="Create">Create New</a> </p> <table class="table"> <tr> <th>Id</th> <th>Url</th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.BlogId) </td> <td> @Html.DisplayFor(modelItem => item.Url) </td> </tr> } </table> ```` We'll also add a view for the `Create` action, which allows the user to enter details for a new blog. * Right-click on the **Blogs** folder and select Add ‣ New Item... * From the left menu select Installed ‣ ASP.NET * Select the **MVC View Page** item template * Enter **Create.cshtml** as the name and click **Add** * Replace the contents of the file with the following code <!-- literal_block {"source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/aspnetcore/Platforms/AspNetCore/AspNetCore.ExistingDb/Views/Blogs/Create.cshtml", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ```` @model EFGetStarted.AspNetCore.ExistingDb.Models.Blog @{ ViewBag.Title = "New Blog"; } <h2>@ViewData["Title"]</h2> <form asp-controller="Blogs" asp-action="Create" method="post" class="form-horizontal" role="form"> <div class="form-horizontal"> <div asp-validation-summary="All" class="text-danger"></div> <div class="form-group"> <label asp-for="Url" class="col-md-2 control-label"></label> <div class="col-md-10"> <input asp-for="Url" class="form-control" /> <span asp-validation-for="Url" class="text-danger"></span> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> </form> ```` ## Run the application You can now run the application to see it in action. * Debug ‣ Start Without Debugging * The application will build and open in a web browser * Navigate to **/Blogs** * Click **Create New** * Enter a **Url** for the new blog and click **Create** ![image](aspnetcore/_static/create.png) ![image](aspnetcore/_static/index-existing-db.png) <file_sep>/samples/Platforms/AspNetCore/AspNetCore.ExistingDb/Controllers/BlogsController.cs using EFGetStarted.AspNetCore.ExistingDb.Models; using Microsoft.AspNetCore.Mvc; using System.Linq; namespace EFGetStarted.AspNetCore.ExistingDb.Controllers { public class BlogsController : Controller { private BloggingContext _context; public BlogsController(BloggingContext context) { _context = context; } public IActionResult Index() { return View(_context.Blog.ToList()); } public IActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Create(Blog blog) { if (ModelState.IsValid) { _context.Blog.Add(blog); _context.SaveChanges(); return RedirectToAction("Index"); } return View(blog); } } } <file_sep>/samples/Miscellaneous/Testing/BusinessLogic/BlogService.cs using System.Collections.Generic; using System.Linq; namespace BusinessLogic { public class BlogService { private BloggingContext _context; public BlogService(BloggingContext context) { _context = context; } public void Add(string url) { var blog = new Blog { Url = url }; _context.Blogs.Add(blog); _context.SaveChanges(); } public IEnumerable<Blog> Find(string term) { return _context.Blogs .Where(b => b.Url.Contains(term)) .OrderBy(b => b.Url) .ToList(); } } } <file_sep>/samples/Saving/Saving/RelatedData/Sample.cs using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; namespace EFSaving.RelatedData { public class Sample { public static void Run() { using (var context = new BloggingContext()) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); } // Adding a graph of new entities using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://blogs.msdn.com/dotnet", Posts = new List<Post> { new Post { Title = "Intro to C#" }, new Post { Title = "Intro to VB.NET" }, new Post { Title = "Intro to F#" } } }; context.Blogs.Add(blog); context.SaveChanges(); } // Adding a related entity using (var context = new BloggingContext()) { var blog = context.Blogs.First(); var post = new Post { Title = "Intro to EF Core" }; blog.Posts.Add(post); context.SaveChanges(); } // Changing relationships using (var context = new BloggingContext()) { var blog = new Blog { Url = "http://blogs.msdn.com/visualstudio" }; var post = context.Posts.First(); blog.Posts.Add(post); context.SaveChanges(); } // Removing relationships using (var context = new BloggingContext()) { var blog = context.Blogs.Include(b => b.Posts).First(); var post = blog.Posts.First(); blog.Posts.Remove(post); context.SaveChanges(); } } public class BloggingContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFSaving.RelatedData;Trusted_Connection=True;"); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List<Post> Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } } } } <file_sep>/ef/providers/ibm/index.md --- uid: providers/ibm/index --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # IBM Data Servers This database provider allows Entity Framework Core to be used with IBM Data Servers. Issues, questions, etc. can be posted in the [.Net Development with DB2 and IDS forum](https://www.ibm.com/developerworks/community/forums/html/forum?id=11111111-0000-0000-0000-000000000467) Note: This provider is not maintained as part of the Entity Framework Core project. When considering a third party provider, be sure to evaluate quality, licensing, support, etc. to ensure they meet your requirements. Caution: This provider currently only supports the Entity Framework Core RC1 pre-release. ## Install Install the [EntityFramework.IBMDataServer NuGet package](https://www.nuget.org/packages/EntityFramework.IBMDataServer). <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": false, "dupnames": [], "language": "text", "highlight_args": {}, "names": []} --> ````text PM> Install-Package EntityFramework.IBMDataServer -Pre ```` ## Get Started The following resources will help you get started with this provider. * [Sample application](https://www.ibm.com/developerworks/community/blogs/96960515-2ea1-4391-8170-b0515d08e4da/entry/sample_ef7_application_for_ibm_data_servers) * [Updates & Limitations](https://www.ibm.com/developerworks/community/blogs/96960515-2ea1-4391-8170-b0515d08e4da/entry/latest_updates_and_limitations_for_ibm_data_server_entityframework_7) ## Supported Database Engines * IBM Data Servers ## Supported Platforms * Full .NET (4.5.1 onwards) <file_sep>/ef/providers/sql-compact/index.md --- uid: providers/sql-compact/index --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Microsoft SQL Server Compact Edition This database provider allows Entity Framework Core to be used with SQL Server Compact Edition. The provider is maintained as part of the [ErikEJ/EntityFramework.SqlServerCompact GitHub Project](https://github.com/ErikEJ/EntityFramework.SqlServerCompact). Note: This provider is not maintained as part of the Entity Framework Core project. When considering a third party provider, be sure to evaluate quality, licensing, support, etc. to ensure they meet your requirements. ## Install To work with SQL Server Compact Edition 4.0, install the [EntityFrameworkCore.SqlServerCompact40 NuGet package](https://www.nuget.org/packages/EntityFrameworkCore.SqlServerCompact40). <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text PM> Install-Package EntityFrameworkCore.SqlServerCompact40 ```` To work with SQL Server Compact Edition 3.5, install the [EntityFrameworkCore.SqlServerCompact35](https://www.nuget.org/packages/EntityFrameworkCore.SqlServerCompact35). <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text PM> Install-Package EntityFrameworkCore.SqlServerCompact35 ```` ## Get Started See the [getting started documentation on the project site](https://github.com/ErikEJ/EntityFramework.SqlServerCompact/wiki/Using-EF-Core-with-SQL-Server-Compact-in-Traditional-.NET-Applications) ## Supported Database Engines * SQL Server Compact Edition 3.5 * SQL Server Compact Edition 4.0 ## Supported Platforms * Full .NET (4.5.1 onwards) <file_sep>/ef/modeling/relational/primary-keys.md --- uid: modeling/relational/primary-keys --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). Note: The configuration in this section is applicable to relational databases in general. The extension methods shown here will become available when you install a relational database provider (due to the shared *Microsoft.EntityFrameworkCore.Relational* package). # Primary Keys A primary key constraint is introduced for the key of each entity type. ## Conventions By convention, the primary key in the database will be named `PK_<type name>`. ## Data Annotations No relational database specific aspects of a primary key can be configured using Data Annotations. ## Fluent API You can use the Fluent API to configure the name of the primary key constraint in the database. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/FluentAPI/Samples/Relational/KeyName.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [9], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .HasKey(b => b.BlogId) .HasName("PrimaryKey_BlogId"); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } } ```` <file_sep>/ef/modeling/relational/sequences.md --- uid: modeling/relational/sequences --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). Note: The configuration in this section is applicable to relational databases in general. The extension methods shown here will become available when you install a relational database provider (due to the shared *Microsoft.EntityFrameworkCore.Relational* package). # Sequences A sequence generates a sequential numeric values in the database. Sequences are not associated with a specific table. ## Conventions By convention, sequences are not introduced in to the model. ## Data Annotations You can not configure a sequence using Data Annotations. ## Fluent API You can use the Fluent API to create a sequence in the model. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/FluentAPI/Samples/Relational/Sequence.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [7], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Order> Orders { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasSequence<int>("OrderNumbers"); } } public class Order { public int OrderId { get; set; } public int OrderNo { get; set; } public string Url { get; set; } } ```` You can also configure additional aspect of the sequence, such as its schema, start value, and increment. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/FluentAPI/Samples/Relational/SequenceConfigured.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [7, 8, 9], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Order> Orders { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasSequence<int>("OrderNumbers", schema: "shared") .StartsAt(1000) .IncrementsBy(5); } } ```` Once a sequence is introduced, you can use it to generate values for properties in your model. For example, you can use [Default Values](default-values.md) to insert the next value from the sequence. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/FluentAPI/Samples/Relational/SequenceUsed.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [11, 12, 13], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Order> Orders { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasSequence<int>("OrderNumbers", schema: "shared") .StartsAt(1000) .IncrementsBy(5); modelBuilder.Entity<Order>() .Property(o => o.OrderNo) .HasDefaultValueSql("NEXT VALUE FOR shared.OrderNumbers"); } } public class Order { public int OrderId { get; set; } public int OrderNo { get; set; } public string Url { get; set; } } ```` <file_sep>/samples/Querying/Querying/Person.cs using System.Collections.Generic; namespace EFQuerying { public class Person { public int PersonId { get; set; } public string Name { get; set; } public List<Post> AuthoredPosts { get; set; } public List<Post> OwnedBlogs { get; set; } public int? PhotoId { get; set; } public PersonPhoto Photo { get; set; } } } <file_sep>/ef/miscellaneous/internals/index.md --- uid: miscellaneous/internals/index --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Internals Caution: These articles are advanced topics. The target audience is provider writers and EF contributors. * [Writing a Database Provider](writing-a-provider.md) * [Understanding EF Services](services.md) <file_sep>/samples/Modeling/Conventions/Samples/KeyId.cs using Microsoft.EntityFrameworkCore; using System.ComponentModel.DataAnnotations; namespace EFModeling.Conventions.Samples.KeyId { class MyContext : DbContext { public DbSet<Car> Cars { get; set; } } class Car { public string Id { get; set; } public string Make { get; set; } public string Model { get; set; } } } <file_sep>/ef/efcore-vs-ef6/porting/index.md --- uid: efcore-vs-ef6/porting/index --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Porting from EF6.x to EF Core The following articles cover porting from EF6.x to EF Core * [Ensure EF Core Will Work for Your Application](ensure-requirements.md) * [Porting an EDMX-Based Model (Model First & Database First)](port-edmx.md) * [Porting a Code-Based Model (Code First & Code First to Existing Database)](port-code.md) <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.ProviderStarter/ValueGeneration/MyValueGeneratorCache.cs using Microsoft.EntityFrameworkCore.ValueGeneration; namespace EntityFrameworkCore.ProviderStarter.ValueGeneration { internal class MyValueGeneratorCache : ValueGeneratorCache { } }<file_sep>/samples/Saving/Saving/Transactions/ExternalDbTransaction/Sample.cs using Microsoft.EntityFrameworkCore; using System.Data.SqlClient; namespace EFSaving.Transactions.ExternalDbTransaction { public class Sample { public static void Run() { var connectionString = @"Server=(localdb)\mssqllocaldb;Database=EFSaving.Transactions;Trusted_Connection=True;"; using (var context = new BloggingContext( new DbContextOptionsBuilder<BloggingContext>() .UseSqlServer(connectionString) .Options)) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); } var connection = new SqlConnection(connectionString); connection.Open(); using (var transaction = connection.BeginTransaction()) { try { // Run raw ADO.NET command in the transaction var command = connection.CreateCommand(); command.Transaction = transaction; command.CommandText = "DELETE FROM dbo.Blogs"; command.ExecuteNonQuery(); // Run an EF Core command in the transaction var options = new DbContextOptionsBuilder<BloggingContext>() .UseSqlServer(connection) .Options; using (var context = new BloggingContext(options)) { context.Database.UseTransaction(transaction); context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); context.SaveChanges(); } // Commit transaction if all commands succeed, transaction will auto-rollback // when disposed if either commands fails transaction.Commit(); } catch (System.Exception) { // TODO: Handle failure } } } public class BloggingContext : DbContext { public BloggingContext(DbContextOptions<BloggingContext> options) : base(options) { } public DbSet<Blog> Blogs { get; set; } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } } } } <file_sep>/ef/providers/mysql/index.md --- uid: providers/mysql/index --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # MySQL (Official) This database provider allows Entity Framework Core to be used with MySQL. The provider is maintained as part of the [MySQL project](http://dev.mysql.com). Caution: This provider is pre-release. Note: This provider is not maintained as part of the Entity Framework Core project. When considering a third party provider, be sure to evaluate quality, licensing, support, etc. to ensure they meet your requirements. ## Install Install the [MySql.Data.EntityFrameworkCore NuGet package](https://www.nuget.org/packages/MySql.Data.EntityFrameworkCore). <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": false, "dupnames": [], "language": "text", "highlight_args": {}, "names": []} --> ````text PM> Install-Package MySql.Data.EntityFrameworkCore -Pre ```` ## Get Started See [Starting with MySQL EF Core provider and Connector/Net 7.0.4](http://insidemysql.com/howto-starting-with-mysql-ef-core-provider-and-connectornet-7-0-4/). ## Supported Database Engines * MySQL ## Supported Platforms * Full .NET (4.5.1 onwards) * .NET Core <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.ProviderStarter/Extensions/MyProviderServiceCollectionExtensions.cs using EntityFrameworkCore.ProviderStarter.Infrastructure; using EntityFrameworkCore.ProviderStarter.Query; using EntityFrameworkCore.ProviderStarter.Query.ExpressionVisitors; using EntityFrameworkCore.ProviderStarter.Storage; using EntityFrameworkCore.ProviderStarter.ValueGeneration; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection.Extensions; namespace Microsoft.Extensions.DependencyInjection { public static class MyProviderServiceCollectionExtensions { public static IServiceCollection AddEntityFrameworkMyProvider(this IServiceCollection services) { services.AddEntityFramework(); services.TryAddEnumerable(ServiceDescriptor .Singleton<IDatabaseProvider, DatabaseProvider<MyDatabaseProviderServices, MyProviderOptionsExtension>>()); services.TryAdd(new ServiceCollection() // singleton services .AddSingleton<MyModelSource>() .AddSingleton<MyValueGeneratorCache>() // scoped services .AddScoped<MyDatabaseProviderServices>() .AddScoped<MyDatabaseCreator>() .AddScoped<MyDatabase>() .AddScoped<MyEntityQueryableExpressionVisitorFactory>() .AddScoped<MyEntityQueryModelVisitorFactory>() .AddScoped<MyQueryContextFactory>() .AddScoped<MyTransactionManager>()); return services; } } } <file_sep>/samples/Saving/Saving/CascadeDelete/Sample.cs using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; namespace EFSaving.CascadeDelete { public class Sample { public static void Run() { using (var db = new BloggingContext()) { db.Database.EnsureDeleted(); db.Database.EnsureCreated(); db.Blogs.Add(new Blog { Url = "http://sample.com", Posts = new List<Post> { new Post { Title = "Saving Data with EF" }, new Post { Title = "Cascade Delete with EF" } } }); db.SaveChanges(); } using (var db = new BloggingContext()) { var blog = db.Blogs.Include(b => b.Posts).First(); db.Remove(blog); db.SaveChanges(); } using (var db = new BloggingContext()) { db.Blogs.Add(new Blog { Url = "http://sample.com", Posts = new List<Post> { new Post { Title = "Saving Data with EF" }, new Post { Title = "Cascade Delete with EF" } } }); db.SaveChanges(); } using (var db = new BloggingContext()) { var blog = db.Blogs.First(); db.Remove(blog); db.SaveChanges(); } } } } <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Migrations/MyHistoryRepository.cs using System; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; namespace EntityFrameworkCore.RelationalProviderStarter.Migrations { public class MyHistoryRepository : HistoryRepository { public MyHistoryRepository( IDatabaseCreator databaseCreator, IRawSqlCommandBuilder rawSqlCommandBuilder, IRelationalConnection connection, IDbContextOptions options, IMigrationsModelDiffer modelDiffer, IMigrationsSqlGenerator migrationsSqlGenerator, IRelationalAnnotationProvider annotations, ISqlGenerationHelper sqlGenerationHelper) : base(databaseCreator, rawSqlCommandBuilder, connection, options, modelDiffer, migrationsSqlGenerator, annotations, sqlGenerationHelper ) { } protected override string ExistsSql { get { throw new NotImplementedException(); } } public override string GetBeginIfExistsScript(string migrationId) { throw new NotImplementedException(); } public override string GetBeginIfNotExistsScript(string migrationId) { throw new NotImplementedException(); } public override string GetCreateIfNotExistsScript() { throw new NotImplementedException(); } public override string GetEndIfScript() { throw new NotImplementedException(); } protected override bool InterpretExistsResult(object value) { throw new NotImplementedException(); } } }<file_sep>/ef/modeling/included-properties.md --- uid: modeling/included-properties --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Including & Excluding Properties Including a property in the model means that EF has metadata about that property and will attempt to read and write values from/to the database. ## Conventions By convention, public properties with a getter and a setter will be included in the model. ## Data Annotations You can use Data Annotations to exclude a property from the model. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/DataAnnotations/Samples/IgnoreProperty.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [6], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# public class Blog { public int BlogId { get; set; } public string Url { get; set; } [NotMapped] public DateTime LoadedFromDatabase { get; set; } } ```` ## Fluent API You can use the Fluent API to exclude a property from the model. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/FluentAPI/Samples/IgnoreProperty.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [7, 8], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .Ignore(b => b.LoadedFromDatabase); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public DateTime LoadedFromDatabase { get; set; } } ```` <file_sep>/samples/Modeling/DataAnnotations/Samples/Relationships/InverseProperty.cs using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace EFModeling.Configuring.DataAnnotations.Samples.Relationships.InverseProperty { class MyContext : DbContext { public DbSet<Post> Posts { get; set; } public DbSet<User> Users { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int AuthorUserId { get; set; } public User Author { get; set; } public int ContributorUserId { get; set; } public User Contributor { get; set; } } public class User { public string UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } [InverseProperty("Author")] public List<Post> AuthoredPosts { get; set; } [InverseProperty("Contributor")] public List<Post> ContributedToPosts { get; set; } } } <file_sep>/ef/querying/overview.md --- uid: querying/overview --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # How Query Works Entity Framework Core uses Language Integrate Query (LINQ) to query data from the database. LINQ allows you to use C# (or your .NET language of choice) to write strongly typed queries based on your derived context and entity classes. ## The life of a query The following is a high level overview of the process each query goes through. 1. The LINQ query is processed by Entity Framework Core to build a representation that is ready to be processed by the database provider 1. The result is cached so that this processing does not need to be done every time the query is executed 2. The result is passed to the database provider 1. The database provider identifies which parts of the query can be evaluated in the database 2. These parts of the query are translated to database specific query language (e.g. SQL for a relational database) 3. One or more queries are sent to the database and the result set returned (results are values from the database, not entity instances) 3. For each item in the result set 1. If this is a tracking query, EF checks if the data represents an entity already in the change tracker for the context instance * If so, the existing entity is returned * If not, a new entity is created, change tracking is setup, and the new entity is returned 2. If this is a no-tracking query, EF checks if the data represents an entity already in the result set for this query * If so, the existing entity is returned * If not, a new entity is created and returned ## When queries are executed When you call LINQ operators, you are simply building up an in-memory representation of the query. The query is only sent to the database when the results are consumed. The most common operations that result in the query being sent to the database are: * Iterating the results in a `for` loop * Using an operator such as `ToList`, `ToArray`, `Single`, `Count` * Databinding the results of a query to a UI <file_sep>/README.md Entity Framework Docs ===================== [![Build Status](https://travis-ci.org/aspnet/EntityFramework.Docs.svg?branch=master)](https://travis-ci.org/aspnet/EntityFramework.Docs) This project provides the source for [docs.efproject.net](http://docs.efproject.net/). **We accept pull requests!** However, before submitting a pull request, please [read the CONTRIBUTING guidelines](CONTRIBUTING.md), which include information on how to build the docs locally, as well as style and organizational guidance. <file_sep>/samples/Querying/Querying/ClientEval/Sample.cs using Microsoft.EntityFrameworkCore; using System.Linq; namespace EFQuerying.ClientEval { public class Sample { public static string StandardizeUrl(string url) { url = url.ToLower(); if (!url.StartsWith("http://")) { url = string.Concat("http://", url); } return url; } public static void Run() { using (var context = new BloggingContext()) { var blogs = context.Blogs .OrderByDescending(blog => blog.Rating) .Select(blog => new { Id = blog.BlogId, Url = StandardizeUrl(blog.Url) }) .ToList(); } using (var context = new BloggingContext()) { var blogs = context.Blogs .Where(blog => StandardizeUrl(blog.Url).Contains("dotnet")) .ToList(); } } } } <file_sep>/ef/modeling/relational/indexes.md --- uid: modeling/relational/indexes --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). Note: The configuration in this section is applicable to relational databases in general. The extension methods shown here will become available when you install a relational database provider (due to the shared *Microsoft.EntityFrameworkCore.Relational* package). # Indexes An index in a relational database maps to the same concept as an index in the core of Entity Framework. ## Conventions By convention, indexes are named `IX_<type name>_<property name>`. For composite indexes `<property name>` becomes an underscore separated list of property names. ## Data Annotations Indexes can not be configured using Data Annotations. ## Fluent API You can use the Fluent API to configure the name of an index. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/FluentAPI/Samples/Relational/IndexName.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [9], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .HasIndex(b => b.Url) .HasName("Index_Url"); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } } ```` <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.ProviderStarter/Query/ExpressionVisitors/MyEntityQueryableExpressionVisitor.cs using System; using System.Linq.Expressions; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors; using Remotion.Linq.Clauses; namespace EntityFrameworkCore.ProviderStarter.Query.ExpressionVisitors { internal class MyEntityQueryableExpressionVisitor : EntityQueryableExpressionVisitor { private EntityQueryModelVisitor _queryModelVisitor; private IQuerySource _querySource; public MyEntityQueryableExpressionVisitor(EntityQueryModelVisitor queryModelVisitor, IQuerySource querySource) : base(queryModelVisitor) { _queryModelVisitor = queryModelVisitor; _querySource = querySource; } protected override Expression VisitEntityQueryable(Type elementType) { throw new NotImplementedException(); } } }<file_sep>/samples/Saving/Saving/ExplicitValuesGenerateProperties/Sample.cs using Microsoft.EntityFrameworkCore; using System; namespace EFSaving.ExplicitValuesGenerateProperties { public class Sample { public static void Run() { using (var db = new EmployeeContext()) { db.Database.EnsureDeleted(); db.Database.EnsureCreated(); } using (var db = new EmployeeContext()) { db.Employees.Add(new Employee { Name = "<NAME>" }); db.Employees.Add(new Employee { Name = "<NAME>", EmploymentStarted = new DateTime(2000, 1, 1) }); db.SaveChanges(); foreach (var employee in db.Employees) { Console.WriteLine(employee.EmployeeId + ": " + employee.Name + ", " + employee.EmploymentStarted); } } using (var db = new EmployeeContext()) { db.Database.EnsureDeleted(); db.Database.EnsureCreated(); } using (var db = new EmployeeContext()) { db.Employees.Add(new Employee { EmployeeId = 100, Name = "<NAME>" }); db.Employees.Add(new Employee { EmployeeId = 101, Name = "<NAME>" }); db.Database.OpenConnection(); try { db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Employee ON"); db.SaveChanges(); db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Employee OFF"); } finally { db.Database.CloseConnection(); } foreach (var employee in db.Employees) { Console.WriteLine(employee.EmployeeId + ": " + employee.Name); } } } } } <file_sep>/ef/modeling/relational/inheritance.md --- uid: modeling/relational/inheritance --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). Note: The configuration in this section is applicable to relational databases in general. The extension methods shown here will become available when you install a relational database provider (due to the shared *Microsoft.EntityFrameworkCore.Relational* package). # Inheritance (Relational Database) Inheritance in the EF model is used to control how inheritance in the entity classes is represented in the database. ## Conventions By convention, inheritance will be mapped using the table-per-hierarchy (TPH) pattern. TPH uses a single table to store the data for all types in the hierarchy. A discriminator column is used to identify which type each row represents. EF will only setup inheritance if two or more inherited types are explicitly included in the model (see [Inheritance](../inheritance.md) for more details). Below is an example showing a simple inheritance scenario and the data stored in a relational database table using the TPH pattern. The *Discriminator* column identifies which type of *Blog* is stored in each row. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/Conventions/Samples/InheritanceDbSets.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<RssBlog> RssBlogs { get; set; } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } } public class RssBlog : Blog { public string RssUrl { get; set; } } ```` ![image](relational/_static/inheritance-tph-data.png) ## Data Annotations You cannot use Data Annotations to configure inheritance. ## Fluent API You can use the Fluent API to configure the name and type of the discriminator column and the values that are used to identify each type in the hierarchy. <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/relational/Modeling/FluentAPI/Samples/InheritanceTPHDiscriminator.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [7, 8, 9, 10], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .HasDiscriminator<string>("blog_type") .HasValue<Blog>("blog_base") .HasValue<RssBlog>("blog_rss"); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } } public class RssBlog : Blog { public string RssUrl { get; set; } } ```` <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Extensions/MyRelationalProviderDbContextOptionsExtensions.cs using EntityFrameworkCore.RelationalProviderStarter.Infrastructure; using Microsoft.EntityFrameworkCore.Infrastructure; namespace Microsoft.EntityFrameworkCore { public static class MyRelationalProviderDbContextOptionsExtensions { public static DbContextOptionsBuilder UseMyRelationalProvider(this DbContextOptionsBuilder optionsBuilder, string connectionString) { ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension( new MyRelationalProviderOptionsExtension { ConnectionString = connectionString }); return optionsBuilder; } } }<file_sep>/ef/modeling/indexes.md --- uid: modeling/indexes --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Indexes Indexes are a common concept across many data stores. While their implementation in the data store may vary, they are used to make lookups based on a column (or set of columns) more efficient. ## Conventions By convention, an index is created in each property (or set of properties) that are used as a foreign key. ## Data Annotations Indexes can not be created using data annotations. ## Fluent API You can use the Fluent API specify an index on a single property. By default, indexes are non-unique. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [7, 8]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/FluentAPI/Samples/Index.cs"} --> ````c# class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .HasIndex(b => b.Url); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } } ```` You can also specify that an index should be unique, meaning that no two entities can have the same value(s) for the given property(s). <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [3]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/FluentAPI/Samples/IndexUnique.cs"} --> ````c# modelBuilder.Entity<Blog>() .HasIndex(b => b.Url) .IsUnique(); ```` You can also specify an index over more than one column. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [7, 8]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/modeling/Modeling/FluentAPI/Samples/IndexComposite.cs"} --> ````c# class MyContext : DbContext { public DbSet<Person> People { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Person>() .HasIndex(p => new { p.FirstName, p.LastName }); } } public class Person { public int PersonId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } ```` Note: There is only one index per distinct set of properties. If you use the Fluent API to configure an index on a set of properties that already has an index defined, either by convention or previous configuration, then you will be changing the definition of that index. This is useful if you want to further configure an index that was created by convention. <file_sep>/ef/efcore-vs-ef6/porting/port-edmx.md --- uid: efcore-vs-ef6/porting/port-edmx --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Porting an EDMX-Based Model (Model First & Database First) EF Core does not support the EDMX file format for models. The best option to port these models, is to generate a new code-based model from the database for your application. ## Install EF Core NuGet packages Install the `Microsoft.EntityFrameworkCore.Tools` NuGet package. You also need to install the **design time** NuGet package for the database provider you want to use. This is typically the runtime database provider package name with `.Design` post-fixed. For example, when targeting SQL Server, you would install `Microsoft.EntityFrameworkCore.SqlServer.Design`. See [Database Providers](../../providers/index.md) for details. ## Regenerate the model You can now use the reverse engineer functionality to create a model based on your existing database. Run the following command in Package Manager Console (Tools –> NuGet Package Manager –> Package Manager Console). See [Package Manager Console (Visual Studio)](../../miscellaneous/cli/powershell.md) for command options to scaffold a subset of tables etc. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "text", "highlight_args": {}, "names": []} --> ````text Scaffold-DbContext "<connection string>" <database provider name> ```` For example, here is the command to scaffold a model from the Blogging database on your SQL Server LocalDB instance. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "text", "highlight_args": {}, "names": []} --> ````text Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer ```` ## Remove EF6.x model You would now remove the EF6.x model from your application. It is fine to leave the EF6.x NuGet package (EntityFramework) installed, as EF Core and EF6.x can be used side-by-side in the same application. However, if you aren't intending to use EF6.x in any areas of your application, then uninstalling the package will help give compile errors on pieces of code that need attention. ## Update your code At this point, it's a matter of addressing compilation errors and reviewing code to see if the behavior changes between EF6.x and EF Core will impact you. ## Test the port Just because your application compiles, does not mean it is successfully ported to EF Core. You will need to test all areas of your application to ensure that none of the behavior changes have adversely impacted your application. <file_sep>/ef/providers/oracle/index.md --- uid: providers/oracle/index --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Oracle (Coming Soon) The Oracle .NET team is evaluating EF Core support, but have not announced any timing. You can vote on the [Oracle EF Core Provider feature request](https://apex.oracle.com/pls/apex/f?p=18357:39:105422858407495::NO::P39_ID:28241). Please direct any questions about this provider, including the release timeline, to the [Oracle Community Site](https://community.oracle.com/). <file_sep>/ef/platforms/aspnetcore/index.md --- uid: platforms/aspnetcore/index --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Getting Started on ASP.NET Core These 101 tutorials require no previous knowledge of Entity Framework (EF) or Visual Studio. They will take you step-by-step through creating a simple application that queries and saves data from a database. Entity Framework can create a model based on an existing database, or create a database for you based on your model. The following tutorials will demonstrate both of these approaches using an ASP.NET Core application. ## Available Tutorials * [ASP.NET Core Application to New Database](new-db.md) * [ASP.NET Core Application to Existing Database (Database First)](existing-db.md) * [Entity Framework Core tutorial on ASP.NET Core site](https://docs.asp.net/en/latest/data/ef-mvc/intro.html.md) <file_sep>/samples/Querying/Querying/Basics/Sample.cs using System.Linq; namespace EFQuerying.Basics { public class Sample { public static void Run() { using (var context = new BloggingContext()) { var blogs = context.Blogs.ToList(); } using (var context = new BloggingContext()) { var blog = context.Blogs .Single(b => b.BlogId == 1); } using (var context = new BloggingContext()) { var blogs = context.Blogs .Where(b => b.Url.Contains("dotnet")) .ToList(); } } } } <file_sep>/samples/Saving/Saving/Program.cs namespace EFSaving { class Program { static void Main(string[] args) { Basics.Sample.Run(); RelatedData.Sample.Run(); CascadeDelete.Sample.Run(); Concurrency.Sample.Run(); Transactions.ControllingTransaction.Sample.Run(); Transactions.SharingTransaction.Sample.Run(); Transactions.ExternalDbTransaction.Sample.Run(); ExplicitValuesGenerateProperties.Sample.Run(); } } } <file_sep>/ef/platforms/aspnetcore/new-db.md --- uid: platforms/aspnetcore/new-db --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # ASP.NET Core Application to New Database In this walkthrough, you will build an ASP.NET Core MVC application that performs basic data access using Entity Framework. You will use migrations to create the database from your model. Tip: You can view this article's [sample](https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/Platforms/AspNetCore/AspNetCore.NewDb) on GitHub. ## Prerequisites The following prerequisites are needed to complete this walkthrough: * [Visual Studio 2015 Update 3](https://go.microsoft.com/fwlink/?LinkId=691129) * [.NET Core for Visual Studio](https://go.microsoft.com/fwlink/?LinkId=817245) ## Create a new project * Open Visual Studio 2015 * File ‣ New ‣ Project... * From the left menu select Templates ‣ Visual C# ‣ Web * Select the **ASP.NET Core Web Application (.NET Core)** project template * Enter **EFGetStarted.AspNetCore.NewDb** as the name and click **OK** * Wait for the **New ASP.NET Core Web Application** dialog to appear * Select the **Web Application** template and ensure that **Authentication** is set to **No Authentication** * Click **OK** Caution: If you use **Individual User Accounts** instead of **None** for **Authentication** then an Entity Framework model will be added to your project in *Models\IdentityModel.cs*. Using the techniques you will learn in this walkthrough, you can choose to add a second model, or extend this existing model to contain your entity classes. ## Install Entity Framework To use EF Core, install the package for the database provider(s) you want to target. This walkthrough uses SQL Server. For a list of available providers see [Database Providers](../../providers/index.md). * Tools ‣ NuGet Package Manager ‣ Package Manager Console * Run `Install-Package Microsoft.EntityFrameworkCore.SqlServer` Note: In ASP.NET Core projects the `Install-Package` command will complete quickly and the package installation will occur in the background. You will see **(Restoring...)** appear next to **References** in **Solution Explorer** while the install occurs. Later in this walkthrough we will also be using some Entity Framework commands to maintain the database. So we will install the commands package as well. * Run `Install-Package Microsoft.EntityFrameworkCore.Tools –Pre` * Open **project.json** * Locate the `tools` section and add the `ef` command as shown below <!-- literal_block {"source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/aspnetcore/Platforms/AspNetCore/AspNetCore.NewDb/project.json", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [2], "linenostart": 1}, "ids": [], "linenos": true} --> ```` "tools": { "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final", "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final", "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final" }, ```` ## Create your model Now it's time to define a context and entity classes that make up your model. * Right-click on the project in **Solution Explorer** and select Add ‣ New Folder * Enter **Models** as the name of the folder * Right-click on the **Models** folder and select Add ‣ New Item... * From the left menu select Installed ‣ Code * Select the **Class** item template * Enter **Model.cs** as the name and click **OK** * Replace the contents of the file with the following code <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/aspnetcore/Platforms/AspNetCore/AspNetCore.NewDb/Models/Model.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ````c# using Microsoft.EntityFrameworkCore; using System.Collections.Generic; namespace EFGetStarted.AspNetCore.NewDb.Models { public class BloggingContext : DbContext { public BloggingContext(DbContextOptions<BloggingContext> options) : base(options) { } public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List<Post> Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } } } ```` Note: In a real application you would typically put each class from your model in a separate file. For the sake of simplicity, we are putting all the classes in one file for this tutorial. ## Register your context with dependency injection The concept of dependency injection is central to ASP.NET Core. Services (such as `BloggingContext`) are registered with dependency injection during application startup. Components that require these services (such as your MVC controllers) are then provided these services via constructor parameters or properties. For more information on dependency injection see the [Dependency Injection](http://docs.asp.net/en/latest/fundamentals/dependency-injection.html) article on the ASP.NET site. In order for our MVC controllers to make use of `BloggingContext` we are going to register it as a service. * Open **Startup.cs** * Add the following `using` statements at the start of the file <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/aspnetcore/Platforms/AspNetCore/AspNetCore.NewDb/Startup.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ````c# using EFGetStarted.AspNetCore.NewDb.Models; using Microsoft.EntityFrameworkCore; ```` Now we can use the `AddDbContext` method to register it as a service. * Locate the `ConfigureServices` method * Add the lines that are highlighted in the following code <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/aspnetcore/Platforms/AspNetCore/AspNetCore.NewDb/Startup.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"hl_lines": [3, 4], "linenostart": 1}, "ids": [], "linenos": true} --> ````c# public void ConfigureServices(IServiceCollection services) { var connection = @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNetCore.NewDb;Trusted_Connection=True;"; services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection)); ```` ## Create your database Now that you have a model, you can use migrations to create a database for you. * Tools –> NuGet Package Manager –> Package Manager Console * Run `Add-Migration MyFirstMigration` to scaffold a migration to create the initial set of tables for your model. If you receive an error stating the term 'add-migration' is not recognized as the name of a cmdlet, then close and reopen Visual Studio * Run `Update-Database` to apply the new migration to the database. Because your database doesn't exist yet, it will be created for you before the migration is applied. Tip: If you make future changes to your model, you can use the `Add-Migration` command to scaffold a new migration to make the corresponding schema changes to the database. Once you have checked the scaffolded code (and made any required changes), you can use the `Update-Database` command to apply the changes to the database.EF uses a `__EFMigrationsHistory` table in the database to keep track of which migrations have already been applied to the database. ## Create a controller Next, we'll add an MVC controller that will use EF to query and save data. * Right-click on the **Controllers** folder in **Solution Explorer** and select Add ‣ New Item... * From the left menu select Installed ‣ Server-side * Select the **Class** item template * Enter **BlogsController.cs** as the name and click **OK** * Replace the contents of the file with the following code <!-- literal_block {"language": "c#", "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/aspnetcore/Platforms/AspNetCore/AspNetCore.NewDb/Controllers/BlogsController.cs", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ````c# using EFGetStarted.AspNetCore.NewDb.Models; using Microsoft.AspNetCore.Mvc; using System.Linq; namespace EFGetStarted.AspNetCore.NewDb.Controllers { public class BlogsController : Controller { private BloggingContext _context; public BlogsController(BloggingContext context) { _context = context; } public IActionResult Index() { return View(_context.Blogs.ToList()); } public IActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Create(Blog blog) { if (ModelState.IsValid) { _context.Blogs.Add(blog); _context.SaveChanges(); return RedirectToAction("Index"); } return View(blog); } } } ```` You'll notice that the controller takes a `BloggingContext` as a constructor parameter. ASP.NET dependency injection will take care of passing an instance of `BloggingContext` into your controller. The controller contains an `Index` action, which displays all blogs in the database, and a `Create` action, which inserts a new blogs into the database. ## Create views Now that we have a controller it's time to add the views that will make up the user interface. We'll start with the view for our `Index` action, that displays all blogs. * Right-click on the **Views** folder in **Solution Explorer** and select Add ‣ New Folder * Enter **Blogs** as the name of the folder * Right-click on the **Blogs** folder and select Add ‣ New Item... * From the left menu select Installed ‣ ASP.NET * Select the **MVC View Page** item template * Enter **Index.cshtml** as the name and click **Add** * Replace the contents of the file with the following code <!-- literal_block {"source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/aspnetcore/Platforms/AspNetCore/AspNetCore.NewDb/Views/Blogs/Index.cshtml", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ```` @model IEnumerable<EFGetStarted.AspNetCore.NewDb.Models.Blog> @{ ViewBag.Title = "Blogs"; } <h2>Blogs</h2> <p> <a asp-controller="Blogs" asp-action="Create">Create New</a> </p> <table class="table"> <tr> <th>Id</th> <th>Url</th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.BlogId) </td> <td> @Html.DisplayFor(modelItem => item.Url) </td> </tr> } </table> ```` We'll also add a view for the `Create` action, which allows the user to enter details for a new blog. * Right-click on the **Blogs** folder and select Add ‣ New Item... * From the left menu select Installed ‣ ASP.NET Core * Select the **MVC View Page** item template * Enter **Create.cshtml** as the name and click **Add** * Replace the contents of the file with the following code <!-- literal_block {"source": "/Users/shirhatti/src/EntityFramework.Docs/docs/platforms/aspnetcore/Platforms/AspNetCore/AspNetCore.NewDb/Views/Blogs/Create.cshtml", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {"linenostart": 1}, "ids": [], "linenos": true} --> ```` @model EFGetStarted.AspNetCore.NewDb.Models.Blog @{ ViewBag.Title = "New Blog"; } <h2>@ViewData["Title"]</h2> <form asp-controller="Blogs" asp-action="Create" method="post" class="form-horizontal" role="form"> <div class="form-horizontal"> <div asp-validation-summary="All" class="text-danger"></div> <div class="form-group"> <label asp-for="Url" class="col-md-2 control-label"></label> <div class="col-md-10"> <input asp-for="Url" class="form-control" /> <span asp-validation-for="Url" class="text-danger"></span> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> </form> ```` ## Run the application You can now run the application to see it in action. * Debug ‣ Start Without Debugging * The application will build and open in a web browser * Navigate to **/Blogs** * Click **Create New** * Enter a **Url** for the new blog and click **Create** ![image](aspnetcore/_static/create.png) ![image](aspnetcore/_static/index-new-db.png) <file_sep>/ef/providers/pomelo/index.md --- uid: providers/pomelo/index --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Pomelo (MySQL) This database provider allows Entity Framework Core to be used with MySQL. The provider is maintained as part of the [Pomelo Foundation Project](https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql). Note: This provider is not maintained as part of the Entity Framework Core project. When considering a third party provider, be sure to evaluate quality, licensing, support, etc. to ensure they meet your requirements. ## Install Install the [Pomelo.EntityFrameworkCore.MySQL NuGet package](https://www.nuget.org/packages/Pomelo.EntityFrameworkCore.MySQL). <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": false, "dupnames": [], "language": "text", "highlight_args": {}, "names": []} --> ````text PM> Install-Package Pomelo.EntityFrameworkCore.MySQL ```` ## Get Started The following resources will help you get started with this provider. * [Getting started documentation](https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql/blob/master/README.md#getting-started) * [Yuuko Blog sample application](https://github.com/Kagamine/YuukoBlog-NETCore-MySql) ## Supported Database Engines * MySQL ## Supported Platforms * Full .NET (4.5.1 onwards) * .NET Core * Mono (4.2.0 onwards) <file_sep>/ef/miscellaneous/cli/powershell.md --- uid: miscellaneous/cli/powershell --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Package Manager Console (Visual Studio) EF command line tools for Visual Studio's Package Manager Console (PMC) window. Caution: The commands require the [latest version of Windows PowerShell](https://www.microsoft.com/en-us/download/details.aspx?id=50395) ## Installation Package Manager Console commands are installed with the *Microsoft.EntityFrameworkCore.Tools* package. To open the console, follow these steps. * Open Visual Studio 2015 * Tools ‣ Nuget Package Manager ‣ Package Manager Console * Execute `Install-Package Microsoft.EntityFrameworkCore.Tools -Pre` ### .NET Core and ASP.NET Core Projects .NET Core and ASP.NET Core projects also require installing .NET Core CLI. See [.NET Core CLI](dotnet.md) for more information about this installation. Note: .NET Core CLI has known issues in Preview 1. Because PMC commands call .NET Core CLI commands, these known issues also apply to PMC commands. See [Preview 2 Known Issues](dotnet.md#dotnet-cli-issues.md). Tip: On .NET Core and ASP.NET Core projects, add `-Verbose` to any Package Manager Console command to see the equivalent .NET Core CLI command that was invoked. ## Usage Note: All commands support the common parameters: `-Verbose`, `-Debug`, `-ErrorAction`, `-ErrorVariable`, `-WarningAction`, `-WarningVariable`, `-OutBuffer`, `-PipelineVariable`, and `-OutVariable`. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ### Add-Migration Adds a new migration. <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text SYNTAX Add-Migration [-Name] <String> [-OutputDir <String>] [-Context <String>] [-Project <String>] [-StartupProject <String>] [-Environment <String>] [<CommonParameters>] PARAMETERS -Name <String> Specifies the name of the migration. -OutputDir <String> The directory (and sub-namespace) to use. If omitted, "Migrations" is used. Relative paths are relative to project directory. -Context <String> Specifies the DbContext to use. If omitted, the default DbContext is used. -Project <String> Specifies the project to use. If omitted, the default project is used. -StartupProject <String> Specifies the startup project to use. If omitted, the solution's startup project is used. -Environment <String> Specifies the environment to use. If omitted, "Development" is used. ```` ### Remove-Migration Removes the last migration. <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text SYNTAX Remove-Migration [-Context <String>] [-Project <String>] [-StartupProject <String>] [-Environment <String>] [-Force] [<CommonParameters>] PARAMETERS -Context <String> Specifies the DbContext to use. If omitted, the default DbContext is used. -Project <String> Specifies the project to use. If omitted, the default project is used. -StartupProject <String> Specifies the startup project to use. If omitted, the solution's startup project is used. -Environment <String> Specifies the environment to use. If omitted, "Development" is used. -Force [<SwitchParameter>] Removes the last migration without checking the database. If the last migration has been applied to the database, you will need to manually reverse the changes it made. ```` ### Scaffold-DbContext Scaffolds a DbContext and entity type classes for a specified database. <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text SYNTAX Scaffold-DbContext [-Connection] <String> [-Provider] <String> [-OutputDir <String>] [-Context <String>] [-Schemas <String>] [-Tables <String>] [-DataAnnotations] [-Force] [-Project <String>] [-StartupProject <String>] [-Environment <String>] [<CommonParameters>] PARAMETERS -Connection <String> Specifies the connection string of the database. -Provider <String> Specifies the provider to use. For example, Microsoft.EntityFrameworkCore.SqlServer. -OutputDir <String> Specifies the directory to use to output the classes. If omitted, the top-level project directory is used. -Context <String> Specifies the name of the generated DbContext class. -Schemas <String> Specifies the schemas for which to generate classes. -Tables <String> Specifies the tables for which to generate classes. -DataAnnotations [<SwitchParameter>] Use DataAnnotation attributes to configure the model where possible. If omitted, the output code will use only the fluent API. -Force [<SwitchParameter>] Force scaffolding to overwrite existing files. Otherwise, the code will only proceed if no output files would be overwritten. -Project <String> Specifies the project to use. If omitted, the default project is used. -StartupProject <String> Specifies the startup project to use. If omitted, the solution's startup project is used. -Environment <String> Specifies the environment to use. If omitted, "Development" is used. ```` ### Script-Migration Generates a SQL script from migrations. <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text SYNTAX Script-Migration -From <String> -To <String> [-Idempotent] [-Context <String>] [-Project <String>] [-StartupProject <String>] [-Environment <String>] [<CommonParameters>] Script-Migration [-From <String>] [-Idempotent] [-Context <String>] [-Project <String>] [-StartupProject <String>] [-Environment <String>] [<CommonParameters>] PARAMETERS -From <String> Specifies the starting migration. If omitted, '0' (the initial database) is used. -To <String> Specifies the ending migration. If omitted, the last migration is used. -Idempotent [<SwitchParameter>] Generates an idempotent script that can be used on a database at any migration. -Context <String> Specifies the DbContext to use. If omitted, the default DbContext is used. -Project <String> Specifies the project to use. If omitted, the default project is used. -StartupProject <String> Specifies the startup project to use. If omitted, the solution's startup project is used. -Environment <String> Specifies the environment to use. If omitted, "Development" is used. ```` ### Update-Database Updates the database to a specified migration. <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text SYNTAX Update-Database [[-Migration] <String>] [-Context <String>] [-Project <String>] [-StartupProject <String>] [-Environment <String>] [<CommonParameters>] PARAMETERS -Migration <String> Specifies the target migration. If '0', all migrations will be reverted. If omitted, all pending migrations will be applied. -Context <String> Specifies the DbContext to use. If omitted, the default DbContext is used. -Project <String> Specifies the project to use. If omitted, the default project is used. -StartupProject <String> Specifies the startup project to use. If omitted, the solution's startup project is used. -Environment <String> Specifies the environment to use. If omitted, "Development" is used. ```` ### Use-DbContext Sets the default DbContext to use. <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text SYNTAX Use-DbContext [-Context] <String> [-Project <String>] [-StartupProject <String>] [-Environment <String>] [<CommonParameters>] PARAMETERS -Context <String> Specifies the DbContext to use. -Project <String> Specifies the project to use. If omitted, the default project is used. -StartupProject <String> Specifies the startup project to use. If omitted, the solution's startup project is used. -Environment <String> Specifies the environment to use. If omitted, "Development" is used. ```` ## Using EF Core commands and EF 6 commands side-by-side EF Core commands do not work on EF 6 or earlier version of EF. However, EF Core re-uses some of the same command names from these earlier versions. These commands can be installed side-by-side, however, EF does not automatically know which version of the command to use. This is solved by prefixing the command with the module name. The EF 6 commands PowerShell module is named "EntityFramework", and the EF Core module is named "EntityFrameworkCore". Without the prefix, PowerShell may call the wrong version of the command. <!-- literal_block {"language": "PowerShell", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````PowerShell # Invokes the EF Core command PS> EntityFrameworkCore\Add-Migration # Invokes the EF 6 command PS> EntityFramework\Add-Migration ```` ## Common Errors ### Error: "No parameterless constructor was found" Design-time tools attempt to automatically find how your application creates instances of your DbContext type. If EF cannot find a suitable way to initialize your DbContext, you may encounter this error. <!-- literal_block {"language": "text", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````text No parameterless constructor was found on 'TContext'. Either add a parameterless constructor to 'TContext' or add an implementation of 'IDbContextFactory<TContext>' in the same assembly as 'TContext'. ```` As the error message suggests, one solution is to add an implementation of `IDbContextFactory<TContext>` to the current project. See [Using IDbContextFactory<TContext>](../configuring-dbcontext.md#use-idbcontextfactory.md) for an example of how to create this factory. See also [Preview 2 Known Issues](dotnet.md#dotnet-cli-issues.md) for .NET Core CLI commands. <file_sep>/ef/saving/disconnected-entities.md --- uid: saving/disconnected-entities --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # 🔧 Disconnected Entities Note: This topic hasn't been written yet! You can track the status of this [issue](https://github.com/aspnet/EntityFramework.Docs/issues/126) through our public GitHub issue tracker. Learn how you can [contribute](https://github.com/aspnet/EntityFramework.Docs/blob/master/CONTRIBUTING.md) on GitHub. <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.ProviderStarter/Query/MyEntityQueryModelVisitorFactory.cs using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors; using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal; using Microsoft.EntityFrameworkCore.Query.Internal; namespace EntityFrameworkCore.ProviderStarter.Query { public class MyEntityQueryModelVisitorFactory : EntityQueryModelVisitorFactory { public MyEntityQueryModelVisitorFactory( IQueryOptimizer queryOptimizer, INavigationRewritingExpressionVisitorFactory navigationRewritingExpressionVisitorFactory, ISubQueryMemberPushDownExpressionVisitor subQueryMemberPushDownExpressionVisitor, IQuerySourceTracingExpressionVisitorFactory querySourceTracingExpressionVisitorFactory, IEntityResultFindingExpressionVisitorFactory entityResultFindingExpressionVisitorFactory, ITaskBlockingExpressionVisitor taskBlockingExpressionVisitor, IMemberAccessBindingExpressionVisitorFactory memberAccessBindingExpressionVisitorFactory, IOrderingExpressionVisitorFactory orderingExpressionVisitorFactory, IProjectionExpressionVisitorFactory projectionExpressionVisitorFactory, IEntityQueryableExpressionVisitorFactory entityQueryableExpressionVisitorFactory, IQueryAnnotationExtractor queryAnnotationExtractor, IResultOperatorHandler resultOperatorHandler, IEntityMaterializerSource entityMaterializerSource, IExpressionPrinter expressionPrinter) : base( queryOptimizer, navigationRewritingExpressionVisitorFactory, subQueryMemberPushDownExpressionVisitor, querySourceTracingExpressionVisitorFactory, entityResultFindingExpressionVisitorFactory, taskBlockingExpressionVisitor, memberAccessBindingExpressionVisitorFactory, orderingExpressionVisitorFactory, projectionExpressionVisitorFactory, entityQueryableExpressionVisitorFactory, queryAnnotationExtractor, resultOperatorHandler, entityMaterializerSource, expressionPrinter) { } public override EntityQueryModelVisitor Create(QueryCompilationContext queryCompilationContext, EntityQueryModelVisitor parentEntityQueryModelVisitor) => new MyEntityQueryModelVisitor(QueryOptimizer, NavigationRewritingExpressionVisitorFactory, SubQueryMemberPushDownExpressionVisitor, QuerySourceTracingExpressionVisitorFactory, EntityResultFindingExpressionVisitorFactory, TaskBlockingExpressionVisitor, MemberAccessBindingExpressionVisitorFactory, OrderingExpressionVisitorFactory, ProjectionExpressionVisitorFactory, EntityQueryableExpressionVisitorFactory, QueryAnnotationExtractor, ResultOperatorHandler, EntityMaterializerSource, ExpressionPrinter, queryCompilationContext); } }<file_sep>/ef/providers/in-memory/index.md --- uid: providers/in-memory/index --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # InMemory (for Testing) This database provider allows Entity Framework Core to be used with an in-memory database. This is useful when testing code that uses Entity Framework Core. The provider is maintained as part of the [EntityFramework GitHub project](https://github.com/aspnet/EntityFramework). ## Install Install the [Microsoft.EntityFrameworkCore.InMemory NuGet package](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.InMemory/). <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": false, "dupnames": [], "language": "text", "highlight_args": {}, "names": []} --> ````text PM> Install-Package Microsoft.EntityFrameworkCore.InMemory ```` ## Get Started The following resources will help you get started with this provider. * [Testing with InMemory](../../miscellaneous/testing.md) * [UnicornStore Sample Application Tests](https://github.com/rowanmiller/UnicornStore/blob/master/UnicornStore/src/UnicornStore.Tests/Controllers/ShippingControllerTests.cs) ## Supported Database Engines * Built-in in-memory database (designed for testing purposes only) ## Supported Platforms * Full .NET (4.5.1 onwards) * .NET Core * Mono (4.2.0 onwards) * Universal Windows Platform <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.ProviderStarter/Extensions/MyProviderDbContextOptionsExtensions.cs using EntityFrameworkCore.ProviderStarter.Infrastructure; using Microsoft.EntityFrameworkCore.Infrastructure; namespace Microsoft.EntityFrameworkCore { public static class MyProviderDbContextOptionsExtensions { public static DbContextOptionsBuilder UseMyProvider(this DbContextOptionsBuilder optionsBuilder, string connectionString) { ((IDbContextOptionsBuilderInfrastructure) optionsBuilder).AddOrUpdateExtension( new MyProviderOptionsExtension { ConnectionString = connectionString }); return optionsBuilder; } } }<file_sep>/ef/miscellaneous/internals/services.md --- uid: miscellaneous/internals/services --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Understanding EF Services Entity Framework executes as a collection of services working together. A service is a reusable component. A service is typically an implementation of an interface. Services are available to other services via [dependency injection (DI)](https://wikipedia.org/wiki/Dependency_injection), which is implemented in EF using [Microsoft.Extensions.DependencyInjection](https://docs.asp.net/en/latest/fundamentals/dependency-injection.html). This article covers some fundamentals principles for understanding how EF uses services and DI. ## Terms Service A reusable component. In .NET, a service can be identified by a class or interface. By convention, Entity Framework only uses interfaces to identify services. Service lifetime A description of the way in which a service is persisted and disposed across multiple uses of the same service type. Service provider The mechanism for storing a collection of services. Also known as a service container. Service collection The mechanism for constructing a service provider. ## Categories of Services Services fall into one or more categories. Context services Services that are related to a specific instance of `DbContext`. They provide functionality for working with the user model and context options. Provider services Provider-specific implementations of services. For example, SQLite uses "provider services" to customize the behavior of SQL generation, migrations, and file I/O. Design-time services Services used when a developer is creating an application. For example, EF commands uses design-time services to execute migrations and code generation (aka scaffolding). User services A user can define custom services to interact with EF. These are written in application code, not provider code. For example, users can provide an implementation of `IModelCustomizer` for controlling how a model is created. Note: Service provider is not to be confused with a "provider's services". ## Service Lifetime EF services can be registered with different lifetime options. The suitable option depends on how the service is used and implemented. Transient Transient lifetime services are created each time they are injected into other services. This isolates each instance of the service. For example, `MigrationsScaffolder` should not be reused, therefore it is registered as transient. Scoped Scoped lifetime services are created once per `DbContext` instance. This is used to isolate instance of `DbContext`. For example, `StateManager` is added as scoped because it should only track entity states for one context. Singleton Singleton lifetime services exists once per service provider and span all scopes. Each time the service is injected, the same instance is used. For example, `IModelCustomizer` is a singleton because it is idempotent, meaning each call to `IModelCustomizer.Customize()` does not change the customizer. ## How AddDbContext works EF provides an extension method `AddDbContext<TContext>()` for adding using EF into a service collection. This method adds the following into a service collection: * `TContext` as "scoped" * `DbContextOptions` as a "singleton" * `DbContextOptionsFactory<T>` as a "singleton" `AddDbContext` does not add any context services, provider services, or design-time services to the service collection (except for [special cases](#special-cases)). DbContext constructs its own internal service provider for this. ### Special cases `AddDbContext` adds `DbContextOptionsFactory<T>` to the service collection AddDbContext was called on (which is used to create the "external" service provider). `DbContextOptionsFactory<T>` acts as a bridge between the external service provider and DbContext's internal service provider. If the external provider has services for `ILoggerFactory` or `IMemoryCache`, these will be added to the internal service provider. The bridging is done for these common scenarios so users can easily configure logging and memory caching without needing to provide a custom internal service provider. ## DbContext's internal service provider By default, `DbContext` uses an internal service provider that is **separate** from all other service providers in the application. This internal provider is constructed from an instance of `DbContextOptions`. Methods such as `UseSqlServer()` extend the construction step add specialized services for their database system. ### Providing a custom internal service provider `DbContextOptionsBuilder` provides an API for giving a custom service provider to DbContext for EF to use internally. This API is `DbContextOptions.UseInternalServiceProvider(IServiceProvider provider)`. If a custom service provider is provided, DbContext will not use `DbContextOptions` to create its own internal service provider. The custom service provider must already have provider-specific services added. Database provider writers should provided methods such as AddEntityFrameworkSqlServer" or "AddEntityFrameworkSqlite" to simplify the process of creating a custom service container. <!-- literal_block {"language": "csharp", "xml:space": "preserve", "classes": [], "backrefs": [], "names": [], "dupnames": [], "highlight_args": {}, "ids": [], "linenos": false} --> ````csharp var services = new ServiceCollection() .AddEntityFrameworkSqlServer() .AddSingleton<MyCustomService>() .BuildServiceProvider(); var options = new DbContextOptionsBuilder(); options .UseInternalServiceProvider(services) .UseSqlServer(connectionString); using (var context = new DbContext(options)) { } ```` ### Service provider caching EF caches this internal service provider with `IDbContextOptions` as the key. This means the service provider is only created once per unique set of options. It is reused when a DbContext is instantiated using a set of options that have already been used during the application lifetime. ## Required Provider Services EF database providers must register a basic set of services. These required services are defined as properties on `IDatabaseProviderServices`. Provider writers may need to implement some services from scratch. Others have partial or complete implementations in EF's library that can be reused. For more information on required provider services, see [Writing a Database Provider](writing-a-provider.md). ## Additional Information EF uses ` the Microsoft.Extensions.DependencyInjection library <[https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection/](https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection/)>`_ to implement DI. Documentation for this library [is available on docs.asp.net](https://docs.asp.net/en/latest/fundamentals/dependency-injection.html). ["System.IServiceProvider"](http://dotnet.github.io/api/System.IServiceProvider.html) is defined in the .NET base class library. <file_sep>/ef/efcore-vs-ef6/porting/port-code.md --- uid: efcore-vs-ef6/porting/port-code --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Porting a Code-Based Model (Code First & Code First to Existing Database) If you've read all the caveats and you are ready to port, then here are some guidelines to help you get started. ## Install EF Core NuGet packages To use EF Core, you install the NuGet package for the database provider you want to use. For example, when targeting SQL Server, you would install `Microsoft.EntityFrameworkCore.SqlServer`. See [Database Providers](../../providers/index.md) for details. If you are planning to use migrations, then you should also install the `Microsoft.EntityFrameworkCore.Tools` package. It is fine to leave the EF6.x NuGet package (EntityFramework) installed, as EF Core and EF6.x can be used side-by-side in the same application. However, if you aren't intending to use EF6.x in any areas of your application, then uninstalling the package will help give compile errors on pieces of code that need attention. ## Swap namespaces Most APIs that you use in EF6.x are in the `System.Data.Entity` namespace (and related sub-namespaces). The first code change is to swap to the `Microsoft.EntityFrameworkCore` namespace. You would typically start with your derived context code file and then work out from there, addressing compilation errors as they occur. ## Context configuration (connection etc.) As described in [Ensure EF Core Will Work for Your Application](ensure-requirements.md), EF Core has less magic around detecting the database to connect to. You will need to override the `OnConfiguring` method on your derived context, and use the database provider specific API to setup the connection to the database. Most EF6.x applications store the connection string in the applications `App/Web.config` file. In EF Core, you read this connection string using the `ConfigurationManager` API. You may need to add a reference to the `System.Configuration` framework assembly to be able to use this API. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {}, "names": []} --> ````c# public class BloggingContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["BloggingDatabase"].ConnectionString); } } ```` ## Update your code At this point, it's a matter of addressing compilation errors and reviewing code to see if the behavior changes will impact you. ## Existing migrations There isn't really a feasible way to port existing EF6.x migrations to EF Core. If possible, it is best to assume that all previous migrations from EF6.x have been applied to the database and then start migrating the schema from that point using EF Core. To do this, you would use the `Add-Migration` command to add a migration once the model is ported to EF Core. You would then remove all code from the `Up` and `Down` methods of the scaffolded migration. Subsequent migrations will compare to the model when that initial migration was scaffolded. ## Test the port Just because your application compiles, does not mean it is successfully ported to EF Core. You will need to test all areas of your application to ensure that none of the behavior changes have adversely impacted your application. <file_sep>/samples/Miscellaneous/Logging/Logging.ConsoleApp/Program.cs using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; namespace EFLogging.ConsoleApp { class Program { static void Main(string[] args) { using (var db = new BloggingContext()) { var serviceProvider = db.GetInfrastructure<IServiceProvider>(); var loggerFactory = serviceProvider.GetService<ILoggerFactory>(); loggerFactory.AddProvider(new MyLoggerProvider()); } using (var db = new BloggingContext()) { db.Database.EnsureCreated(); db.Blogs.Add(new Blog { Url = "http://sample.com" }); db.SaveChanges(); } using (var db = new BloggingContext()) { foreach (var blog in db.Blogs) { Console.WriteLine(blog.Url); } } } } } <file_sep>/samples/Saving/Saving/Concurrency/Sample.cs using Microsoft.EntityFrameworkCore; using System; using System.ComponentModel.DataAnnotations; using System.Linq; namespace EFSaving.Concurrency { public class Sample { public static void Run() { // Ensure database is created and has a person in it using (var context = new PersonContext()) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); context.People.Add(new Person { FirstName = "John", LastName = "Doe" }); context.SaveChanges(); } using (var context = new PersonContext()) { // Fetch a person from database and change phone number var person = context.People.Single(p => p.PersonId == 1); person.PhoneNumber = "555-555-5555"; // Change the persons name in the database (will cause a concurrency conflict) context.Database.ExecuteSqlCommand("UPDATE dbo.People SET FirstName = 'Jane' WHERE PersonId = 1"); try { // Attempt to save changes to the database context.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { foreach (var entry in ex.Entries) { if (entry.Entity is Person) { // Using a NoTracking query means we get the entity but it is not tracked by the context // and will not be merged with existing entities in the context. var databaseEntity = context.People.AsNoTracking().Single(p => p.PersonId == ((Person)entry.Entity).PersonId); var databaseEntry = context.Entry(databaseEntity); foreach (var property in entry.Metadata.GetProperties()) { var proposedValue = entry.Property(property.Name).CurrentValue; var originalValue = entry.Property(property.Name).OriginalValue; var databaseValue = databaseEntry.Property(property.Name).CurrentValue; // TODO: Logic to decide which value should be written to database // entry.Property(property.Name).CurrentValue = <value to be saved>; // Update original values to entry.Property(property.Name).OriginalValue = databaseEntry.Property(property.Name).CurrentValue; } } else { throw new NotSupportedException("Don't know how to handle concurrency conflicts for " + entry.Metadata.Name); } } // Retry the save operation context.SaveChanges(); } } } public class PersonContext : DbContext { public DbSet<Person> People { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFSaving.Concurrency;Trusted_Connection=True;"); } } public class Person { public int PersonId { get; set; } [ConcurrencyCheck] public string FirstName { get; set; } [ConcurrencyCheck] public string LastName { get; set; } public string PhoneNumber { get; set; } } } } <file_sep>/ef/querying/related-data.md --- uid: querying/related-data --- Caution: This documentation is for EF Core. For EF6.x and earlier release see [http://msdn.com/data/ef](http://msdn.com/data/ef). # Loading Related Data Entity Framework Core allows you to use the navigation properties in your model to load related entities. There are three common O/RM patterns used to load related data. * **Eager loading** means that the related data is loaded from the database as part of the initial query. * **Explicit loading** means that the related data is explicitly loaded from the database at a later time. * **Lazy loading** means that the related data is transparently loaded from the database when the navigation property is accessed. Lazy loading is not yet possible with EF Core. Tip: You can view this article's [sample](https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/Querying) on GitHub. ## Eager loading You can use the `Include` method to specify related data to be included in query results. In the following example, the blogs that are returned in the results will have their `Posts` property populated with the related posts. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/querying/Querying/Querying/RelatedData/Sample.cs"} --> ````c# var blogs = context.Blogs .Include(blog => blog.Posts) .ToList(); ```` Tip: Entity Framework Core will automatically fix-up navigation properties to any other entities that were previously loaded into the context instance. So even if you don't explicitly include the data for a navigation property, the property may still be populated if some or all of the related entities were previously loaded. You can include related data from multiple relationships in a single query. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/querying/Querying/Querying/RelatedData/Sample.cs"} --> ````c# var blogs = context.Blogs .Include(blog => blog.Posts) .Include(blog => blog.Owner) .ToList(); ```` ### Including multiple levels You can drill down thru relationships to include multiple levels of related data using the `ThenInclude` method. The following example loads all blogs, their related posts, and the author of each post. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/querying/Querying/Querying/RelatedData/Sample.cs"} --> ````c# var blogs = context.Blogs .Include(blog => blog.Posts) .ThenInclude(post => post.Author) .ToList(); ```` You can chain multiple calls to `ThenInclude` to continue including further levels of related data. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/querying/Querying/Querying/RelatedData/Sample.cs"} --> ````c# var blogs = context.Blogs .Include(blog => blog.Posts) .ThenInclude(post => post.Author) .ThenInclude(author => author.Photo) .ToList(); ```` You can combine all of this to include related data from multiple levels and multiple roots in the same query. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/querying/Querying/Querying/RelatedData/Sample.cs"} --> ````c# var blogs = context.Blogs .Include(blog => blog.Posts) .ThenInclude(post => post.Author) .ThenInclude(author => author.Photo) .Include(blog => blog.Owner) .ThenInclude(owner => owner.Photo) .ToList(); ```` ### Ignored includes If you change the query so that it no longer returns instances of the entity type that the query began with, then the include operators are ignored. In the following example, the include operators are based on the `Blog`, but then the `Select` operator is used to change the query to return an anonymous type. In this case, the include operators have no effect. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/querying/Querying/Querying/RelatedData/Sample.cs"} --> ````c# var blogs = context.Blogs .Include(blog => blog.Posts) .Select(blog => new { Id = blog.BlogId, Url = blog.Url }) .ToList(); ```` By default, EF Core will log a warning when include operators are ignored. See [Logging](../miscellaneous/logging.md) for more information on viewing logging output. You can change the behavior when an include operator is ignored to either throw or do nothing. This is done when setting up the options for your context - typically in `DbContext.OnConfiguring`, or in `Startup.cs` if you are using ASP.NET Core. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1, "hl_lines": [5]}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/querying/Querying/Querying/RelatedData/ThrowOnIgnoredInclude/BloggingContext.cs"} --> ````c# protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFQuerying;Trusted_Connection=True;") .ConfigureWarnings(warnings => warnings.Throw(CoreEventId.IncludeIgnoredWarning)); } ```` ## Explicit loading Explicit loading does not yet have a first class API in EF Core. You can view the [explicit loading item on our backlog](https://github.com/aspnet/EntityFramework/issues/625) to track this feature. However, you can use a LINQ query to load the data related to an existing entity instance, by filtering to entities related to the entity in question. Because EF Core will automatically fix-up navigation properties to any other entities that were previously loaded into the context instance, the loaded data will be populated into the desired navigation property. In the following example, a query is used to load a blog, and then a later query is used to load the posts related to the blog. The loaded posts will be present in the `Posts` property of the previously loaded blog. <!-- literal_block {"ids": [], "classes": [], "xml:space": "preserve", "backrefs": [], "linenos": true, "dupnames": [], "language": "c#", "highlight_args": {"linenostart": 1}, "names": [], "source": "/Users/shirhatti/src/EntityFramework.Docs/docs/querying/Querying/Querying/RelatedData/Sample.cs"} --> ````c# var blog = context.Blogs .Single(b => b.BlogId == 1); context.Posts .Where(p => p.BlogId == blog.BlogId) .Load(); ```` ## Lazy loading Lazy loading is not yet supported by EF Core. You can view the [lazy loading item on our backlog](https://github.com/aspnet/EntityFramework/issues/3797) to track this feature. <file_sep>/samples/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Storage/MyRelationalDatabaseProviderServices.cs using System; using EntityFrameworkCore.RelationalProviderStarter.Infrastructure; using EntityFrameworkCore.RelationalProviderStarter.Metadata; using EntityFrameworkCore.RelationalProviderStarter.Migrations; using EntityFrameworkCore.RelationalProviderStarter.Query.ExpressionTranslators.Internal; using EntityFrameworkCore.RelationalProviderStarter.Query.Sql; using EntityFrameworkCore.RelationalProviderStarter.Update; using EntityFrameworkCore.RelationalProviderStarter.ValueGeneration; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Query.ExpressionTranslators; using Microsoft.EntityFrameworkCore.Query.Sql; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Update; using Microsoft.EntityFrameworkCore.ValueGeneration; namespace EntityFrameworkCore.RelationalProviderStarter.Storage { public class MyRelationalDatabaseProviderServices : RelationalDatabaseProviderServices { public MyRelationalDatabaseProviderServices(IServiceProvider services) : base(services) { } public override string InvariantName => "MyRelationalProvider"; public override IRelationalAnnotationProvider AnnotationProvider => GetService<MyRelationalAnnotationProvider>(); public override IMemberTranslator CompositeMemberTranslator => GetService<MyRelationalCompositeMemberTranslator>(); public override IMethodCallTranslator CompositeMethodCallTranslator => GetService<MyRelationalCompositeMethodCallTranslator>(); public override IDatabaseCreator Creator => GetService<MyRelationalDatabaseCreator>(); public override IHistoryRepository HistoryRepository => GetService<MyHistoryRepository>(); public override IModelSource ModelSource => GetService<MyModelSource>(); public override IModificationCommandBatchFactory ModificationCommandBatchFactory => GetService<MyModificationCommandBatchFactory>(); public override IQuerySqlGeneratorFactory QuerySqlGeneratorFactory => GetService<MyQuerySqlGeneratorFactory>(); public override IRelationalConnection RelationalConnection => GetService<MyRelationalConnection>(); public override IRelationalDatabaseCreator RelationalDatabaseCreator => GetService<MyRelationalDatabaseCreator>(); public override ISqlGenerationHelper SqlGenerationHelper => GetService<MyRelationalSqlGenerationHelper>(); public override IUpdateSqlGenerator UpdateSqlGenerator => GetService<MyUpdateSqlGenerator>(); public override IValueGeneratorCache ValueGeneratorCache => GetService<MyValueGeneratorCache>(); } }<file_sep>/samples/Saving/Saving/Transactions/ControllingTransaction/Sample.cs using Microsoft.EntityFrameworkCore; using System; using System.Linq; namespace EFSaving.Transactions.ControllingTransaction { public class Sample { public static void Run() { using (var context = new BloggingContext()) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); } using (var context = new BloggingContext()) { using (var transaction = context.Database.BeginTransaction()) { try { context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); context.SaveChanges(); context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/visualstudio" }); context.SaveChanges(); var blogs = context.Blogs .OrderBy(b => b.Url) .ToList(); // Commit transaction if all commands succeed, transaction will auto-rollback // when disposed if either commands fails transaction.Commit(); } catch (Exception) { // TODO: Handle failure } } } } public class BloggingContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFSaving.Transactions;Trusted_Connection=True;"); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } } } }
1abd8b5489dba6f762127c8938446e5fd20aac29
[ "Markdown", "C#" ]
124
C#
shirhatti/EntityFramework.Docs
8ba0d19894dd1b27cde9f3b5ecb1c7fe2c51dfff
8a35d7de59cbf80ea2c85ae655114987025ad1f3
refs/heads/master
<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab10Alt { class Car { private String make; private String model; private int year = 0; private double price = 0.0; public Car(string make, string model, int year, double price) { Make = make; Model = model; Year = year; Price = price; } public string Make { get => make; set => make = value; } public string Model { get => model; set => model = value; } public int Year { get => year; set => year = value; } public double Price { get => price; set => price = value; } public override string ToString() { return $"New |{make} |{model} |{year} |{price, 8:C} |0 |"; } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Lab10Alt; namespace Lab10Alt { public class Validator { public static int InputValidator(int x) { int userInput = 0; string input = Console.ReadLine(); while (true) { try { userInput = int.Parse(input); if (userInput <= x - x || userInput > x) { Console.Write("\nThat entry is not valid! Please make another selection: "); input = Console.ReadLine(); continue; } } catch (IndexOutOfRangeException e) { } catch (Exception e) { Console.Write("\nThat entry is not valid! Please make another selection: "); input = Console.ReadLine(); continue; } return userInput; } } public static string Confirm() { while (true) { Console.Write("\n\tWould you like to by this vehicle? Y or N "); string test = Console.ReadLine().ToLower(); if (test == "y" || test == "yes") { return "ok"; } else if (test == "n" || test == "no") { Continue(); return "NotOk"; } } } public static string Continue() { while (true) { Console.Write("\n\tWould you like to purchase a vehicle? Y or N "); string test = Console.ReadLine().ToLower(); if (test == "y" || test == "yes") { return "\n\tExcellent! Let me show you what we have in stock."; } else if (test == "n" || test == "no") { Console.WriteLine($"Bye! "); Console.ReadLine(); Environment.Exit(1); } } } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab10Alt { class UsedCar : Car { double Miles = 0.0; public UsedCar(string make, string model, int year, double price, double miles) : base(make,model,year,price) { Miles = miles; } public override string ToString() { return $"Used |{Make} |{Model} |{Year} |{Price, 8:C} |{Miles} |"; } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab10Alt { class Program { static void Main(string[] args) { int userInput = 0; ArrayList Cars = new ArrayList(); ArrayList Receipt = new ArrayList(); Cars.Add(new Car("Pontiac ", "Aztec ", 1999, 21_000)); Cars.Add(new Car("Chevrolet", "Camaro ", 2012, 35_000)); Cars.Add(new Car("BMW ", "M3 ", 2015, 85_000)); Cars.Add(new UsedCar("VW ", "Bus ", 1965, 2_000, 189_000)); Cars.Add(new UsedCar("Pontiac ", "Vibe ", 2003, 1_500, 189_000)); Cars.Add(new UsedCar("Ford ", "Mustang", 1989, 3_500, 120_000)); Console.WriteLine(Validator.Continue()); while (true) { Header(); int c = 0; foreach (Car car in Cars) { c++; Console.WriteLine($"|>{c}. |" + car); Console.WriteLine("|==============================================================|"); } Console.Write("Enter the number for the vehicle that you would like to purchase: "); userInput = Validator.InputValidator(Cars.Count) - 1; Console.WriteLine("\n\t\t\tYou have selected"); Header(); Console.WriteLine($"<<|>>|{Cars[userInput]}\n"); string confirm = Validator.Confirm(); if (confirm == "NotOk") { continue; } Receipt.Insert(0, Cars[userInput]); Cars.RemoveAt(userInput); Console.WriteLine("\n\t\tYour current purchases are.\n"); Header(); int x = 0; foreach (Object buys in Receipt) { x++; Console.WriteLine($"|>{x}. |" + buys); } if (Cars.Count <= 0) { Console.WriteLine("\n\t There is no more vehicles in stock. "); Console.WriteLine("\n\t\tYour current purchases are.\n"); Header(); int d = 0; foreach (Object buys in Receipt) { d++; Console.WriteLine($"|>{d}. |" + buys); } Console.WriteLine($"\n\t\t\tBye! "); Console.ReadLine(); Environment.Exit(1); } Console.WriteLine(Validator.Continue()); } } private static void Header() { Console.WriteLine("________________________________________________________________"); Console.WriteLine("|Condition |Make |Model |Year |Price |Miles |"); Console.WriteLine("|==============================================================|"); } } }
9e5adb96e59865eccf30629ebdd021c9ebc52e14
[ "C#" ]
4
C#
JacobSnover/LabAlt10
dfd76091614d12104fb2e824cf100802d1c7bbb1
4711319676f898b353263f0539fd478559f15d97
refs/heads/master
<repo_name>Etison/github_plugin<file_sep>/README.md # Github Plugin This plugin moves data from the Github API to Google Cloud Storage based on the specified object. ## Hooks ### GithubHook This hook handles the authentication and request to Github. This extends the HttpHook. ### S3Hook Core Airflow S3Hook with the standard boto dependency. ## Operators ### GithubtoCloudStorageOperator This operator composes the logic for this plugin. It fetches the Github specified object and saves the result in GCS. The parameters it can accept include the following: ```:param src: Path to the local file. (templated) :type src: str :param dst: Destination path within the specified bucket. (templated) :type dst: str :param bucket: The bucket to upload to. (templated) :type bucket: str :param google_cloud_storage_conn_id: The Airflow connection ID to upload with :type google_cloud_storage_conn_id: str :param mime_type: The mime-type string :type mime_type: str :param delegate_to: The account to impersonate, if any :type delegate_to: str :param gzip: Allows for file to be compressed and uploaded as gzip ``` <file_sep>/operators/github_to_cloud_storage_operator.py from tempfile import NamedTemporaryFile from flatten_json import flatten import logging import json from airflow.utils.decorators import apply_defaults from airflow.models import BaseOperator from airflow.hooks import S3Hook from github_plugin.hooks.github_hook import GithubHook class GithubToCloudStorageOperator(BaseOperator): """ Github To Cloud Storage Operator :param github_conn_id: The Github connection id. :type github_conn_id: string :param github_org: The Github organization. :type github_org: string :param github_repo: The Github repository. Required for commits, commit_comments, issue_comments, and issues objects. :type github_repo: string :param github_object: The desired Github object. The currently supported values are: - commits - commit_comments - issue_comments - issues - members - organizations - pull_requests - repositories :type github_object: string :param payload: The associated github parameters to pass into the object request as keyword arguments. :type payload: dict :param destination: The final destination where the data should be stored. Possible values include: - GCS - S3 :type destination: string :param dest_conn_id: The destination connection id. :type dest_conn_id: string :param bucket: The bucket to be used to store the data. :type bucket: string :param key: The filename to be used to store the data. :type key: string """ template_field = ('key',) @apply_defaults def __init__(self, github_conn_id, github_org, github_object, dest_conn_id, bucket, key, destination='s3', github_repo=None, payload={}, **kwargs): super().__init__(**kwargs) self.github_conn_id = github_conn_id self.github_org = github_org self.github_repo = github_repo self.github_object = github_object self.payload = payload self.destination = destination self.dest_conn_id = dest_conn_id self.bucket = bucket self.key = key if self.github_object.lower() not in ('commits', 'commit_comments', 'issue_comments', 'issues', 'members', 'organizations', 'pull_requests', 'repositories'): raise Exception('Specified Github object not currently supported.') def execute(self, context): g = GithubHook(self.github_conn_id) output = [] if self.github_object not in ('members', 'organizations', 'repositories'): if self.github_repo == 'all': repos = [repo['name'] for repo in self.paginate_data(g, self.methodMapper('repositories'))] for repo in repos: output.extend(self.retrieve_data(g, repo=repo)) elif isinstance(self.github_repo, list): repos = self.github_repo for repo in repos: output.extend(self.retrieve_data(g, repo=repo)) else: output = self.retrieve_data(g, repo=self.github_repo) else: output = self.retrieve_data(g, repo=self.github_repo) self.output_manager(output) def output_manager(self, output): output = '\n'.join([json.dumps(flatten(record)) for record in output]) if self.destination.lower() == 's3': s3 = S3Hook(self.dest_conn_id) s3.load_string( string_data=output, key=self.key, bucket_name=self.bucket, replace=True ) elif self.destination.lower() == 'gcs': with NamedTemporaryFile('w') as tmp: tmp.write(output) gcs = GoogleCloudStorageHook(self.dest_conn_id) gcs.upload( bucket=self.bucket, object=self.key, filename=tmp.name, ) def retrieve_data(self, g, repo=None): """ This method builds the endpoint and passes it into the "paginate_data" method. It is wrapped in a "try/except" in the event that an HTTP Error is thrown. This can happen when making a request to a page that does not yet exist (e.g. requesting commits from a repo that has no commits.) """ try: endpoint = self.methodMapper(self.github_object, self.github_org, repo) return self.paginate_data(g, endpoint) except: logging.info('Resource is unavailable.') return '' def paginate_data(self, g, endpoint): """ This method takes care of request building and pagination. It retrieves 100 at a time and continues to make subsequent requests until it retrieves less than 100 records. """ output = [] final_payload = {'per_page': 100, 'page': 1} for param in self.payload: final_payload[param] = self.payload[param] response = g.run(endpoint, final_payload).json() output.extend(response) logging.info('Retrieved: ' + str(final_payload['per_page'] * final_payload['page'])) while len(response) == 100: final_payload['page'] += 1 response = g.run(endpoint, final_payload).json() logging.info('Retrieved: ' + str(final_payload['per_page'] * final_payload['page'])) output.extend(response) output = [self.filterMapper(record) for record in output] return output def methodMapper(self, github_object, org=None, repo=None): """ This method maps the desired object to the relevant endpoint according to v3 of the Github API. """ mapping = {"commits": "repos/{0}/{1}/commits".format(org, repo), "commit_comments": "repos/{0}/{1}/comments".format(org, repo), "issue_comments": "repos/{0}/{1}/issues/comments".format(org, repo), "issues": "repos/{0}/{1}/issues".format(org, repo), "members": "orgs/{0}/members".format(org), "organizations": "user/organizations", "pull_requests": "repos/{0}/{1}/pulls".format(org, repo), "repositories": "orgs/{0}/repos".format(self.github_org) } return mapping[github_object] def filterMapper(self, record): """ This process strips out unnecessary objects (i.e. ones that are duplicated in other core objects). Example: a commit returns all the same user information for each commit as already returned the members endpoint). In most cases, id for these striped objects are kept for reference although multiple values can be added to the array. Labels is currently returned as an array of dicts. When flattened, this can cause an undo amount of columns with the naming convention labels_0_name, labels_1_name, etc. Until a better data model can be determined (possibly putting labels in their own table) these fields are striped out entirely. In situations where there are no desired retention fields, "retained" should be set to "None". """ mapping = [{'name': 'commits', 'filtered': 'author', 'retained': ['id'] }, {'name': 'commits', 'filtered': 'committer', 'retained': ['id'] }, {'name': 'issues', 'filtered': 'labels', 'retained': None }, {'name': 'issue_comments', 'filtered': 'user', 'retained': ['id'] }, {'name': 'commit_comments', 'filtered': 'user', 'retained': ['id'] }, {'name': 'repositories', 'filtered': 'owner', 'retained': ['id'] }, {'name': 'pull_requests', 'filtered': 'assignee', 'retained': ['id'] }, {'name': 'pull_requests', 'filtered': 'milestone', 'retained': ['id'] }, {'name': 'pull_requests', 'filtered': 'head', 'retained': ['label'] }, {'name': 'pull_requests', 'filtered': 'base', 'retained': ['label'] }, {'name': 'pull_requests', 'filtered': 'user', 'retained': ['id'] } ] def process(record, mapping): """ This method processes the data according to the above mapping. There are a number of checks throughout as the specified filtered object and desired retained fields will not always exist in each record. """ for entry in mapping: # Check to see if the filtered value exists in the record if (entry['name'] == self.github_object) and (entry['filtered'] in list(record.keys())): # Check to see if any retained fields are desired. # If not, delete the object. if entry['retained']: for retained_item in entry['retained']: # Check to see the filterable object exists in the # specific record. This is not always the case. # Check to see the retained field exists in the # filterable object. if record[entry['filtered']] is not None and\ retained_item in list(record[entry['filtered']].keys()): # Bring retained field to top level of # object with snakecasing. record["{0}_{1}".format(entry['filtered'], retained_item)] = \ record[entry['filtered']][retained_item] if record[entry['filtered']] is not None: del record[entry['filtered']] return record return process(record, mapping)
e090ec7396217a6550409b8fa175e2774754a132
[ "Markdown", "Python" ]
2
Markdown
Etison/github_plugin
6741c30fdb44cfe919a65ee7879b2632edc1f3a4
71ce9bdc852eb0d05ba20db52300ff06055a0de7
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 Frontera; import Entidad.Sistema; import Entidad.Usuario; import java.util.ArrayList; /** * * @author Hp */ public class FramePrincipal extends javax.swing.JFrame { private Registro registro = new Registro(); private Ingreso ingreso = new Ingreso(); //Instancia de Sistema public static Sistema sistema = new Sistema(); public FramePrincipal() { initComponents(); inicializacion(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jToolBar2 = new javax.swing.JToolBar(); registroB = new javax.swing.JButton(); ingresoB = new javax.swing.JButton(); panelPrincipal = new javax.swing.JPanel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Login de Usuario"); jToolBar2.setRollover(true); registroB.setText("Registro"); registroB.setFocusable(false); registroB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); registroB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); registroB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { registroBActionPerformed(evt); } }); jToolBar2.add(registroB); ingresoB.setText("Ingreso"); ingresoB.setFocusable(false); ingresoB.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); ingresoB.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); ingresoB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ingresoBActionPerformed(evt); } }); jToolBar2.add(ingresoB); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jToolBar2, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 11, Short.MAX_VALUE)) ); panelPrincipal.setName("Login de Usuario"); // NOI18N panelPrincipal.setLayout(new java.awt.BorderLayout()); 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.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(panelPrincipal, 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(panelPrincipal, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE) .addGap(12, 12, 12)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void registroBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_registroBActionPerformed panelPrincipal.setVisible(false); panelPrincipal.removeAll(); panelPrincipal.add(registro); panelPrincipal.setVisible(true); }//GEN-LAST:event_registroBActionPerformed private void ingresoBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ingresoBActionPerformed panelPrincipal.setVisible(false); panelPrincipal.removeAll(); panelPrincipal.add(ingreso); panelPrincipal.setVisible(true); }//GEN-LAST:event_ingresoBActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FramePrincipal().setVisible(true); } }); } public void inicializacion(){ } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton ingresoB; private javax.swing.JPanel jPanel1; private javax.swing.JToolBar jToolBar2; private javax.swing.JPanel panelPrincipal; private javax.swing.JButton registroB; // End of variables declaration//GEN-END:variables }
f60c2d4f02bc27f40a22888cea9810ec26b86211
[ "Java" ]
1
Java
dlopezav/LoginApplication
052aed4521f23b9f820e3248aee3be9c10dc266e
10dd600aa6eef80bd650fc947d9622b61bc1b595
refs/heads/master
<repo_name>Chant-Lee/learn<file_sep>/vue-webpack/docs/static.md # 处理静态文件 您将注意到在项目结构中,我们有两个静态资源目录:src/assets和static/。它们之间有什么区别? ### Webpacked To answer this question, we first need to understand how Webpack deals with static assets. In `*.vue` components, all your templates and CSS are parsed by `vue-html-loader` and `css-loader` to look for asset URLs. For example, in `<img src="./logo.png">` and `background: url(./logo.png)`, `"./logo.png"` is a relative asset path and will be **resolved by Webpack as a module dependency**. 为了回答这个问题,我们首先需要了解Webpack如何处理静态资产。在*.vue组件中,您的所有模板和CSS都由解析vue-html-loader和css-loader查找资源网址。例如,在<img src="./logo.png">和中background: url(./logo.png),"./logo.png"是相对资产路径,将由Webpack解析为模块依赖项。 因为logo.png不是JavaScript,当被当作模块依赖,我们需要使用url-loader和file-loader处理它。这个样板文件已经为你配置了这些加载器,所以你基本上可以免费获得文件名指纹和条件base64内联等功能,同时能够使用相对/模块路径,而不必担心部署。 由于这些资源可能在构建期间内联/复制/重命名,因此它们基本上是源代码的一部分。这就是为什么建议将Webpack处理的静态资源放在里面/src,沿着其他源文件。事实上,你甚至不必把它们全部/src/assets:你可以根据模块/组件使用它们来组织它们。例如,您可以将每个组件放在其自己的目录中,其静态资产位于其旁边。 ### 文件解析规则 - 相对URL,例如./assets/logo.png将被解释为模块依赖。它们将替换为基于您的Webpack输出配置的自动生成的URL。 - 非前缀URL,例如assets/logo.png将被视为与相对URL相同并被翻译成./assets/logo.png。 - 以前缀的网址~被视为模块请求,类似于require('some-module/image.png')。如果要利用Webpack的模块解析配置,则需要使用此前缀。例如,如果您有一个解决别名assets,您需要使用<img src="~assets/logo.png">以确保别名受到尊重。 - 根相对URL,例如/assets/logo.png根本不处理。 ### 在JavaScript中获取文件路径 为了使Webpack返回正确的文件路径,您需要使用require('./relative/path/to/file.jpg'),它将由处理file-loader并返回解析的URL。例如: ``` js computed: { background () { return require('./bgs/' + this.id + '.jpg') } } ``` 注意上面的例子将包括./bgs/最终构建中的每个图像。这是因为Webpack无法猜测其中的哪些将在运行时使用,因此它包括所有。 ### “真正的”静态文件 相比之下,Webpack static/根本不处理文件:它们直接复制到其最终目的地,具有相同的文件名。您必须使用绝对路径引用这些文件,这是由join build.assetsPublicPath和build.assetsSubDirectoryin决定的config.js。 ``` js // config.js module.exports = { // ... build: { assetsPublicPath: '/', assetsSubDirectory: 'static' } } ``` static/应使用绝对URL引用放置的任何文件/static/[filename]。如果您更改assetSubDirectory为assets,则这些网址需要更改为/assets/[filename]。 我们将在有关后端集成的部分中了解有关配置文件的更多信息。<file_sep>/vue-webpack/docs/end.md # 端到端测试 这个样板文件使用Nightwatch.js进行e2e测试。Nightwatch.js是在Selenium之上构建的高度集成的e2e测试运行器。这个样板自带的Selenium服务器和chromedriver二进制文件为您预先配置,所以你不必自己麻烦这些。 让我们来看看目录中的文件test/e2e: - `runner.js` 一个Node.js脚本,它启动dev服务器,然后启动Nightwatch对其运行测试。这是运行时将运行的脚本npm run e2e - `nightwatch.conf.js` Nightwatch配置文件。有关详细信息,请参阅配置上的[Nightwatch文档](http://nightwatchjs.org/guide#settings-file) - `custom-assertions/` 可以在Nightwatch测试中使用的自定义断言。有关详细信息,请参阅Nightwatch的文档以编写自定义断言。 - `specs/` - 你实际测试!有关详细信息,请参阅Nightwatch的文档,了解如何编写测试和API参考。 You actual tests! See [Nightwatch's docs on writing tests](http://nightwatchjs.org/guide#writing-tests) and [API reference](http://nightwatchjs.org/api) for more details. ### 在更多浏览器中运行测试 要配置哪些浏览器运行测试,请在“test_settings”中添加一个条目test/e2e/nightwatch.conf.js,以及中的--env标志test/e2e/runner.js。如果你想在像SauceLabs这样的服务上配置远程测试,你可以根据环境变量设置Nightwatch配置,或者使用单独的配置文件。有关详细信息,请咨询Selenium的夜视文档。 To configure which browsers to run the tests in, add an entry under "test_settings" in [`test/e2e/nightwatch.conf.js`](https://github.com/vuejs-templates/webpack/blob/master/template/test/e2e/nightwatch.conf.js#L17-L39) , and also the `--env` flag in [`test/e2e/runner.js`](https://github.com/vuejs-templates/webpack/blob/master/template/test/e2e/runner.js#L15). If you wish to configure remote testing on services like SauceLabs, you can either make the Nightwatch config conditional based on environment variables, or use a separate config file altogether. Consult [Nightwatch's docs on Selenium](http://nightwatchjs.org/guide#selenium-settings) for more details. <file_sep>/javascript/9.md #《编写可维护的javascript》读书笔记 >每个人都有一套编码习惯,在团队协作过程中,需要每个人都遵守统一的编码约定和编程方法,以便团队任何人都可以轻松的理解,修改和扩展你的代码。 ####第一部分:编程风格 ###一、基本的格式化 #####1、缩进层级 第一种缩进:使用制表符进行缩进。 第二种缩进:使用空格符进行缩进。 推荐:4个空格字符为一个缩进层级,可以在编辑器中配置Tab键插入4个空格。 #####2、语句结局 有时候加没加分号代码可能都会正常运行,没看到这里之前,你可能不知道这是分析器的自动分号插入机制(ASI)在偷偷的帮你干活。 <pre> function getData() { return { text: '看看不加分号的后果!' } } ASI会解析成下面的样子: function getData() { return ; { text: '看看不加分号的后果!' }; } </pre> 所以如果调用上面的getData的方法,返回的就是undefined。尽管没有分号,这段代码工作正常。 <pre> function getData() { return { text: '看看不加分号的后果!' } } </pre> #####3、行的长度: 倾向于80个字符。 如果一行多于80个字符,应当在一个运算符(逗号,加号等)后换行。下一行应当增加两级缩进。 <pre> if (category_id==111111 && task_status.tender_condition.isNewSecurity && $task_os_type == 1) { func(); } </pre> #####4、命名 JavaScript一般使用驼峰命名法来给变量和函数命名。变量命名前缀一般是名词,函数名前缀一般是动词。(以大写字母开始叫大驼峰,以小写字母开始,之后的单词首字母大写叫小驼峰,构造函数命名遵照大驼峰命名法) <pre> var MAX_PRICE = 18, //常量值初始化后就不变了 myName = "wahaha", myAge = 20;//变量的值是可变的 function getName(){ myAge==MAX_PRICE?console.log(myName):console.log("sorry"); } </pre> ###二、注释 #####1、单行注释 单行注释有三种使用方法: 独占一行的注释,用来解释下一行代码。这行注释之前总要有一个空行,且缩进层级和下一行码保持一致。 <pre> // 好的写法 function print(){ // 控制台输出数字1 console.log(1); } </pre> #####2、多行注释 多行注释之前也应该有一个空行,且缩进层级和其描述的代码保持一致。 #####3、文档注释 多行注释以单斜线加双星号(/**)开始,接下来是描述信息,其中使用@符号来表示一个或多个属性。 ###三、避免“空比较” #####1、检测原始值 JavaScript有5中简单的原始类型:字符串、数字、布尔值、null和undefined。最佳的选择是用typeof运算符,返回一个值的类型的字符串。 用typeof检测一下4种原始值类型是非常安全的。 <pre> //检测字符串 if (typeof name === "string") { anotherName = name.substring(3); } //检测数字 if (typeof count === "number") { updateCount(count); } //检测布尔值 if (typeof found === "boolean" && found){ message("Found!"); } //检测underfined if (typeof MyApp=== "undefined") { MyApp = {}; } </pre> #####2、检测引用值 引用值也称为对象,检测某个引用值的类型的官方最好的方法是使用instanceof运算符。但是它不仅检测构造这个对象的构造器,还检测原型链。因为每个对象都继承自Object,因此每个对象的 value instanceof Object都会返回true。 <pre> var now = new Date(); console.log(now instanceof object); // true console.log(now instanceof Date) // true </pre> #####3、检测数组 <pre> function isArray(value) { return Object.prototype.toString.call(value) === "[object Array]"; } // ECMAScript6:Array.isArray() </pre> ###四、函数 + 推荐总是先声明后使用,和变量声明一样 + 匿名函数可以在最后加一对小括号来立即执行并返回一个值,然后将这个值赋值给变量 <pre> var val = (function() { return "abc"; }()); </pre> + 避免意外的全局变量 ###五、事件处理 + 隔离应用逻辑 <pre> var aa = { aa1: function(){ return 123; }, aa2: function(){ console.log(this.aa1()); } }; </pre> ###六、抽离配置数据 配置数据是应用中写死的值。 <pre> var config={ U_ID:"123", U_URL:"http://www.baidu.com" }; function validate(val){ if(config.U_ID==val){ console.log(config.U_URL); } } </pre> **问题讨论:**html标签里的ID在javascript中都是全局变量 <div id="abc"></div> <div id="abc-d"></div> ![](9.jpg) 所以建议用类名.J-send-sj这种 <div class="abc-d J-abc-d"></div><file_sep>/vue-webpack/docs/pre-process.md # **预处理器** 此样板为大多数常用的CSS预处理器(包括LESS,SASS,Stylus和PostCSS)预配置了CSS提取。要使用预处理器,您所需要做的就是为其安装适当的webpack加载器。例如,要使用SASS: ``` bash npm install sass-loader node-sass --save-dev ``` 注意,你还需要安装node-sass,因为sass-loader它依赖于它作为对等体的依赖。 ### 在组件中使用预处理器 在组件中使用预处理器 ``` html <style lang="scss"> /* write SASS! */ </style> ``` ### 关于SASS语法的注释 - lang="scss" 对应于CSS超集语法(带大括号和分号)。 - lang="sass" 对应于基于缩进的语法。 ### PostCSS *.vue默认情况下,文件中的样式通过PostCSS进行管道传输,因此您不需要为其使用特定的加载器。您可以简单地添加要build/webpack.base.conf.js在vue块中使用的PostCSS插件: ``` js // build/webpack.base.conf.js module.exports = { // ... vue: { postcss: [/* your plugins */] } } ``` 有关更多详细信息,vue-loader的相关文档。[vue-loader的相关文档](http://vuejs.github.io/vue-loader/en/features/postcss.html) ### 独立CSS文件 为了确保一致的提取和处理,建议从根App.vue组件导入全局,独立的样式文件,例如: ``` html <!-- App.vue --> <style src="./styles/global.less" lang="less"></style> ``` 请注意,您应该只为自己为应用程序编写的样式执行此操作。对于现有的库,例如Bootstrap或Semantic UI,您可以将它们放在里面/static并直接引用它们index.html。这避免了额外的构建时间,并且更好地用于浏览器缓存。<file_sep>/mongodb-koa/router/index.js const Router = require('koa-router') const { signup, updateUser, getAllUsers, addUserInfo, deleteUserInfo } = require('../app/controllers/user') const { hasBodyInfo, hasToken } = require('../app/filter') module.exports = function () { let router = new Router({ prefix: '/api' }) router.post('/prune/signup', hasBodyInfo, signup) router.post('/prune/update', hasBodyInfo, hasToken, updateUser) router.get('/prune/getUsers', getAllUsers) router.post('/prune/addUser', addUserInfo) router.post('/prune/deleteUser', deleteUserInfo) return router }<file_sep>/javascript/7.2.md ####利用arguments切片 - arguments 并非数组,只是访问单个参数的方式与访问数组元素的方式相同。因此在使用slice方法的时候,需要用类似[].slice.call(arguments, 1) 的这种方式去调用 ``` function helloLog(){ var arr=Array.prototype.slice.call(arguments,0); arr.unshift("(hello) "); console.log.apply(console,arr) } helloLog(1,2,3) ```<file_sep>/javascript/12.1.md ## 神奇的Object.defineProperty ### 1、语法 * Object.defineProperty(obj, prop,descriptor) ### 2、参数 * Object obj 目标对象 * String prop 需要定义的属性 * Object descriptor 该属性拥有的特性,可设置的值有: * value 属性的值,默认为 undefined。 * writable 该属性是否可写,如果设置成 false,则任何对该属性改写的操作都无效(但不会报错),默认为 false。 * get 一旦目标对象访问该属性,就会调用这个方法,并返回结果。默认为 undefined。 * set 一旦目标对象设置该属性,就会调用这个方法。默认为 undeinfed。 * configurable 如果为false,则任何尝试删除目标属性或修改属性以下特性(writable, configurable, enumerable)的行为将被无效化,默认为 false。 * enumerable 是否能在for...in循环中遍历出来或在Object.keys中列举出来。默认为 false。 ``` 例如: //改变writable使它变为不可写(数组可以绕过这个规则,无效) var obj = {}; Object.defineProperty(obj, 'key', { value: 'static', writable:false , enumerable:false, configurable:false }); obj.key=123;//obj.key='static' //改变configurable的值 var a= {} Object.defineProperty(a,"b",{ configurable:false }) Object.defineProperty(a,"b",{ configurable:true }) //error: Uncaught TypeError: Cannot redefine property: b //改变enumerable var obj= {} Object.defineProperty(obj,"b",{ value:3445, enumerable:true }) console.log(Object.keys(a));// 打印["b"]*/ ``` ### 3、Object.getOwnPropertyDescriptor(obj,prop) * 打印属性拥有的特性 ``` var obj = {}; Object.defineProperty(obj, 'key', {}); Object.getOwnPropertyDescriptor(obj,'key') //会打印出obj.key的所有特性 ``` ### 4、set和get * 在descriptor 中不能同时设置访问器(get 和 set)和 writable 或 value,否则会错,就是说想用 get 和 set,就不能用 writable 或 value 中的任何一个。 ``` <p>你好,<span id='nickName'></span></p> <div id="introduce"></div> <script> var userInfo = {}; Object.defineProperty(userInfo, "nickName", { get: function(){ return document.getElementById('nickName').innerHTML; }, set: function(nick){ document.getElementById('nickName').innerHTML = nick; } }); Object.defineProperty(userInfo, "introduce", { get: function(){ return document.getElementById('introduce').innerHTML; }, set: function(introduce){ document.getElementById('introduce').innerHTML = introduce; } }) userInfo.nickName = "张三"; userInfo.introduce = "我是张三,我来自重庆,..." </script> ``` ``` //双向绑定input文本框 <input type="text" id="demo"> <p id="display"></p> <script> var obj = {}; var bind = []; //触发obj对象set和get方法的时候,趁机来输出或修改bind数组的内容 Object.defineProperty(obj, 's', { set: function (val) { bind['s'] = val; }, get: function () { return bind['s']; } }) var demo = document.querySelector('#demo'); var display = document.querySelector('#display'); //#demo的value值与bind['s']绑定,#display的innerHTML也与bind['s']绑定。 demo.onkeyup = function () { obj['s'] = demo.value;//触发了obj的set方法,等于#demo的value值赋值给bind['s']。 display.innerHTML = bind['s']; console.log(bind) } </script> ```<file_sep>/mongodb-koa/app/service/user_service.js const mongoose = require('mongoose') const User = mongoose.model('User') /** * 通过电话号码查询 * @param {[type]} options.phoneNumber [description] * @return {[type]} [description] */ const selectUserByPhone = async ({ phoneNumber }) => { let query = User.find({ phoneNumber }) let res = {} await query.exec(function (err, user) { res = user || {} }) return res } /** * 查找所用用户 * @return {[type]} [description] */ const selectAllUsers = async () => { let query = User.find({}) let res = [] await query.exec(function (err, users) { res = err ? [] : users }) return res } /** * 增加用户 * @param {[User]} user [mongoose.model('User')] * @return {[type]} [description] */ const addUser = async (user) => { user = await user.save() return user } /** * 删除用户 * @param {[type]} options.phoneNumber [description] * @return {[type]} [description] */ const deleteUser = async ({ phoneNumber }) => { let flag = false await User.remove({ phoneNumber }, function (err) { flag = err ? false : true }) return flag } module.exports = { selectUserByPhone, selectAllUsers, addUser, deleteUser }<file_sep>/vue-webpack/docs/api-proxy.md # 开发过程中的API代理 当将此样板与现有后端集成时,常见的需求是在使用开发服务器时访问后端API。为了实现这一点,我们可以并行(或远程)运行dev服务器和API后端,并让dev服务器代理所有API请求到实际的后端。 要配置代理规则,请dev.proxyTable在中编辑选项config/index.js。dev服务器使用[http-proxy-middleware](https://github.com/chimurai/http-proxy-middleware) 代理,所以你应该参考它的文档的详细用法。但这里有一个简单的例子 ``` js // config/index.js module.exports = { // ... dev: { proxyTable: { // proxy all requests starting with /api to jsonplaceholder '/api': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, pathRewrite: { '^/api': '' } } } } } ``` 上述例子将请求代理/api/posts/1到http://jsonplaceholder.typicode.com/posts/1。 ## 网址匹配 除了静态网址,您还可以使用glob模式来匹配网址,例如/api/**。有关详细信息,请参阅上下文匹配。此外,您可以提供一个filter选项,可以是一个自定义函数来确定请求是否应该被代理: ``` js proxyTable: { '*': { target: 'http://jsonplaceholder.typicode.com', filter: function (pathname, req) { return pathname.match('^/api') && req.method === 'GET' } } } ``` <file_sep>/javascript/13json/13.3.md ### 3.JSON的解析 ##### 3.1JSON.parse() 把JSON字符串解析为原生JavaScript值(传的字符串如果不是一个有效的JSON,该方法会抛出错误),可以接受两个参数 ``` JSON.parse(text [, reviver]) ``` - text:必须,一个有效的 JSON 字符串。  - reviver:可选。 一个转换结果的函数。 将为对象的每个成员调用此函数。 如果成员包含嵌套对象,则先于父对象转换嵌套对象。 对于每个成员,会发生以下情况: - 如果 reviver 返回一个有效值,则成员值将替换为转换后的值。 - 如果 reviver 返回它接收的相同值,则不修改成员值。 - 如果 reviver 返回 undefined,则删除成员。 ```javascript var objStr = '{"name":"lizongji","year":2017,"nation":"China","age":null}' var obj = JSON.parse(objStr,function test(key,value){   switch(key){     case "name":       return "xiaoming";     case "year":       return undefined;     default:     return value;     }   } ) obj //Object {name: "xiaoming", nation: "China", age: null} ``` - 一般来说在JSON.parse的参数包含转移字符的时候会遇到两次转义的问题,其实第一次是字符串本身的转义,第二次是将真正转为js对象的转义。 (也可以直接先转换为字符串JSON.stringify,再进行JSON.parse) ```javascript var obj=JSON.parse('{"a":"b","b":"\\\\","c":{"b":"\\\\","a":{"b":"\\\\"}}}') obj //Object {a: "b", b: "\", c: Object} /**** 对于其他的其他的特殊字符 1.双引号("),如果正确出现双引号应为\\\" 2.\n,如想想出现正确的换行需要json字符串中是\\n,其实是先对\n中的\转义,n变成了普通字符,在解析为js对象的时候n与之前的\(只有一个\了)被解释为换行。如下的两个与此类似。 3.\r,\\r (回车(CR) ,将当前位置移到本行开头) ****/ var obj={"a":"b","b":"\\","c":{"b":"\\","a":{"b":"\\"}}} var objstr = JSON.stringify(obj) objstr //"{"a":"b","b":"\\","c":{"b":"\\","a":{"b":"\\"}}}" ``` ##### 3.2eval也可以把JSON字符串解析为原生JavaScript值,并且eval不会抛出错误,不过不建议使用eval。 ```javascript eval()可以执行不符合JSON格式的代码,有可能会包含恶意代码 eval('(' + '{"a":alert(1)}'+')').a;//弹出1 JSON.parse('{"a":alert(1)}').a;//报错 ``` ```javascript eval("("+"{'success':true}"+")")   JSON.parse("{'success':true}")   //报错 ``` ##### 3.3使用第三方库,例如 JQuery 等jQuery.parseJSON(str) ```javascript jQuery.parseJSON('{ "name": "John" }') //Object {name: "John"} ``` <file_sep>/vue-webpack/docs/backend.md # 与后端框架集成 如果您正在构建一个纯静态应用程序(与后端API分开部署的应用程序),那么您可能甚至不需要编辑config/index.js。但是,如果要将此模板与现有的后端框架(例如Rails / Django / Laravel)(它们自带的项目结构)进行集成,则可以编辑config/index.js以直接在后端项目中生成前端资源。 让我们来看看默认config/index.js: ``` js var path = require('path') module.exports = { build: { index: path.resolve(__dirname, 'dist/index.html'), assetsRoot: path.resolve(__dirname, 'dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', productionSourceMap: true }, dev: { port: 8080, proxyTable: {} } } ``` 在该build部分中,我们有以下选项: ### `build.index` > 必须是本地文件系统上的绝对路径。 这是生成index.html(带有注入的资产网址)的地方。 如果您使用此模板与后端框架,您可以相应地编辑index.html,并将此路径指向由后端应用程序呈现的视图文件,例如app/views/layouts/application.html.erbRails应用程序或resources/views/index.blade.phpLaravel应用程序。 ### `build.assetsRoot` > 必须是本地文件系统上的绝对路径。 这应该指向包含应用程序的所有静态资产的根目录。例如,public/对于Rails / Laravel。 ### `build.assetsSubDirectory` 在此目录下嵌入webpack生成的资产build.assetsRoot,以便它们不会与您可能存在的其他文件混合build.assetsRoot。例如,如果build.assetsRoot是/path/to/dist,和build.assetsSubDirectory是static,则将生成所有Webpack资产path/to/dist/static。 此目录将在每次构建之前清除,因此它只应包含构建生成的资产。 内部的文件static/将在构建期间被复制到此目录中。这意味着,如果您更改此前缀,您的所有绝对URL引用的文件static/也需要更改。有关详细信息,请参阅处理静态资产。 ### `build.assetsPublicPath` 这应该是您build.assetsRoot通过HTTP提供服务的网址路径。在大多数情况下,这将是root(/)。仅当您的后端框架提供带有路径前缀的静态资产时,才需要更改此设置。在内部,这被传递给Webpack output.publicPath。 ### `build.productionSourceMap` 是否为生成源映射。 ### `dev.port` 指定开发服务器侦听的端口。 ### `dev.proxyTable` 定义dev服务器的代理规则。有关更多详细信息,请参阅开发过程中的API代理。 <file_sep>/vue-webpack/docs/create.md # 构建命令 所有构建命令都通过NPM脚本执行。[NPM](https://docs.npmjs.com/misc/scripts). ### `npm run dev` >启动Node.js本地开发服务器。有关更多详细信息,请参阅开发过程中的API代理。 * Webpack + vue-loader用于单文件Vue组件。 * 状态保持热重载 * 状态保留编译错误叠加 * 使用ESLint保存Lint * 源地图 ### `npm run build` > 构建生产资产。有关更多详细信息,请参阅与[后端框架集成](backend.md) * 使用UglifyJS缩小JavaScript 。 * HTML使用html-minifier缩小。 * 所有组件的CSS提取到一个单一的文件,并与cssnano缩小。 * 所有使用版本哈希编译的静态资产,以便进行有效的长期缓存,并且index.html自动生成带有这些生成资产的正确网址的生产。 * 另请参阅部署说明。 ### `npm run unit` > 在PhantomJS中使用Karma运行单元测试。有关详细信息,请参阅[单元测试](unit-test.md)。 - 在测试文件中支持ES2015 +。 - 支持所有webpack加载器。 - 容易模拟注入。 ### `npm run e2e` > 使用Nightwatch运行端到端测试。有关详细信息,请参阅[端到端测试](end.md)。 [Nightwatch](http://nightwatchjs.org/) * 在多个浏览器中并行运行测试。 * 使用一个命令开箱即用: - 硒和chromedriver依赖自动处理。 - 自动生成Selenium服务器。 <file_sep>/javascript/13json/13.4.md ### 4.JSON的序列化 ##### 4.1JSON.stringify() 把JavaScript值序列化为JSON字符串(可以接受三个参数 ) ``` JSON.stringify(value [, replacer] [, space]) ``` - value:要序列化的JavaScript值(一般是对象或数组) - 键名不是双引号的(包括没有引号或者是单引号),会自动变成双引号;字符串是单引号的,会自动变成双引号 - 最后一个属性后面有逗号的,会被自动去掉 - 布尔值、数字、字符串的包装对象在序列化过程中会自动转换成对应的原始值 ;也就是你的什么new String("bala")会变成"bala",new Number(2017)会变成2017 ```javascript JSON.stringify(new Number(2017)) //"2017" ``` - 不符合JSON语法的值:undefined、任意的函数(其实有个函数会发生神奇的事,后面会说)以及 symbol 值(ES6 引入了一种新的原始数据类型`Symbol`,表示独一无二的值。它是 JavaScript 语言的第七种数据类型。[symbol详见ES6对symbol的介绍](http://es6.ruanyifeng.com/#docs/symbol)) - 出现在非数组对象的属性值中:在序列化过程中会被忽略 ```javascript JSON.stringify({x: undefined, y: function(){return 1;}, z: Symbol("")}); //"{}" ``` - 出现在数组中时:被转换成 null ​ ```javascript JSON.stringify([undefined,function(){return 1;},Symbol("")]); //"[null,null,null]" ``` - NaN、Infinity和-Infinity,不论在数组还是非数组的对象中,都被转化为null ```javascript JSON.stringify({x: NaN, y: Infinity, z: -Infinity}); //"{"x":null,"y":null,"z":null}" JSON.stringify([ NaN, Infinity, -Infinity]); //"[null,null,null]" ``` - 不可枚举的属性会被忽略 ```javascript var person={"age":12} var xM = Object.defineProperty(person, "name", {     value: "xiaoming",     enumerable: false }); JSON.stringify(person) //"{"age":12}" ``` - replacer:可选,过滤器,可以是一个数组,也可以是一个函数 - 如果是一个数组,则只有数组中存在名称才能够被转换,且转换后顺序与数组中的值保持一致。 - 如果是一个函数,传递key,value,可以对JSON对象每一个属性值及值进行处理后返回。(这里一定要return一个值给下一个遍历函数作为参数传入,如果不return的话,后面的遍历就没法进行下去了。) - 如果是null,那作用上和空着没啥区别,但是不想设置第二个参数,只是想设置第三个参数的时候,就可以设置第二个参数为null ```javascript //如果第二个参数是一个数组 var friend={   "firstName": "Good",   "lastName": "Man",   "phone":"1234567",   "age":18 }; //注意下面的数组有一个值并不是上面对象的任何一个属性名 var friendAfter=JSON.stringify(friend,["firstName","address","phone"]); console.log(friendAfter); //{"firstName":"Good","phone":"1234567"} //指定的“address”由于没有在原来的对象中找到而被忽略 //如果第二个参数是一个函数 var friend={   "firstName": "Good",   "lastName": "Man",   "phone":"1234567",   "age":18 }; var friendAfter=JSON.stringify(friend,function(key,value){   if(key==="phone"){       return "(000)"+value;   }else if(typeof value === "number"){       return value + 10;   }else{       return value; //如果你把这个else分句删除,那么结果会是undefined }); console.log(friendAfter); //输出:{"firstName":"Good","lastName":"Man","phone":"(000)1234567","age":28} ``` - space:可选,表示是否在字符串中保留缩进(用于控制结果中的缩进和空白符) ,默认不保留,并且删除所有换行。 - 如果这个参数是一个数值,那他表示的是每个级别缩进的空格数(最大的缩进空格数为10,超过10都会自动转换为10处理); - 如果缩进是一个字符串而非数值,则这个字符串将在JSON字符串中被用作缩进字符(不再使用空格,最长也不能超过10个字符长) - **序列化是为了传输,传输就是能越小越好,加莫名其妙的缩进符,解析困难(如果是字符串的话),也弱化了轻量化这个特点** ```javascript var friend={   "firstName": "Good",   "lastName": "Man",   "phone":{"home":"1234567","work":"7654321"} }; //直接转化是这样的: //{"firstName":"Good","lastName":"Man","phone":{"home":"1234567","work":"7654321"}} var friendAfter=JSON.stringify(friend,null,4); console.log(friendAfter); /* {   "firstName": "Good",   "lastName": "Man",   "phone": {       "home": "1234567",       "work": "7654321"   } } */ var friendAfter=JSON.stringify(friend,null,"HAHAHAHA"); console.log(friendAfter); /* { HAHAHAHA"firstName": "Good", HAHAHAHA"lastName": "Man", HAHAHAHA"phone": { HAHAHAHAHAHAHAHA"home": "1234567", HAHAHAHAHAHAHAHA"work": "7654321" HAHAHAHA} } */ ``` ##### 4.2影响 JSON.stringify 的神奇函数 如果你在一个JS对象上实现了toJSON方法,那么调用JSON.stringify去序列化这个JS对象时,JSON.stringify会把这个对象的toJSON方法返回的值作为参数去进行序列化。 ```javascript var obj = { "name":"lizongji", "year":2017, "nation":"China", "age":null,     toJSON:function(){ return "Obj" } } JSON.stringify(obj) //'"Obj"' ``` 要注意的是他和 stringify 方法第二个参数稍微有点不同。因为 stringify 第二个参数是回调函数时,只是对当前 key 对应的值进行修改。而 toJSON 则是对当前对象进行修改。 [JSON在线解析及格式化验证](http://json.cn/) 今天的分享之后,小伙伴可以下去试着回答一下下面的问题,嗯确实so easy。 ```javascript //one 以下JS对象通过JSON.stringify后的字符串是怎样的? var friend={   firstName: 'Good',   'lastName': 'Man',   'address': undefined,   'phone': ["1234567",undefined],   'fullName': function(){       return this.firstName + ' ' + this.lastName;   } }; JSON.stringify(friend);//这个会返回什么呢? //two 如果我想在最终JSON字符串将这个'friend'的姓名全部变成大写字母,也就是把"Good"变成"GOOD",把"Man"变成"MAN",那么可以怎么做? ``` <file_sep>/javascript/1.1.md ## 函数是一等公民 #### 1. 传统语言(c/java等) - 函数都是作为一个二等公民存在,只能用语言的关键字声明一个函数然后调用。 #### 2. Javascript - 在JavaScript世界中函数却是一等公民,它不仅拥有一切传统函数的使用方式(声明和调用),而且可以做到像简单值一样赋值、传参、返回。 <file_sep>/vue-webpack/docs/README.md # Introduction 这个样板是针对大型,严肃的项目,并假设你有点熟悉Webpack和vue-loader。请务必阅读常用工作流程配方vue-loader的文档。 如果你只是想尝试vue-loader或鞭出一个快速原型,请使用webpack-simple模板。 ## 快速搭建 要使用此模板,请使用vue-cli构建项目。命令行如下 ``` bash $ npm install -g vue-cli $ vue init webpack my-project $ cd my-project $ npm install $ npm run dev ```<file_sep>/express/mytest/routes/test.js /** * Created by liliangquan on 2017/1/5. */ var express=require('express'); var router=express.Router(); var data={ name: 'nunjucks学习', fruits: ['Apple', 'Pear', 'Banana'], count: 12000 }; router.get('/', function(req, res, next) { console.log(1111); res.render('nun-index', data); }); router.get('/hello', function(req, res, next) { console.log(222222); res.render('hello', data); }); module.exports = router;<file_sep>/javascript/video&danmaku/video&danmaku.md # 项目下载及之后的操作: - git地址: https://git.zhubajie.la/danpengfei/zbj-thinkjs - 安装环境,进入项目根目录 执行命令: npm install thinkjs@2 -g --verbose npm install - 静态文件编译: gulp - 编译并启动server: npm start - 访问server: http://127.0.0.1:8360 # 标签的属性 - src :视频的属性 - poster:视频封面,没有播放时显示的图片 - preload:预加载 - autoplay:自动播放 - loop:循环播放 - controls:浏览器自带的控制条 - width:视频宽度 - height:视频高度 # 网络状态 - video.currentSrc; //返回当前资源的URL - video.src = value; //返回或设置当前资源的URL - video.canPlayType(type); //是否能播放某种格式的资源 - video.networkState; //0.此元素未初始化 1.正常但没有使用网络 2.正在下载数据 3.没有找到资源 - video.load(); //重新加载src指定的资源 - video.buffered; //返回已缓冲区域,TimeRanges - video.preload; //none:不预载 metadata:预载资源信息 auto: # 准备状态 - video.readyState;//1:HAVE_NOTHING 2:HAVE_METADATA 3.HAVE_CURRENT_DATA 4.HAVE_FUTURE_DATA 5.HAVE_ENOUGH_DATA - video.seeking; //是否正在seeking # 回放状态 - video.currentTime = value; //当前播放的位置,赋值可改变位置 - video.startTime; //一般为0,如果为流媒体或者不从0开始的资源,则不为0 - video.duration; //当前资源长度 流返回无限 - video.paused; //是否暂停 - video.defaultPlaybackRate = value;//默认的回放速度,可以设置 - video.playbackRate = value;//当前播放速度,设置后马上改变 - video.played; //返回已经播放的区域,TimeRanges,关于此对象见下文 - video.seekable; //返回可以seek的区域 TimeRanges - video.ended; //是否结束 - video.autoPlay; //是否自动播放 - video.loop; //是否循环播放 - video.play(); //播放 - video.pause(); //暂停 # 视频控制 - video.controls;//是否有默认控制条 - video.volume = value; //音量 - video.muted = value; //静音 # TimeRanges(区域)对象 - TimeRanges.length; //区域段数 - TimeRanges.start(index) //第index段区域的开始位置 - TimeRanges.end(index) //第index段区域的结束位置 # 相关事件 - eventTester("loadstart"); //客户端开始请求数据 - eventTester("progress"); //客户端正在请求数据 - eventTester("suspend"); //延迟下载 - eventTester("abort"); //客户端主动终止下载(不是因为错误引起) - eventTester("loadstart"); //客户端开始请求数据 - eventTester("progress"); //客户端正在请求数据 - eventTester("suspend"); //延迟下载 - eventTester("abort"); //客户端主动终止下载(不是因为错误引起), - eventTester("error"); //请求数据时遇到错误 - eventTester("stalled"); //网速失速 - eventTester("play"); //play()和autoplay开始播放时触发 - eventTester("pause"); //pause()触发 - eventTester("loadedmetadata"); //成功获取资源长度 - eventTester("loadeddata"); // - eventTester("waiting"); //等待数据,并非错误 - eventTester("playing"); //开始回放 - eventTester("canplay"); //可以播放,但中途可能因为加载而暂停 - eventTester("canplaythrough"); //可以播放,歌曲全部加载完毕 - eventTester("seeking"); //寻找中 - eventTester("seeked"); //寻找完毕 - eventTester("timeupdate"); //播放时间改变 - eventTester("ended"); //播放结束 - eventTester("ratechange"); //播放速率改变 - eventTester("durationchange"); //资源长度改变 - eventTester("volumechange"); //音量改变<file_sep>/javascript/4.2.md ## 函数缓存的利弊 #### 利 - 1.函数调用之前计算的结果的时候,能享有性能优势 - 2.幕后黑箱操作,对于方法的调用者和用户来说没有任何区别 #### 弊 - 任何形式的缓存都需要牺牲内存,有些时候很难判断算法的复杂度牺牲的性能更多还是缓存后牺牲的内存更多<file_sep>/javascript/2.3.md ## 作为(函数/对象的方法/构造器)调用 #### 情况一:纯粹的函数调用 function test() { this.x = 1; console.log('我是普通函数调用的this'+this); } test(); // 1 #### 情况二:作为对象方法的调用 var o={ fn:function () { console.log('我是作为对象方法调用后的this'+this) } } // 调用 o.fn(); #### 情况三 作为构造函数调用 function test(){ this.x=5; console.log('我是作为构造函数调用的this:'+this); } var o = new test(); <file_sep>/README.md # learn ## 前端学习 ### demo-master用来存放一些感兴趣的案例【css3,js】 ### express是用来存放自己对于express的运用 ### vue-webpack 利用vue-cli快速搭建项目的文档<file_sep>/javascript/13json/13.2.md ### 2.JSON对象 - ECMAScript5对解析JSON的行为进行了规范,定义了全局对象JSON   [注意]IE7-浏览器不支持(虽然我们现在已经不需要支持了)IE7-浏览器可以通过使用json2.js文件来使用JSON 处理JSON格式的数据。它有两个方法:JSON.stringify和JSON.parse。 <file_sep>/javascript/5.1.md ## 函数重载的意义 #### 1.重载是面向对象三大特性中的多态的表现之一,一个函数可以通过接收不同个数的函数来呈现出不同的“态” #### 2.日常开发中有些功能函数过度封装导致了非常高的耦合,利用函数重载能较快的打到解除耦合的目的 #### 问题:JavaScript并没有像传统面向对象语言那样自带函数重载的功能,需要我们自己通过一些方法去实施重载 <file_sep>/javascript/3.2.md #### 递归函数自引用的方式 - 1.闭包 - 2.this - 3.内联函数 - 4.arguments.callee #### 闭包 var obj ={ Fibonacci:function(n) { if(n<=2){ return 1; }else{ return obj.Fibonacci(n-2)+obj.Fibonacci(n-1); } } }; console.log('没被重置前',obj.Fibonacci(5)); var newObj={ Fibonacci:obj.Fibonacci }; obj={}; console.log('被重置后',newObj.Fibonacci(5)); #### this var obj ={ Fibonacci:function(n) { if(n<=2){ return 1; }else{ return this.Fibonacci(n-2)+this.Fibonacci(n-1); } } }; console.log('没被重置前',obj.Fibonacci(5)); var newObj={ Fibonacci:obj.Fibonacci }; obj={}; console.log('被重置后',newObj.Fibonacci(5)); #### 内联函数 var obj ={ Fibonacci:function fb(n) { if(n<=2){ return 1; }else{ return fb(n-2)+fb(n-1); } } }; console.log('没被重置前',obj.Fibonacci(5)); var newObj={ Fibonacci:obj.Fibonacci }; obj={}; console.log('被重置后',newObj.Fibonacci(5)); #### arguments.callee var obj ={ Fibonacci:function(n) { if(n<=2){ return 1; }else{ return arguments.callee(n-2)+arguments.callee(n-1); } } }; console.log('没被重置前',obj.Fibonacci(5)); var newObj={ Fibonacci:obj.Fibonacci }; obj={}; console.log('被重置后',newObj.Fibonacci(5)); <file_sep>/vue-webpack/docs/project.md # Project Structure ``` bash ├── build/ # 此目录包含开发服务器和生产webpack构建的实际配置。通常你不需要触摸这些文件,除非你想自定义Webpack加载器,在这种情况下你应该看看build/webpack.base.conf.js。 │ └── ... ├── config/ │ ├── index.js # 这是显示构建设置的一些最常见配置选项的主配置文件。 │ └── ... ├── src/ # 这是大多数应用程序代码都存在的地方。 │ ├── main.js # app entry file │ ├── App.vue # main app component │ ├── components/ # ui components │ │ └── ... │ └── assets/ # module assets (processed by webpack) │ └── ... ├── static/ # 此目录是您不想使用Webpack处理的静态资产的转义填充。它们将被直接复制到生成webpack构建的资产的同一目录中。 ├── test/ │ └── unit/ # 包含单元测试相关文件。 │ │ ├── specs/ # │ │ ├── index.js # test build entry file │ │ └── karma.conf.js # test runner config file │ └── e2e/ # 包含e2e测试相关文件 │ │ ├── specs/ # test spec files │ │ ├── custom-assertions/ # custom assertions for e2e tests │ │ ├── runner.js # test runner script │ │ └── nightwatch.conf.js # test runner config file ├── .babelrc # babel config ├── .editorconfig.js # editor config ├── .eslintrc.js # eslint config ├── index.html # 这是我们的单页应用程序的模板 index.html。在开发和构建期间,Webpack将生成资产,并且这些生成的资产的URL将自动注入此模板以呈现最终的HTML。 └── package.json # NPM包元文件,其中包含所有构建依赖项和构建命令。 ``` ### `build/` 此目录包含开发服务器和生产webpack构建的实际配置。通常你不需要触摸这些文件,除非你想自定义Webpack加载器,在这种情况下你应该看看build/webpack.base.conf.js。 ### `config/index.js` 这是显示构建设置的一些最常见配置选项的主配置文件。有关更多详细信息,请参阅[API代理](api-proxy.md)和 [与后端框架集成](backend.md) ### `src/` 这是大多数应用程序代码都存在的地方。如何构建这个目录中的所有内容主要取决于您; 如果使用Vuex,可以参考Vuex应用程序的建议。 ### `static/` 此目录是您不想使用Webpack处理的静态资产的转义填充。它们将被直接复制到生成webpack构建的资产的同一目录中。 有关详细信息,请参阅[处理静态资产](static.md) ### `test/unit` 包含单元测试相关文件。有关详细信息,请参阅[单元测试](unit-test.md) ### `test/e2e` 包含e2e测试相关文件。有关详细信息,请参阅[端到端测试](end.md)。 ### `index.html` 这是我们的单页应用程序的模板 index.html。在开发和构建期间,Webpack将生成资产,并且这些生成的资产的URL将自动注入此模板以呈现最终的HTML。 ### `package.json` NPM包元文件,其中包含所有构建依赖项和构建命令。 <file_sep>/javascript/8.1.md ### javascript纯函数 ### 定义 纯函数是指不依赖于且不改变它作用域之外的变量状态的函数。 也就是说,纯函数的返回值只由它调用时的参数决定,它的执行不依赖于系统的状态。 * 1.一个输入只有一个输出 * 2.函数的计算过程没有副作用 * 3.函数不依赖外部状态 满足这三个点的才能叫纯函数 纯函数是函数式编程的一个基础。接下来我们看一个简单的例子。 var values = { a: 1 }; function impureFunction ( obj ) { var b = 1; obj = obj * b + 2; return obj.a; } var c = impureFunction( values ); // 现在 `values.a` 变成 3, impureFunction 改变了它。 在上面的代码中,我们改变了参数对象中的一个属性。由于我们定义的函数改变的对象在我们的函数作用域之外,导致这个函数成为“不纯”的函数。 var values = { a: 1 }; function impureFunction ( obj ) { var b = 1; obj = obj * b + 2; return obj; } var c = impureFunction( values ); 上面的代码,我们只计算了作用域内的局部变量,没有任何作用域外部的变量被改变,因此这个函数是“纯函数”。 纯函数是这样一种函数,即相同的输入,永远会得到相同的输出,而且没有任何可观察的副作用。 printf() 是非纯函数,因为它促使输出到一个I/O装置,产生了副作用。 var xs = [1,2,3,4,5]; // 纯函数 xs.slice(0,3); //=> [1,2,3] xs.slice(0,3); //=> [1,2,3] xs.slice(0,3); //=> [1,2,3] // 非纯函数 xs.splice(0,3); //=> [1,2,3] xs.splice(0,3); //=> [4,5] xs.splice(0,3); //=> [] * 问题:假设我们在一次项目迭代中,需要将splice变成纯函数,并且还不能影响原来的功能,运用前面讲的重载闭包方式实现。【杰锅赞助饮料一瓶】 ``` //参考答案 Array.prototype.splice = (function () { var oldfn = Array.prototype.splice; return function () { var flag=Object.prototype.toString.call(arguments[0]) === '[object Array]', context=flag?this.concat():this, arg=flag?arguments[0]:arguments; return oldfn.apply(context, arg); } })(); var a=[1,2,3,4,5];var c=a.splice(0,3);console.log(a,c); -->[4, 5] [1, 2, 3] var a=[1,2,3,4,5];var c=a.splice([0,3]);console.log(a,c); -->[1, 2, 3, 4, 5] [1, 2, 3] //例一代码 var spliceFn = Array.prototype.splice; Array.prototype.splice = function(){ var isWritable = arguments[0] === false ? false : true; var self = isWritable ? this : this.slice(0); var n = isWritable ? 0 : 1; var args = Array.prototype.slice.call(arguments, n); //例二代码 Array.prototype.splice = (function () { var nativeSplice = Array.prototype.splice; return function () { if (typeof arguments[0] === 'boolean') { var orgs = [].slice.call(arguments, 1); var newArr = this.concat(); return nativeSplice.apply(newArr, orgs); } else { return nativeSplice.apply(this, arguments); } } })() ``` ### 使用纯函数的好处 * 首先它没有副作用,纯函数是不会修改作用域之外的状态,就意味着代码变得足够的简单和清晰;当你在调用一个纯函数的时候,你只要关注它的返回值,不用担心因为其他地方的问题影响里面出问题。 * 纯函数是健壮的,改变执行次序不会对系统造成影响,因此纯函数的操作可以并行执行。 * 纯函数非常容易进行单元测试,因为不需要考虑上下文环境,只需要考虑输入和输出。 <file_sep>/vue-webpack/docs/unit-test.md # 单元测试 本样板用于单元测试的工具概述: - [Karma](https://karma-runner.github.io/): 启动浏览器的测试运行器,运行测试并将结果报告给我们。 - [karma-webpack](https://github.com/webpack/karma-webpack): Karma的插件,它使用Webpack捆绑我们的测试。 - [Mocha](https://mochajs.org/): 我们写测试规范的测试框架。 - [Chai](http://chaijs.com/): 测试断言库,提供更好的断言语法。 - [Sinon](http://sinonjs.org/): 提供间谍,存根和模拟的测试实用程序库。 柴和兴农使用的是集成卡玛兴农齐[karma-sinon-chai](https://github.com/kmees/karma-sinon-chai)因此所有的柴接口(should,expect,assert) ,并sinon在测试文件全局可用。 And the files: - `index.js` 这是用于karma-webpack捆绑所有测试代码和源代码(用于覆盖目的)的条目文件。你可以忽略它的大部分。 - `specs/` 这个目录是你写实际测试的地方。您可以在测试中使用完整的ES2015 +和所有支持的Webpack加载器。 - `karma.conf.js` 这是Karma配置文件。有关详细信息,请参阅Karma文档[Karma docs](https://karma-runner.github.io/) ## 在更多浏览器中运行测试 您可以通过安装更多的karma发射器并调整其中的browsers字段,在多个实际浏览器中运行测试test/unit/karma.conf.js。 ## 模拟依赖 默认情况下,此样板自带了inject-loader[inject-loader](https://github.com/plasticine/inject-loader)。有关*.vue组件的使用,请参阅[vue-loader docs on testing with mocks](http://vue-loader.vuejs.org/en/workflow/testing-with-mocks.html). <file_sep>/mongodb-koa/app.js const fs = require('fs') const path = require('path') const mongoose = require('mongoose') const db = 'mongodb://localhost:27017/test' /** * mongoose连接数据库 * @type {[type]} */ mongoose.Promise = require('bluebird') mongoose.connect(db) /** * 获取数据库表对应的js对象所在的路径 * @type {[type]} */ const models_path = path.join(__dirname, '/app/models') /** * 已递归的形式,读取models文件夹下的js模型文件,并require * @param {[type]} modelPath [description] * @return {[type]} [description] */ var walk = function(modelPath) { fs .readdirSync(modelPath) .forEach(function(file) { var filePath = path.join(modelPath, '/' + file) var stat = fs.statSync(filePath) if (stat.isFile()) { if (/(.*)\.(js|coffee)/.test(file)) { require(filePath) } } else if (stat.isDirectory()) { walk(filePath) } }) } walk(models_path) const Koa = require('koa') const logger = require('koa-logger') const session = require('koa-session') const bodyParser = require('koa-bodyparser') const app = new Koa() app.keys = ['prune'] app.use(logger()) app.use(session(app)) app.use(bodyParser()) /** * 使用路由转发请求 * @type {[type]} */ const router = require('./router/index')() app .use(router.routes()) .use(router.allowedMethods()); // 访问静态资源文件 这里是访问所有dist目录下的静态资源文件 // app.use(express.static(path.resolve(__dirname, '../dist'))) // 首页静态页面 // app.get('*', function(req, res) { // const html = fs.readFileSync(path.resolve(__dirname, '../dist/index.html'), 'utf-8') // res.send(html) // }) app.listen(9000) console.log('app started at port 9000...');<file_sep>/javascript/1.3.md ## 事件轮询机制 概念:主线程从“任务队列”中读取事件,这个过程是循环不断的,所以整个的这 种运行机制又称为Event Loop。 - JavaScript是单线程 - 任务队列 - 事件和回调函数 ![PNG](1.png) <file_sep>/mongodb-koa/readme.md ## mongodb+koa尝试 ## 启动 ```js mongod --dbpath +路径 ``` ```js npm start ``` 可以用postman进行接口测试<file_sep>/javascript/1.md ## 函数的特性 by 周杨 2016/12/13 <file_sep>/vue-webpack/docs/linter.md # Linter配置 此样板使用ESLint作为linter,并使用标准预设与一些小的自定义。 如果你不满意默认的linting规则,你有几个选择: - 1 覆盖中的各个规则.eslintrc.js。例如,您可以添加以下规则以强制使用分号,而不是省略它们: ``` js "semi": [2, "always"] ``` - 2 在生成项目时选择不同的ESLint预设,例如[eslint-config-airbnb](https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb) - 3 在生成项目并定义自己的规则时,为ESLint预设选择“无”。有关更多详细信息,请参阅[ESLint文档](http://eslint.org/docs/rules/) <file_sep>/javascript/6.2.md ##闭包的常用例子 ####处理回调 ``` //防连点 function() { var isSubmiting = true; var url = "http://www.baidu.com/"; $.ajax({ url : url, success : function() { isSubmiting = false; // do sth... } }); } ``` ####处理定时器 ``` for (var i = 0; i < 10; i++) { setTimeout((function(i) { return function(){ console.log(i); } })(i), 2000); } ``` <file_sep>/vue-demo1/src/store/action.js const actions = { asyncIncrement (context) { console.log(context) setTimeout(() => { context.commit('increment') }, 1000) }, asyncLessCount ({commit}) { setTimeout(() => { commit('lessCount') }, 1000) } } export default actions <file_sep>/javascript/5.2.md ## 函数重载的实现方式 #### 1.判断参数是否存在 function fn(a,b,c){ if(c){ return a*b; }else{ return a+b; } } console.log('两个参数',fn(4,5)); console.log('三个参数',fn(4,5,true)); #### 2.switch参数个数 function fn(){ switch(arguments.length){ case 1: console.log('执行1个参数的方法'); break; case 2: console.log('执行2个参数的方法'); break; case 3: console.log('执行3个参数的方法'); break; } } fn(1); fn(1,2); fn(1,2,3); #### 3.重载挂载 var demo={}; function addMethod(obj,name,fn){ var oldFn=obj[name]; obj[name]=function(){ console.log(fn.length,arguments.length); if(fn.length==arguments.length){ return fn.apply(this,arguments); }else if(typeof oldFn == 'function'){ return oldFn.apply(this,arguments); } } } addMethod(demo,'calc',function(){ return 0; }); addMethod(demo,'calc',function(a,b){ return a+b; }); addMethod(demo,'calc',function(a,b,c){ return a*b; }); addMethod(demo,'calc',function(a,b,c,d){ return a-b; });<file_sep>/lq-shell/readme.md ## 1 前言 ### 1.1 像我们熟悉的 vue-cli,taro-cli 等脚手架,只需要输入简单的命令 taro init project,即可快速帮我们生成一个初始项目。在日常开发中,有一个脚手架工具可以用来提高工作效率。 ### 1.2 为什么需要脚手架 * 减少重复性的工作,从零创建一个项目和文件。 * 根据交互动态生成项目结构和配置文件等。 * 多人协作更为方便,不需要把文件传来传去。 ### 1.3 怎样来搭建呢? 脚手架是怎么样进行构建的呢,我是借助了[taro-cli](https://github.com/NervJS/taro/tree/master/packages/taro-cli)的思路。 ### 1.4 本文的目标读者 * 1 想要学习更多和了解更多的人 * 2 对技术充满热情 ## 2 搭建前准备 ### 2.1 第三方工具 * [commander.js](https://github.com/tj/commander.js),可以自动的解析命令和参数,用于处理用户输入的命令。 * [download-git-repo](https://github.com/flipxfx/download-git-repo),下载并提取 git 仓库,用于下载项目模板。 * [Inquirer.js](https://github.com/SBoudrias/Inquirer.js),通用的命令行用户界面集合,用于和用户进行交互。 * [handlebars.js](https://github.com/wycats/handlebars.js),模板引擎,将用户提交的信息动态填充到文件中。 * [ora](https://github.com/sindresorhus/ora),下载过程久的话,可以用于显示下载中的动画效果。 * [chalk](https://github.com/chalk/chalk),可以给终端的字体加上颜色。 * [log-symbols](https://github.com/sindresorhus/log-symbols),可以在终端上显示出 √ 或 × 等的图标 ### 2.2 上手 #### 2.2.1 新建一个文件夹,然后npm init初始化 npm 不单单用来管理你的应用和网页的依赖,你还能用它来封装和分发新的 shell 命令。 ``` $ mkdir lq-cli $ npm init ``` 这时在我们的lq-cli项目中有 package.json 文件,然后需要创建一个 JS 文件包含我们的脚本就取名index.js吧。 package.json内容如下 ``` { "name": "lq-shell", "version": "1.0.0", "description": "脚手架搭建", "main": "index.js", "bin": { "lq": "./index.js" }, "scripts": { "test": "test" }, "keywords": [ "cli" ], "author": "prune", "license": "ISC" } ``` index.js内容如下 ``` #!/usr/bin/env node console.log('Hello, cli!'); ``` 到这一步就可以简单运行一下这个命令 ``` npm link lq ``` npm link命令可以将一个任意位置的npm包链接到全局执行环境,从而在任意位置使用命令行都可以直接运行该npm包。 控制台会输出`Hello, cli!` #### 2.2.2 捕获init之类的命令 前面的一个小节,可以跑一个命令行了,但是我们看到的taro-cli中还有一些命令,init初始化项目之类。这个时候`commander`就需要利用起来了。 运行下面的这个命令将会把最新版的 commander 加入 package.json ``` npm install --save commander ``` 引入commander我们将index.js做如下修改 ``` #!/usr/bin/env node console.log('Hello, cli!') const program = require('commander') program .version(require('./package').version, '-v, --version') .command('init <name>') .action((name) => { console.log(name) }) program.parse(process.argv) ``` 可以通过`lq -v`来查看版本号 通过`lq init name`的操作,action里面会打印出name #### 2.2.3 对console的美工 我们看到taro init 命令里面会有一些颜色标识,就是因为引入了chalk这个包,同样和commander一样 ``` npm install --save chalk ``` console.log(chalk.green('init创建')) 这样会输出一样绿色的 #### 2.2.4 模板下载 download-git-repo 支持从 Github下载仓库,详细了解可以参考官方文档。 ``` npm install --save download-git-repo ``` download() 第一个参数就是仓库地址,详细了解可以看官方文档 #### 2.2.5 命令行的交互 命令行交互功能可以在用户执行 init 命令后,向用户提出问题,接收用户的输入并作出相应的处理。用 inquirer.js 来实现。 ``` npm install --save inquirer ``` index.js文件如下 ``` #!/usr/bin/env node const chalk = require('chalk') console.log('Hello, cli!') console.log(chalk.green('init创建')) const program = require('commander') const download = require('download-git-repo') const inquirer = require('inquirer') program .version(require('./package').version, '-v, --version') .command('init <name>') .action((name) => { console.log(name) inquirer.prompt([ { type: 'input', name: 'author', message: '请输入你的名字' } ]).then((answers) => { console.log(answers.author) download('', name, {clone: true}, (err) => { console.log(err ? 'Error' : 'Success') }) }) }) program.parse(process.argv) ``` #### 2.2.6 ora进度显示 ``` npm install --save ora ``` 相关命令可以如下 ``` const ora = require('ora') // 开始下载 const proce = ora('正在下载模板...') proce.start() // 下载失败调用 proce.fail() // 下载成功调用 proce.succeed() ``` #### 2.2.6 log-symbols 在信息前面加上 √ 或 × 等的图标 ``` npm install --save log-symbols ``` 相关命令可以如下 ``` const chalk = require('chalk') const symbols = require('log-symbols') console.log(symbols.success, chalk.green('SUCCESS')) console.log(symbols.error, chalk.red('FAIL')) ``` #### 2.2.7 完整文件如下 ``` #!/usr/bin/env node const chalk = require('chalk') console.log('Hello, cli!') console.log(chalk.green('init创建')) const fs = require('fs') const program = require('commander') const download = require('download-git-repo') const inquirer = require('inquirer') const ora = require('ora') const symbols = require('log-symbols') program .version(require('./package').version, '-v, --version') .command('init <name>') .action((name) => { console.log(name) inquirer.prompt([ { type: 'input', name: 'author', message: '请输入你的名字' } ]).then((answers) => { console.log(answers.author) const lqProcess = ora('正在创建...') lqProcess.start() download('github:/Mr-Prune/learn/mongodb-koa', name, {clone: true}, (err) => { if (err) { lqProcess.fail() console.log(symbols.error, chalk.red(err)) } else { lqProcess.succeed() const fileName = `${name}/package.json` const meta = { name, author: answers.author } if(fs.existsSync(fileName)){ const content = fs.readFileSync(fileName).toString(); const result = handlebars.compile(content)(meta); fs.writeFileSync(fileName, result); } console.log(symbols.success, chalk.green('创建成gong')) } }) }) }) program.parse(process.argv) ``` ## 总结 通过上面的例子只是能够搭建出一个简单的脚手架工具,其实bash还可以做很多东西,比如 npm 包优雅地处理标准输入、管理并行任务、监听文件、管道流、压缩、ssh、git等,要想了解更多,就要深入了解,这里只是打开一扇门,学海无涯<file_sep>/javascript/6.3.md ##闭包的作用 ####利用闭包变量私有化 ``` //我们创建了一个变量slices来保存状态。这个变量只能在Ninja()函数内部访问。这就意味着我们可以维持状态而不让它们被用户直接访问,从而实现了私有变量的相同意义。 function Ninja() { var slices = 0; this.getSlices = function() { return slices; }; this.slice = function() { slices++; } } var ninja = new Ninja(); ninja.slice(); console.log('ninja.getSlices():'+ninja.getSlices()); console.log('ninja.slices:'+ninja.slices); ``` ####利用闭包绑定上下文 ``` //粗糙实现prototype.bind Function.prototype.bind =Function.prototype.bind || function (scope) { var fn = this; return function () { return fn.apply(scope,arguments); }; } //应用bind var foo = { x: 3 } var bar = function(y){ console.log(this.x,y); } bar(); var boundFunc = bar.bind(foo); boundFunc(12); ``` <file_sep>/javascript/8.2.md ## javascript高阶函数 ### 高阶函数 这是一个有趣的东西,也说明了javascript对象的强大,我们要做的就是输出一个helloworld。 高阶看上去就像是一种先进的编程技术的一个深奥术语【ps:我刚开始是这样子认为的。】 然而,在javascript中,高阶函数只是将函数作为参数或返回值的函数。我们来看一个helloworld的简单例子。 var test = function(p1){ this.add = function (p2){ return p1 + ' ' + p2; }; return add; }; 我们可以这样子使用这个函数: console.log(test('Hello')('New Year!')); 上面的这个过程我们可以简写一下就会更加明白,实际上test('Hello')是一个函数。 var t=test('Hello'); t('New Year!'); "Hello New Year!" 从上面我们可以看出,高阶函数可以使代码更加的简洁、高效。 接下来来一个简单实例 add = function(a,b){ return a + b; }; function math(func,array){ return func(array[0],array[1]); } console.log(math(add,[1,2])); 在上面的实例中,传进去的add是一个参数,返回的时候是一个函数。 接下来,看一下应用场景 #### 1 回调函数 通过回调函数将业务的重点聚焦在回调函数中,而不必每次都要重复编写遍历代码。 例如ajax请求 #### 2 偏函数 作为将函数当作返回值输出的典型应用就是偏函数。看个类型判断的例子。 js的对象有三个属性:原型、类、可扩展性。判断类型的代码如下 isString = function(obj){ return Object.prototype.toString.call(obj)=== "[object String]"; } isNumber = function(obj){ return Object.prototype.toString.call(obj)=== "[object Number]"; } isArray = function(obj){ return Object.prototype.toString.call(obj)=== "[object Array]"; } 这几个函数的大部分代码是重复的,这是高阶函数的便华丽的登场了。 isType = function(type) { return function(obj) { return Object.prototype.toString.call(obj) === "[object " + type + "]"; } } isString = isType('String'); isNumber = isType('Number'); isArray = isType('Array'); 还可以这样简写 var obj=["Arguments", "Function", "String", "Number", "Date", "RegExp", "Error"]; obj.forEach(function(t) { p["is" + t] = function(e) { return toString.call(e) === "[object " + t + "]" } }) 所以通过指定部分参数来返回一个新的定制函数的形式就是偏函数。 #### 3 事件节流   在某些场景下,某些事件可能会被重复的触发,但事件处理函数并不需要每次都执行。比如在window.resize事件中进行复杂的逻辑计算,如果用户频繁的改变浏览器大小,复杂计算会对性能造成严重影响;有时这些逻辑计算并不需要每次rezise时都触发,只需要计算有限的几次便可以。这时我们需要根据时间段来忽略一些事件请求。请看以下节流函数: function throttle(fn, interval) { var doing = false; return function() { if (doing) { return; } doing = true; fn.apply(this, arguments); setTimeout(function() { doing = false; }, interval); } } window.onresize = throttle(function(){ console.log('execute'); }, 500);   通过控制函数执行时间,可以在函数执行次数与功能需求之间达到完美平衡。另一个事件是mousemove。如果我们给一个dom元素绑定该事件,鼠标在改元素上移动时,该事件便会重复触发 #### 4 事件结束   对于某些可以频繁触发的事件,有时候我们希望在事件结束后进行一系列操作。这时我们可以利用高阶函数做如下处理: function debounce(fn, interval) { var timer = null; function delay() { var target = this; var args = arguments; return setTimeout(function(){ fn.apply(target, args); }, interval); } return function() { if (timer) { clearTimeout(timer); } timer = delay.apply(this, arguments); } }; window.onresize = throttle(function(){ console.log('resize end'); }, 500); 如果在这一过程中事件被触发则清除上一次事件句柄,重新绑定执行时间 <file_sep>/demos-master/README.md # demos a bunch of demos ##Run 在项目目录下运行http-server即可 ##目前可以公开的情报 1. css3 2. js-practice(js基础实践) 3. regex(正则表达式) <file_sep>/javascript/6.1.md ##什么是闭包 ####有权访问另一个变量域中的变量的函数 ``` function a(){ var i=0; function b(){ console.log(++i); } return b; } var c = a(); c(); //这段代码有两个特点: //1、函数b嵌套在函数a内部; //2、函数a返回函数b。 //这样在执行完var c=a()后,变量c实际上是指向了函数b,再执行c()后就会在控制台打印出i的值(第一次为1)。这段代码其实就创建了一个闭包,为什么?因为函数a外的变量c引用了函数a内的函数b,就是说: //当函数a的内部函数b被函数a外的一个变量引用的时候,就创建了一个闭包。 ``` ####闭包是怎样工作的 + 以第一个例子为例,a执行完并返回后,闭包使得Javascript的垃圾回收机制GC不会收回a所占用的资源,因为a的内部函数b的执行需要依赖a中的变量。在上面的例子中,由于闭包的存在使得函数a返回后,a中的i始终存在,这样每次执行c(),i都是自加1后打印出i的值。 <file_sep>/javascript/1.2.md ## 函数是第一型对象 #### 1.函数可以通过自变量进行创建 function myfunc(/* arguments */) { } #### 2.函数可以赋值给变量,数组或者其他对象的属性 var myfunc = function (/* arguments */) { } var myfunc2 = { getFun: function () { } } #### 3.函数可以作为参数传递给函数 function a() { console.log('我是a中的内容!') } function b(cb) { cb(); } b(a); #### 4.函数可以作为函数的返回值进行返回 function f1() { var n = 999; function f2() { console.log('我是f2函数里的n:' + n); } return f2; } f1(); #### 5.函数可以拥有动态创建并赋值的属性 var a = "var sum;"; var b = "sum = x + y;"; var c = "return sum;"; var square = new Function("x", "y", a + b + c); console.log('我是动态创建的加法函数并且值为:'+square(2, 3)); b = "sum = x -y;"; var square = new Function(" x", "y", a + b + c); console.log('我是动态创建的减法函数并且值为:'+square(2, 3));<file_sep>/vue-webpack/docs/environment.md # 环境变量 有时,根据应用程序运行的环境,具有不同的配置值是实用的。 举个例子: ```js // config/prod.env.js module.exports = { NODE_ENV: '"production"', DEBUG_MODE: false, API_KEY: '"..."' // this is shared between all environments } // config/dev.env.js module.exports = merge(prodEnv, { NODE_ENV: '"development"', DEBUG_MODE: true // this overrides the DEBUG_MODE value of prod.env }) // config/test.env.js module.exports = merge(devEnv, { NODE_ENV: '"testing"' }) ``` > 注意:字符串变量需要包装为单引号和双引号'"..."' 所以,环境变量是: - 产生 - NODE_ENV = 'production', - DEBUG_MODE = false, - API_KEY = '...' - 发展 - NODE_ENV = 'development', - DEBUG_MODE = true, - API_KEY = '...' - 测试 - NODE_ENV = 'testing', - DEBUG_MODE = true, - API_KEY = '...' 正如我们可以看到的,test.env继承dev.env和dev.env继承prod.env ### 用法 在代码中使用环境变量很简单。例如: ```js Vue.config.debug = process.env.DEBUG_MODE ```<file_sep>/javascript/2.1.md ## 形参和实参 - 调用函数传递的实参与定义函数规定的形参是依次对应的,即第1个实参的值传递给第1个形参,第2个实参的值传递给第2个形参... - 超出形参数目的实参不使用其值。(可用arguments取到) - 如果没有对应的实参(实参数目少于形参数目)传入,其值为undefined。 - 调用函数时传递的实参数目可以大于形参数目,但是最好不要小于形参数目 <file_sep>/javascript/7.1.md ####apply取数组中的最大 ``` function max1(arr){ return Math.max.apply(this, arr) } var arr1 = [1,2,3,4,5,9,8,7,6] max1(arr1) ```<file_sep>/javascript/3.1.md #### 函数递归的概念 - 程序调用自身的编程技巧称为递归( recursion),它通常把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解,递归策略只需少量的程序就可描述出解题过程所需要的多次重复计算,大大地减少了程序的代码量。 - 递归通常有三个必备点 1.递归前进段 2.边界条件 3.递归返回段 #### 斐波拉契数列 - 斐波那契数列(Fibonacci sequence),又称黄金分割数列、因数学家列昂纳多·斐波那契(Leonardoda Fibonacci)以兔子繁殖为例子而引入,故又称为“兔子数列”,指的是这样一个数列:1、1、2、3、5、8、13、21、34、……在数学上,斐波纳契数列以如下被以递归的方法定义:F(1)=1,F(2)=1, F(n)=F(n-1)+F(n-2)(n>2,n∈N*) - 入参:n 代表队列中的第N个数字 - 出参:代表第N个数字的值 #### 斐波拉契数列的实现 function Fibonacci(n) { if(n<=2){ return 1; }else{ return Fibonacci(n-2)+Fibonacci(n-1); } } console.log('第三项的值为',Fibonacci(3)); console.log('第四项的值为',Fibonacci(4)); console.log('第五项的值为',Fibonacci(5)); console.log('第六项的值为',Fibonacci(6)); <file_sep>/javascript/2.2.md ## arguments与this #### 一、arguments ##### 1.Javascript并没有重载函数的功能,但是Arguments对象能够模拟重载。 ##### 2.Javascrip中的每个函数都会有一个Arguments对象实例arguments,它引用着函数的实参,可以用数组下标的方式"[]"引用arguments的元素。 - arguments.length为函数实参个数。 - arguments.callee引用函数自身。详情见:[http://www.jianshu.com/p/a426979b9605](http://www.jianshu.com/p/a426979b9605) - arguments.callee.length判断形参个数 function test() { var s = ''; for (i = 0; i < arguments.length; i++) { s += arguments[i] + ","; } console.log(arguments.length); console.log(arguments.callee); return s; } test("name", "age") ### 二、this ![PNG](2.png) <file_sep>/vue-webpack/docs/SUMMARY.md # Summary * [介绍](README.md) * [项目结构](project.md) * [构建命令](create.md) * [linter配置](linter.md) * [前处理器](pre-process.md) * [处理静态资产](static.md) * [环境变量](environment.md) * [开发过程中api代理](api-proxy.md) * [单元测试](unit-test.md) * [与后端框架集成](backend.md) * [端到端测试](end.md) * [预渲染seo](seo.md) <file_sep>/javascript/2.4.md ## call/apply的用法 ![PNG](3.png) #### 实例: //1、call/apply常规用法 function add(a,b) { console.log('a+b='+(a+b)); } function sub(a,b) { console.log('a-b='+(a-b)); } add.call(sub,3,1); add.apply(sub,[3,1]) //2、call、apply实现继承 function Animal(name){ this.name = name; this.showName = function(){ console.log(this.name); } } function Cat(name){ Animal.call(this, name); } var cat = new Cat("Black Cat"); cat.showName();<file_sep>/vue-webpack/docs/seo.md # 预渲染SEO 如果您想要预渲染路由,一旦推送到生产,它不会显着更改,请使用此Webpack插件:[prerender-spa-plugin](https://www.npmjs.com/package/prerender-spa-plugin),已经过测试与Vue一起使用。对于网页不经常更改,[Prerender.io](https://prerender.io/) 和[Netlify](https://www.netlify.com/pricing) 都提供计划定期重新预呈现您的搜索引擎的内容。 ## Using `prerender-spa-plugin` 1. 将其作为开发人员依赖关系安装: ```bash npm install --save-dev prerender-spa-plugin ``` 2. 在build / webpack.prod.conf.js中需要它: ```js // This line should go at the top of the file where other 'imports' live in var PrerenderSpaPlugin = require('prerender-spa-plugin') ``` 3. 在plugins数组中(也在build / webpack.prod.conf.js中)配置它: ```js new PrerenderSpaPlugin( // Path to compiled app path.join(__dirname, '../dist'), // List of endpoints you wish to prerender [ '/' ] ) ``` 如果你也想预呈现/about和/contact,然后该数组会[ '/', '/about', '/contact' ]。<file_sep>/javascript/1.4.md ## 1.4 函数的回调机制 ### 1.回调函数定义 - 定义:在JavaScript中,回调函数具体的定义为:函数A作为参数(函数引用)传递到另一个函数B中,并且这个函数B执行函数A。我们就说函数A叫做回调函数。如果没有名称(函数表达式),就叫做匿名回调函数。 ### 2.回调函数在什么时候执行? - 回调函数,一般在同步情境下是最后执行的,而在异步情境下有可能不执行,因为事件没有被触发或者条件不满足。 ### 3.回调函数的使用场合 - 回调函数,一般在同步情境下是最后执行的,而在异步情境下有可能不执行,因为事件没有被触发或者条件不满足。 - 资源加载:动态加载js文件后执行回调,加载iframe后执行回调,ajax操作回调,图片加载完成执行回调,AJAX等等。 - DOM事件及Node.js事件基于回调机制(Node.js回调可能会出现多层回调嵌套的问题)。 - setTimeout的延迟时间为0,这个hack经常被用到,settimeout调用的函数其实就是一个callback的体现。 - 链式调用:链式调用的时候,在赋值器(setter)方法中(或者本身没有返回值的方法中)很容易实现链式调用,而取值器(getter)相对来说不好实现链式调用,因为你需要取值器返回你需要的数据而不是this指针,如果要实现链式方法,可以用回调函数来实现 //链式调用中使用回调函数 window.API2 = window.API2 || function () { var name = 'zhouyang'; this.setName = function (newName) { name = newName; return this; }; this.getName = function (callback) { callback.call(this, name); return this; }; }; var o2 = new API2(); var log = function (el) { console.log('我是回调函数里的值:'+el); }; o2.getName(log).setName('Hehe').getName(log); <file_sep>/javascript/13json/13.1.md ##JSON浅谈 ###1.JSON简介 #####1.1JSON是什么? JSON(Javascript Object Notation)全称是javascript对象表示法,它是一种**数据交换**的文本格式(轻量级(Light-Weight)、 基于文本的 (Text-Based)、 可读的 (Human-Readable)格式),而不是一种编程语言(虽然具有和JavaScript相同的语法形式,但是JSON并不属于JavaScript),用于读取结构化数据。 #####1.2JSON的语法 - 简单值 + 使用与JavaScript相同的语法,可以在JSON中表示字符串,数值,布尔值和null,但是JSON不支持JavaScript中的特殊值undefined ```javascript //合格的简单值 5 "hello world" true null //不合格的简单值 +0x1 'hello world' undefined NaN Infinity ``` + JavaScript字符串与JSON字符串最大的区别在于,JSON字符串必须使用双引号(单引号会导致语法错误) - 对象 ```javascript //合格的对象 { "name":"huochai", "age":29, "school":{ "name":"diankeyuan", "location":"beijing" } } //不合格的对象 { name: "张三", 'age': 32 }//属性名必须使用双引号 {};//不需要末尾的分号 { "birthday": new Date('Fri, 26 Aug 2011 07:13:10 GMT'), "getName": function() { return this.name; } } // 不能使用函数和日期对象 ``` 与JavaScript的对象字面量相比。JSON没有声明变量;没有末尾的分号;对象的键名及属性值必须加上**双引号**(而不是单引号或者不加引号)。 - 数组 ```javascript //合格的数组 ["zhangsan","lisi"] //不合格的数组 ['1989','2001',]//属性名必须使用双引号,末尾不能加逗号 ``` 总的来说JSON格式和JS对象语法上的区别有以下几点: ![image](./json-js.png) 可以看到,相对于JS对象,JSON的格式更严格,所以大部分写的JS对象是不符合JSON的格式的。 #####1.3JSON 和 XML - 相比 XML,JSON 的优势如下: + 没有结束标签,长度更短,读写更快 + 能够直接被 JavaScript 解释器解析 + 可以使用数组 - 下面是描述同样信息的 XML 文件和 JSON 文件,来看看区别。 ```javascript //JSON: { name:"lizongji", year:2017, friends:["xiaoming","xiaohong","xiaoxing"] } ``` ```HTML //XML: <root> <name>lizongji</name> <year>2017</year> <friends>xiaoming</friends> <friends>xiaohong</friends> <friends>xiaoxing</friends> </root> ``` 可以看到,描述同样的信息,XML 更加麻烦,而 JSON 要轻巧得多,在有数组出现的情况下更加明显。而且,当数组项很多的时候,XML 文件中的大量信息都被用于描述没什么用的标签上了。  <file_sep>/javascript/js/9.2.md ## js对象属性解析 js中所有的食物都是对象,比如String、Date、Array 等等。 对象只是带有属性和方法的特殊数据类型。 ### 1 创建对象 function Person() { } var person = new Person(); person.name = 'name'; console.log(person.name) // name ### 2 prototype 每个函数都有一个prototype属性,就是我们经常在各种例子中看到的那个prototype function Person() { } // prototype是函数才会有的属性 Person.prototype.name = 'name'; var person1 = new Person(); var person2 = new Person(); console.log(person1.name) // name console.log(person2.name) // name 那这个函数的prototype属性到底指向的是什么呢?是这个函数的原型吗? 其实,函数的prototype属性指向了一个对象,这个对象正是调用该构造函数而创建的实例的原型,也就是这个例子中的person1和person2的原型。 那么什么是原型呢?你可以这样理解:每一个JavaScript对象(null除外)在创建的时候就会与之关联另一个对象,这个对象就是我们所说的原型,每一个对象都会从原型"继承"属性。 ![关系图](proto.png) 在这张图中我们用Object.prototype表示实例原型 那么我们该怎么表示实例与实例原型,也就是person和Person.prototype之间的关系呢,这时候我们就要讲到第二个属性: ### 3 _proto_ 这是每一个JavaScript对象(除了null)都具有的一个属性,叫__proto__,这个属性会指向该对象的原型。 function Person() { } var person = new Person(); console.log(person.__proto__ === Person.prototype); //true __proto__, 绝大部分浏览器都支持这个非标准的方法访问原型,然而它并不存在与Person.prototype中,实际上,它是来自于Object.prototype,与其说是一个属性,不如说是一个getter/setter,当使用obj.__proto__时,可以理解成返回了Object.getPrototypeOf(obj) ![关系图1](proto1.png) ### 4 实例与原型 当读取实例的属性时,如果找不到,就会查找与对象关联的原型中的属性,如果还查不到,就去找原型的原型,一直找到最顶层为止。 如下: function Person() { } Person.prototype.name = 'name'; var person = new Person(); person.name = 'name of this person'; console.log(person.name) // name of this person delete person.name; console.log(person.name) // name 在这个例子中,我们设置了person的name属性,所以我们可以读取到为'name of this person',当我们删除了person的name属性时,读取person.name,从person中找不到就会从person的原型也就是person.__proto__ == Person.prototype中查找,幸运的是我们找到了为'name',但是万一还没有找到呢?原型的原型又是什么呢? var obj = new Object(); obj.name = 'name' console.log(obj.name) // name Object.prototype的原型呢,就是null(无中生有) ![关系图2](proto2.png) <file_sep>/SUMMARY.md # Summary * [Introduction](README.md) * [JavaScript基础](javascriptji-chu.md) * [1.函数的特性](1.md) * [1.1函数是一等公民](javascript/1.1.md) * [1.2函数是第一型对象](javascript/1.2.md) * [1.3事件轮询机制](javascript/1.3.md) * [1.4函数的回调机制](javascript/1.4.md) * 2.函数的调用 * [2.1形参和实参](javascript/2.1.md) * [2.2arguments与this](javascript/2.2.md) * [2.3函数的调用模式](javascript/2.3.md) * [2.4call/apply的用法](javascript/2.4.md) * 3.函数递归 * [3.1函数递归的概念](javascript/3.1.md) * [3.2递归函数自引用的方式](javascript/3.2.md) * 4.函数重载 * [4.1函数可以缓存什么](javascript/4.1.md) * [4.2函数缓存的利弊](javascript/4.2.md) * 5.函数重载 * [5.1函数重载的意义](javascript/5.1.md) * [5.2函数重载的实现方式](javascript/5.2.md) * 6.闭包 * [6.1什么是闭包](javascript/6.1.md) * [6.2闭包应用](javascript/6.2.md) * [6.3闭包的作用](javascript/6.3.md) * 7.apply和arguments应用 * [7.1apply取数组中的最大](javascript/7.1.md) * [7.2利用arguments切片](javascript/7.2.md) * 8.javascript高阶函数和纯函数 * [8.1js纯函数](javascript/8.1.md) * [8.2js高阶函数](javascript/8.2.md) * 9.js中间件和对象 * [9.1中间件](javascript/js/9.1.md) * [9.2js对象属性](javascript/js/9.2.md) * 10.《编写可维护的javascript》读书笔记 * [9.JS\_Style\_Notes](javascript/9.md) * [11.Deferred与Promise](javascript/11.md) * 12.神奇的Object.defineProperty * [12.1Object.defineProperty语法](javascript/12.1.md) * 13.JSON浅谈 * [13.1JSON简介](javascript/13json/13.1.md) * [13.2JSON对象](javascript/13json/13.2.md) * [13.3JSON的解析](javascript/13json/13.3.md) * [13.4JSON的序列化](javascript/13json/13.4.md) <file_sep>/express/mock/README.md # learn-express-mock 前端学习 ### 根目录先运行npm init,然后运行DEBUG=mock & npm start【windows用:set DEBUG=mock & npm start】 ### 目录结构 bin public node_modules等和express的目录结构一致 mock-test.html是我用来测试是否可以通过get和post请求数据<file_sep>/mongodb-koa/pages/test.js import React, { Component, PropTypes } from 'react' import ReactDOM from 'react-dom' import Axios from 'axios' class Test extends Component { constructor (props) { super(props); this.state = { showTooltip: false // 控制 tooltip 的显示隐藏 } } componentDidMount () { } getAllUser () { Axios.get({}) } render () { <div class='test_koa'> 11111111 </div> } }<file_sep>/javascript/11.md ## Deferred 和 Promise 目的:为了解决冗长的回调造成的不便 状态:等到->完成 等待->失败 Deferred :等待->成功 Deferred.resolve() 触发.done(function(){}) ​ 等待->失败 Deferred.reject() 触发.fail(function(){}) Promise: 等待->成功 Promise.resolve() 触发.then(function(){}) ​ 等待->失败 Promise.reject() 触发.then(null,function(){})或者.catch(function(){}) ### jQuery deferred deferred对象就是jQuery的回调函数解决方案 $.ajax()操作完成后,如果使用的是低于1.5.0版本的jQuery,返回的是XHR对象,你没法进行链式操作;如果高于1.5.0版本,返回的是deferred对象,可以进行链式操作。 ## 原模式 $.ajax({ ... success:function () { }, error:function(){ } }) ## deferred模式 $.ajax({ ... }) .done(function () { ​ }) .fail(function () { ​ }) ## 常用方法:.then(function(),function()) .done() .fail() .always() $.when($ajax(),}) 多个事件指定一个回调函数 $.when($.ajax("test1.html"), $.ajax("test2.html"))   .done(function(){ alert("哈哈,成功了!"); })   .fail(function(){ alert("出错啦!"); }); 先执行两个操作$.ajax("test1.html")和$.ajax("test2.html"),如果都成功了,就运行done()指定的回调函数;如果有一个失败或都失败了,就执行fail()指定的回调函数 ## 补充:非ajax的deferred封装 function show() { var def = $.Deferred(); setTimeout(function () { //console.log("输出展示内容"); def.resolve("输出展示内容"); }, 3000) return def.promise(); } $.when(show()).done(function (args) { console.log("内容:" + args); }) ### ES6 Promise promise/A+规范:原生js解决回调的解决方案 ### 状态改变:Promise.resolve() Promise.reject() ## 常用方法:.then() .catch() .all([]) .race([]) ## then的返回值 1、返回另一个promise; 2、返回一个同步值(或者undefined); 3、抛出一个同步错误。 ### catch()并不和then(null,…)一摸一样 somePromise().catch(function (err) { // handle error }); somePromise().then(null, function (err) { // handle error }); 当你使用then(resolveHandler,rejectHandler)格式,如果resolveHandler自己抛出一个错误rejectHandler并不能捕获。 基于这个原因,我已经形成了自己的一个习惯,永远不要对then()使用第二个参数,并总是优先使用catch() ## promise库 兼容性方面 高版本的主流浏览器都有内置的Promise对象,因为这个ES6的规范,较低版本的浏览器可以通过引入第三方的库来实现,例如bulebird。在nodejs中也无需npm模块,只需require(“Promise”) http://bluebirdjs.com/docs/getting-started.html ## 参考文档 http://www.ruanyifeng.com/blog/2011/08/a_detailed_explanation_of_jquery_deferred_object.html https://segmentfault.com/a/1190000002452115 http://web.jobbole.com/82601/ https://segmentfault.com/q/1010000006115125/a-1020000006115341 http://blog.csdn.net/mingzznet/article/details/53146471 <file_sep>/javascript/4.1.md #### 函数可以缓存什么 - 1.函数的计算结果 - 2.dom元素 #### 斐波拉契数列加入缓存 function Fibonacci(n) { if(n<=2){ return 1; }else{ return Fibonacci(n-2)+Fibonacci(n-1); } } console.time('Fibonacci43'); for(var i=3;i<=43;i++){ console.log('第'+i+'项的值为',Fibonacci(i)) } console.timeEnd('Fibonacci43'); var FibonacciCache=function cache(n) { if(n<=2){ return 1; }else{ if(cache[n]){ return cache[n]; }else{ var result=cache(n-2)+cache(n-1); cache[n]=result; return result; } } } console.time('Fibonacci43'); for(var i=3;i<=43;i++){ console.log('第'+i+'项的值为',FibonacciCache(i)) } console.timeEnd('Fibonacci43'); <file_sep>/express/README.md # learn-express 前端学习 ### 1 mock是自己运用express搭建的一个本地mock数据环境,用于前后端开发的时候,前端mock数据。 ### 2 mytest是自己用nunjuck替换express默认的jade模板。<file_sep>/vue-webpack/vue-webpack/README.md # vue-webpack > A Vue.js project ## Build Setup ``` bash # install dependencies npm install # serve with hot reload at localhost:8080 npm run dev # build for production with minification npm run build # build for production and view the bundle analyzer report npm run build --report # run unit tests npm run unit # run e2e tests npm run e2e # run all tests npm test ``` ## 目录结构 ├── build/ # 此目录包含开发服务器和生产webpack构建的实际配置。通常你不需要触摸这些文件,除非你想自定义Webpack加载器,在这种情况下你应该看看build/webpack.base.conf.js。 │ └── ... ├── config/ │ ├── index.js # 这是显示构建设置的一些最常见配置选项的主配置文件。 │ └── ... ├── src/ # 这是大多数应用程序代码都存在的地方。 │ ├── main.js # app entry file │ ├── App.vue # main app component │ ├── components/ # ui components │ │ └── ... │ └── assets/ # module assets (processed by webpack) │ └── ... ├── static/ # 此目录是您不想使用Webpack处理的静态资产的转义填充。它们将被直接复制到生成webpack构建的资产的同一目录中。 ├── test/ │ └── unit/ # 包含单元测试相关文件。 │ │ ├── specs/ # │ │ ├── index.js # test build entry file │ │ └── karma.conf.js # test runner config file │ └── e2e/ # 包含e2e测试相关文件 │ │ ├── specs/ # test spec files │ │ ├── custom-assertions/ # custom assertions for e2e tests │ │ ├── runner.js # test runner script │ │ └── nightwatch.conf.js # test runner config file ├── .babelrc # babel config ├── .editorconfig.js # editor config ├── .eslintrc.js # eslint config ├── index.html # 这是我们的单页应用程序的模板 index.html。在开发和构建期间,Webpack将生成资产,并且这些生成的资产的URL将自动注入此模板以呈现最终的HTML。 └── package.json # NPM包元文件,其中包含所有构建依赖项和构建命令。
6eb3074b3f46720f7cd80c480c94d25e2611d9cf
[ "Markdown", "JavaScript" ]
58
Markdown
Chant-Lee/learn
c8d0bd45a1b163625a55e7225d64d090e7c6b332
1a465cc4417abcb320de6fecbd1f74aca8162603
refs/heads/master
<repo_name>Tommas10/Merge-two-Microsoft-Word-docx-file-into-one-docx-file-with-Python-script<file_sep>/mergetwodocx.py #!/usr/bin/env python # This is small automation to merge two Microsoft Word docx file with Python. # Created by <NAME>. #python-docx is a Python library for creating and updating Microsoft Word (.docx) files. from docx import Document # Merge Microsoft Word files source. t1 = Document("/Users/TommasHuang/Documents/test1.docx") # # Merge Microsoft Word files distance. t2 = Document("/Users/TommasHuang/Documents/test2.docx") for p in t2.paragraphs: # Here is the new paragraph, followed by the style is the style t1.add_paragraph(p.text,p.style) # Merge Microsoft Word two files save new file t1.save("test1-new.docx")
0c2964409eb9bf3521276832f7c01bd4faf1add4
[ "Python" ]
1
Python
Tommas10/Merge-two-Microsoft-Word-docx-file-into-one-docx-file-with-Python-script
c90b89d8217c532633e7026feec62dcdcaee7fcc
78dd88ac39355b2f7cbcedee36e4f0d8b41db8c7
refs/heads/master
<repo_name>chuan1900/algorithm_practice<file_sep>/math_tag/com/countOne.cpp #include<iostream> using namespace std; int count2(int n); int main(void) { int x = 13; cout<<count2(x)<<endl; return 0; } //解法二: int count2(int n) { int count = 0;//统计变量 int factor = 1;//分解因子 int lower = 0;//当前处理位的所有低位 int higher = 0;//当前处理位的所有高位 int curr =0;//当前处理位 while(n/factor != 0) { lower = n - n/factor*factor;//求得低位 curr = (n/factor)%10;//求当前位 higher = n/(factor*10);//求高位 switch(curr) { case 0: count += higher * factor; break; case 1: count += higher * factor + lower + 1; break; default: count += (higher+1)*factor; } factor *= 10; } return count; }<file_sep>/binaryTree/com/first_common_ancestor.java /* * First common ancestor (not necessarily BST) * * With link to parent * */ TreeNode commonAncestor(TreeNode p, Treenode q){ int delta = depth(p) - depth(q); TreeNode shallow = delta > 0 ? q : p; TreeNode deep = delta > 0 ? p : q; deep = goUpBy(deep, delta); //move deeper node up //Find the intersection while(shallow != deep && shallow != null && deep != null){ shallow = shallow.parent; deep = deep.parent; } return shallow == null || deep == null ? null : shallow; } TreeNode goUpBy(TreeNode node, int delta){ while(delta > 0 && node != null){ node = node.parent; delta--; } return node; } int depth(TreeNode node){ int depth = 0; while(node != null){ node = node.parent; depth++; } return node; }<file_sep>/sort_algorithm/com/QuickSort.java /* *input[]: 2,3,7,4,1,9 *after quick sort: input[] → 1,2,3,4,7,9 */ class QuickSort { private int input[]; private int length; public void sort(input[] numbers){ if(numbers.length == 0 || numbers == null){ return; } this.input = numbers; this.length = numbers.length; quickSort(0, length); } private void quickSort(int low, int high){ int i = low; int j = high; int pivot = input[low + (high - low)/2]; /* *In each iteration, we identify a number in left side of input[] that is greater than pivot *and a number in right side that is less than pivot *then swap the above two */ while(i <= j){ while(input[i] < pivot) i++; while(input[j] > pivot) j--; if(i <= j){ swap(i, j); i++; j-- ; } } //call quickSort() recursively if(low < j){ quickSort(low, j); } if(i < high){ quickSort(i, high); } } private void swap(int i, int j){ int temp; temp = input[i]; input[i] = input[j]; input[j] = temp; } } /* *Insertion Sort */ public void insertionSort(int[] nums){ for(int i = 0; i < nums.length; i++){ //int curr = nums[i]; int j = i; while(j > 0 && nums[j - 1] > nums[j]){ swap(nums, nums[j-1], nums[j]); j--; } } } <file_sep>/array_tag/com/pairOfSameSum.java How to find all pairs in array of integers whose sum is equal to given number? Don’t forget to ask questions: 1. Does array contains only positive numbers or negative? 2. What is some pairs repeated like twice, should I print it every time? 3. Do we need to print only distinct pair? → (3, 3) for sum is 6 ok? 4. How large is the array? public class Solution{ /* * Brute-force * loop through the array * [1,4,2,3,6,5] sum = 3 * output should be: → (1, 2) * time complexity: O(n^2) */ public void printPairs(int sum, int[] array){ for(int i = 0; i < array.length; i++){ int first = array[i]; for(int j = i+1; j < array; j++){ int second = array[j]; if(first + second == sum){ System.out.println(“(%d, %d)”, first, second); } } } } /* * Use Hashtable(set) * time complexity: O(n) * space complexity: O(n) */ public void printPairsSet(int sum, int[] array){ if(array.length < 2) return; Set<Integer> set = new HashSet<>(); for(int val : array){ int sub = sum - val; if(!set.contains(sub)){ set.add(sub); }else{ System.out.println(“%d, %d”, val, sub); } } } } <file_sep>/array_tag/com/MediumLevel.java package array_tag.com; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class MediumLevel { public static void main(String[] args) { // TODO Auto-generated method stub int[] nums = {-3,3,4}; //System.out.println(nums.toString()); MediumLevel ml = new MediumLevel(); //int[] ret = ml.twoSum(nums,0); //System.out.println(Arrays.toString(ret)); int[][] matrix = {{1, 3, 5, 7},{10, 11, 16, 20},{23, 30, 34, 50}}; System.out.println(ml.searchMatrix(matrix, 11)); } /* * 39. Combination Sum * * Backtrack Algorithm * * 40. Conbination Sum II, slightly difference */ public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> result = new ArrayList<>(); //List<Integer> tempList = new ArrayList<>(); //sort为下面for节约计算 Arrays.sort(candidates); //---------------> 必须是new ArrayList<>(),不然只是原来的副本,结果是错误的 backtrack(result, new ArrayList<Integer>(), candidates, target, 0); return result; } public void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] candidates, int target,int start) { if(target < 0) return; // ---------------->构造器:用一个tempList对象来构造,并将该集合的元素添加到ArrayList else if(target == 0) result.add(new ArrayList<Integer>(tempList)); else{ for(int i = start; i < candidates.length; i++){ tempList.add(candidates[i]); // not i + 1 because we can reuse same elements backtrack(result, tempList, candidates, target-candidates[i], i); tempList.remove(tempList.size() - 1); } } } /* * 40. Combination Sum II, without duplicate of the same number * * This can explain the "skip duplicates" part : !!!!!!!!IMPORTANT!!!!!!!!!! * The revursive component tries the elements after the current one and also tries duplicate elements. * So we can get correct answer for cases like [1 1] 2. * The iterative component checks duplicate combinations and skip it if it is. * So we can get correct answer for cases like [1 1 1] 2. * */ public List<List<Integer>> combinationSum2(int[] nums, int target) { List<List<Integer>> list = new ArrayList<>(); Arrays.sort(nums); backtrack1(list, new ArrayList<Integer>(), nums, target, 0); return list; } private void backtrack1(List<List<Integer>> list, List<Integer> tempList, int [] nums, int remain, int start){ if(remain < 0) return; else if(remain == 0) list.add(new ArrayList<>(tempList)); else{ for(int i = start; i < nums.length; i++){ // iterative component //why??? It just said no duplication of each number??? if(i > start && nums[i] == nums[i-1]) continue; // skip duplicates tempList.add(nums[i]); backtrack(list, tempList, nums, remain - nums[i], i + 1); // recursive componenet tempList.remove(tempList.size() - 1); } } } /* * 216. Combination Sum III */ public class Solution { public List<List<Integer>> combinationSum3(int k, int n) { List<List<Integer>> result = new ArrayList<>(); List<Integer> tempList = new ArrayList<>(); backtrack(result, tempList, k, n, 1); return result; } public void backtrack(List<List<Integer>> result, List<Integer> tempList, int k, int n, int start){ //To make this faster, you can quit the for loop early and avoid unnecessary work. if(tempList.size() > k) return; if(tempList.size() == k && n == 0) result.add(new ArrayList<Integer>(tempList)); for(int i = start; i <= 9; i++){ tempList.add(i); //将i 加入tempList backtrack(result, tempList, k, n - i, i + 1); //遍历i的后代(即:之后的数字),寻找可行的解,类似于深度优先 tempList.remove(tempList.size() - 1); // 没有可行的解路径,则删掉i重来 } } } /* * 78. Subsets I * * Backtrack algorithm again. Like DFS and use recursion * * 找到所有的XXX,这种题目都可以向DP和backtracking的方向去想,这道题和38, * Combination Sum的解法基本是一样的,不同的是这道题目让返回所有的子集,所以在backtrack中不用进行检测, * 直接将当前的subset加入subsets中即可。另外这道题目也反映出了无剪枝的backtracking算法的运行情况,大约会调用2 ^ n次 */ public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> result = new ArrayList<List<Integer>>(); List<Integer> subset = new ArrayList<>(); backtrack(nums, 0 , result, subset); return result; } //------------------------------------------->传参避免了使用全局变量 //怎样保证subsets不重复??? private void backtrack(int[] nums, int start, List<List<Integer>> result, List<Integer> subset){ result.add(new ArrayList<>(subset)); for(int i = start; i < nums.length; i++){ subset.add(nums[i]); backtrack(nums,i + 1, result, subset); subset.remove(subset.size() - 1); } } /* * 289. Game of Life * * All about two dimensional array and Logic ~~~ * * 代码全是参考的 */ // 0: dead -> dead // 1: live -> live // 2: live -> dead // 3: dead -> live public void gameOfLife(int[][] board) { int [] di = {-1, -1, -1, 0, 0, 1, 1, 1}; int [] dj = {-1, 0, 1, -1, 1, -1, 0, 1}; int row = board.length, col = row != 0 ? board[0].length : 0; for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ int live = 0; //firstly, 判断边界 for(int k = 0; k < 8; k++){ int ii = i + di[k], jj = j + dj[k]; if(ii < 0 || ii >= row || jj < 0 || jj >= col) continue; if(board[ii][jj] == 2 || board[ii][jj] == 1) live++; } if(board[i][j] == 1 && (live < 2 || live > 3)) board[i][j] = 2; if(board[i][j] == 0 && live == 3) board[i][j] = 3; } } for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ board[i][j] %= 2; } } } /* * 120. Triangle * * DP DP DP DP DP DP DP DP DP DP DP DP * * 找到状态转移方程 bottom-up. 对于当前行中的每一个元素,只需要找到上一行中和当前元素相邻的2个元素的最小值, * 然后把这儿最小值加上当前元素饼更新sum_vec数组就可以了。不断进行下去,直到最后一行为止。这个过程可以看做一个很简单的动态规划。 * */ //calculate in-place public int minimumTotal(List<List<Integer>> triangle) { for(int i = triangle.size() - 2; i >= 0; i--){ for(int j = 0; j <=i; j++){ int sum =triangle.get(i).get(j) + Math.min(triangle.get(i+1).get(j), triangle.get(i+1).get(j+1)); triangle.get(i).set(j, sum); } } return triangle.get(0).get(0); } //update an extra one dimensional array using O(N) space public int minimumTotal1(List<List<Integer>> triangle){ List<Integer> minSum = new ArrayList<>(triangle.get(triangle.size() - 1)); for(int i = triangle.size() - 2; i >= 0; i--){ for(int j = 0; j <=i; j++){ int sum = triangle.get(i).get(j) + Math.min(minSum.get(j),minSum.get(j + 1)); minSum.set(j, sum); } } return minSum.get(0); } /* * 11. Container With Most Water * * -------------> "Two pointers" * * The idea is : to compute area, we need to take min(height[i],height[j]) as our height. * Thus if height[i]<height[j], then the expression min(height[i],height[j]) will always * lead to at maximum height[i] for all other j(i being fixed), hence no point checking them. * Similarly when height[i]>height[j] then all the other i's can be ignored for that particular j. */ public int maxArea(int[] height) { int left = 0, right = height.length - 1; int water = (right - left) * Math.min(height[left], height[right]); while(left < right){ if(height[left] < height[right]) left++; else right--; water = Math.max(water, (right - left) * Math.min(height[left], height[right])); } return water; } /* * 122. Best Time to Buy and Sell Stock II * * Greedy: Just like eating shit after seeing the answer */ public int maxProfit(int[] prices) { int total = 0; for (int i=0; i< prices.length-1; i++) { if (prices[i+1]>prices[i]) total += prices[i+1]-prices[i]; } return total; } /* * 189. Rotate Array */ public void rotate(int[] nums, int k) { int size = nums.length; reverse(nums, 0, k%size - 1); reverse(nums, k%size, size - 1); reverse(nums, 0, size - 1); } public void reverse(int[] nums, int start, int end){ while(start < end){ int temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; } } /* * 35. Search Insert Position * * Binary Search */ public int searchInsert(int[] nums, int target) { int low = 0, high = nums.length - 1, middle = 0; while(low <= high){ middle = low + ((high - low) >> 1); if(target == nums[middle]) return middle; else{ if(target > nums[middle]) high = middle - 1; else low = middle + 1; } } //if(high <= middle) return high+1; //else return low-1; return low; } /* * 48. Rotate Image * * * clockwise rotate * first reverse up to down, then swap the symmetry * 1 2 3 7 8 9 7 4 1 * 4 5 6 => 4 5 6 => 8 5 2 * 7 8 9 1 2 3 9 6 3 */ /* * anticlockwise rotate * first reverse left to right, then swap the symmetry * 1 2 3 3 2 1 3 6 9 * 4 5 6 => 6 5 4 => 2 5 8 * 7 8 9 9 8 7 1 4 7 */ public void rotate(int[][] matrix) { int n = matrix.length; for(int i = 0; i < n; i++){ //pay attention to the index j for(int j = i; j < n; j++){ int temp = 0; temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } // this is to reverse left to right for(int i = 0; i < n; i++){ //pay attention to the index j for(int j = 0; j < n/2; j++){ int temp = 0; temp = matrix[i][j]; matrix[i][j] = matrix[i][n-1-j]; matrix[i][n-1-j] = temp; } } } /* * 162. Find Peak Element * * Binary Search: * Consider that each local maximum is one valid peak. * My solution is to find one local maximum with binary search. * Binary search satisfies the O(logn) computational complexity. */ public int findPeakElement(int[] nums) { int low = 0, high = nums.length - 1; while(low < high){ int middle1 = low + (high - low)/2; int middle2 = middle1 + 1; if(nums[middle1] < nums[middle2]){ low = middle2; }else{ high = middle1; } } return low; } //Sequential search public int findPeakElement1(int[] nums){ for(int i = 1; i < nums.length; i++){ if(nums[i] < nums[i - 1]) return i-1; } return nums.length - 1; } /* * 229. Majority Element II * * 回头再细研究!!!~~~ */ public List<Integer> majorityElement(int[] nums) { //there should be at most 2 different elements in nums more than n/3 //so we can find at most 2 elements based on Boyer-Moore Majority Vote algo List<Integer> res = new ArrayList<Integer>(); if(nums.length==0) return res; int count1=0,count2=0,m1=0,m2=0; for(int n : nums){ if(m1==n) count1++; else if(m2==n) count2++; else if(count1==0) { m1=n; count1=1; } else if(count2==0) { m2=n; count2=1; } else{ count1--; count2--; } } count1=0; count2=0; //count the number for the 2 elements for(int n:nums){ if(n==m1) count1++; else if(n==m2) count2++; } //if those appear more than n/3 if(count1>nums.length/3) res.add(m1); if(count2>nums.length/3) res.add(m2); return res; } /* * 167. Two Sum II - Input array is sorted * * Without HashMap, just have two pointers or binary search. Much more faster!!! */ public int[] twoSum(int[] nums, int target) { Map<Integer,Integer> map = new HashMap<>(); int[] result = new int[2]; for(int i = 0; i < nums.length; i++){ //if(nums[i] > target) break; int subsum = target - nums[i]; if(map.containsKey(subsum)){ System.out.println("i am here"); result[0] = i + 1; result[1] = map.get(subsum) + 1; System.out.println(result[0]); System.out.println(result[1]); break; }else{ System.out.println("i am here 1"); map.put(nums[i], i); } } return result; } /* * 33. Search in Rotated Sorted Array * * Similar problem: 153. Find Minimum in Rotated Sorted Array * * Binary Search * * The idea is that when rotating the array, there must be one half of the array that is still in sorted order. *For example, 6 7 1 2 3 4 5, the order is disrupted from the point between 7 and 1. So when doing binary search, * we can make a judgement that which part is ordered and whether the target is in that range, if yes, continue the * search in that half, if not continue in the other half. */ public int search(int[] nums, int target) { int low = 0, high = nums.length - 1; while(low < high){ int middle = low + (high - low)/2; if(target == nums[middle]) return middle; if(nums[middle] >= nums[low]){//the left part of the array is well sorted //Was the targer in the left part? if(target >= nums[low] && target <= nums[middle]) high = middle - 1; else low = middle + 1; } if(nums[middle] <= nums[high]){//the right part of the array is well sorted //Was the target in the right part? //之所以写<= >= 是为了考虑nums[middle] == nums[high]的情况 if(target >= nums[middle] && target <= nums[high]) low = middle + 1; else high = middle - 1; } } //ATTENTION!!!!!!!!!!!!! while(low < high) ===> 存在 返回low return nums[low] == target ? low :-1; } /* *153. Find Minimum in Rotated Sorted Array * * Like the question above * * Binary Search */ public int findMin(int[] nums) { if(nums.length == 1) return nums[0]; int low = 0, high = nums.length - 1; while(low < high){ int middle = low + (high - low)/2; if(nums[low] < nums[high]) return nums[low]; //if(nums[middle] < nums[high]) high = middle; if(nums[middle] >= nums[low]) low = middle + 1; else high = middle; } return nums[low]; } /* * 74. Search a 2D Matrix */ public boolean searchMatrix(int[][] matrix, int target) { int m = matrix.length, n = matrix[0].length; int aimRow = 0, left = 0, right = n - 1; int flag = 0; for(int i = 0; i < m; i++){ if(matrix[i][0] <= target && matrix[i][n-1] >= target){ aimRow = i; System.out.println("aimRow: "+aimRow); flag = 1; break; } } if(flag == 0) return false; while(left < right){ int mid = left + (right - left)/2; if(matrix[aimRow][mid] == target) return true; if(matrix[aimRow][mid] > target) right = mid - 1; if(matrix[aimRow][mid] < target) left = mid + 1; } return matrix[aimRow][left] == target ? true : false; } //Another method: just treat it as one-dimensional sorted array public boolean searchMatrix2(int[][] matrix, int target) { int row_num = matrix.length; int col_num = matrix[0].length; int begin = 0, end = row_num * col_num - 1; while(begin <= end){ int mid = (begin + end) / 2; //the mid value is the key point to solve this problem int mid_value = matrix[mid/col_num][mid%col_num]; if( mid_value == target){ return true; }else if(mid_value < target){ //Should move a bit further, otherwise dead loop. begin = mid+1; }else{ end = mid-1; } } return false; } /* * 34. Search for a Range * * Binary Search * * Given a sorted array of integers, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. * * Something tricky of the two binary searches, especially the second => int mid = (left + right + 1)/2; */ public int[] searchRange(int[] nums, int target) { int left = 0, right = nums.length -1; int[] result = {-1, -1}; //check the left bound while(left < right){ int mid = left + (right - left)/2; if(nums[mid] < target) left = mid + 1; if(nums[mid] >= target) right = mid; } if(nums[left] != target) return result; result[0] = left; //check the right bound right = nums.length - 1; while(left < right){ int mid = (left + right + 1)/2; if(nums[mid] > target) right = mid - 1; if(nums[mid] <= target) left = mid; } result[1] = right; return result; } /* * 55. Jump Game * * Greedy * * I just iterate and update the maximal index that I can reach * */ public boolean canJump(int[] nums) { int size = nums.length, reach = 0; for(int i = 0; i < size; i++){ if(reach < i) return false; reach = Math.max(nums[i] + i, reach);//greedy } return true; } //think reversely from the above answer public boolean canJump1(int[] nums) { int back = nums.length - 1, size = nums.length,i; for(i = size - 2; i >= 0; i--){ if(nums[i] + i >= back) back = i; } return i == 0; } /* * 45. Jump Game II * * Greedy */ public int jump(int[] nums) { int curStart = 0, curEnd = 0, reach = 0, jump = 0; //pay attention to the index bound for(int i = 0; i < nums.length - 1; i++){ reach = Math.max(nums[i] + i, reach); if(i == curEnd){ curEnd = reach; jump++; } } return jump; } } <file_sep>/array_tag/com/array_sample.java /* *contains duplicates * */ public boolean containsNearByDuplicates(int[] nums, int k){ HashMap<Integer, Integer> hm = new HashMap<>(); for(int i = 0; i < nums.length; i++){ if(hm.contansKey(nums[i]) && (i - hm.get(nums[i]) <= k)) return true; hm.put(nums[i], i); } return false; } /* * remove duplicates from sorted array * @return length of the array after removal * * [0,1,1,1,2,3,3,5] --> */ public int removeDuplicates(int[] nums){ int curr = 1; for(int i = 0; i < nums.length; i++){ if(nums[i+1] != nums[i]) nums[curr++] = nums[i+1]; } return curr; } /* * Search in rotated array * Using binary search to settle out the problem * input: [6,7,1,2,3,4,5] * @param * @param * @return index of the target */ public int search(int[] nums, int target){ int low = 0, high = nums.length - 1; while(low < high){ int mid = low + (high - low)/2; if(nums[mid] == target) return mid; if(nums[mid] >= nums[low]){// left half of the array is well sorted if(target >= nums[low] && target < nums[mid]) high = mid - 1; else low = mid + 1; } if(nums[mid] <= nums[low]){//right half of the array is well sorted if(target > nums[mid] && target <= nums[high]) low = mid + 1; else high = mid - 1; } } return arr[low] == target ? low : -1; } /* * contains duplicate * Using hashmap * @param k * @param * */ public boolean containsNearByDuplicate(int[] nums, int k){ HashMap<Integer, Integer> hm = new HashMap<>(); for(int i = 0; i < nums.length; i++){ if(hm.containsKey(nums[i]) && (hm.get(nums[i]) - i) <= k) return true; else hm.put(nums[i],i); } return false; } <file_sep>/sort_algorithm/com/SortingAlgorithm.java package sort_algorithm.com; import java.util.Arrays; public class SortingAlgorithm { public static void main(String[] args) { // TODO Auto-generated method stub SortingAlgorithm sa = new SortingAlgorithm(); int[] A ={9,2,4,3,7,3,8,10}; sa.quickSort(A, 0, 7); System.out.println(Arrays.toString(A)); } /* * Quick sort * * 1. Partition (Divide): choose a pivot (p). array[l....r] Rearrange the (sub)array * so that all other elements in the array * that are less or equal to the pivot are to its left and vice versa. * * 2. Conquer: recursively sorting (also choosing pivot) the sub-arrays array[l...p-1] and array[p+1....r] * * 3. In-place, without any extra space. On average, time complexity is O(n log(n)) */ void quickSort(int[] A, int left, int right){ if(A == null || A.length == 0) return; //Important!!!!!! Recursion 的终止标志!!!!! if(left >= right) return; int pivot = A[left], i = left, j = right; while(i < j){ //find the number that is less than the pivot, move it to the left while(i < j && A[j] >= pivot) j--; if(i < j) A[i++] = A[j]; //find the number that is larger or equal than the pivot, move it to the right while(i < j && A[i] < pivot) i++; if(i < j) A[j--] = A[i]; } A[i] = pivot; quickSort(A, left, i - 1); quickSort(A, i + 1, right); } /* * Heap Sort: Complete binary tree * * If the parent node is stored at index I, the left child can be calculated by 2 * I + 1 * and right child by 2 * I + 2. * * For max heap: * 1. Build a max heap * 2. At this point, the root is the largest element. swap the root with the last element and reduce * the size of the heap by one. Heapify the root the heap * 3. Repeat the above two step until there is no more than one element in the heap (heap size steps). * * Heap sort is an in-place algorithm. * Time complexity of heapify is O(Logn). Time complexity of createAndBuildHeap() is O(n) and * overall time complexity of Heap Sort is O(nLogn). */ //i is the index of the array where we want to heapify from, in heap sort typically i is the root // n = subarray.length is the size of the heap //终止条件有点让晕啊啊啊!!!! void heapify(int[] A, int n, int i){ int largest = i; int lc = 2*i + 1, rc = 2*i + 2; //if left child > parent if(lc < n && A[lc] > A[i]) largest = lc; //if right child > parent if(rc < n && A[rc] > A[i]) largest = rc; //if the above situations happen, swap parent and its larger child if(largest != i){ int temp = A[i]; A[i] = A[largest]; A[largest] = temp; //heapify the subtree top-down recursively //~~~~~~~~~~~~~~until largest is i~~~~~~~~~~~~~ heapify(A, n, largest); } } //Heap sort void heapSort(int[] A){ int len = A.length; //build heap //starting from the none leaf node, the leaf nodes can be treated as already heapified for(int i = len/2 - 1; i >= 0; i--) heapify(A, len, i); //swap and sort one by one in the array for(int i = len-1; i > 0; i--){ int temp = A[0]; A[0] = A[i]; A[i] = temp; heapify(A, i, 0); } } } <file_sep>/sort_algorithm/com/mergeSort.java void mergeSort(int[] array, int[] helper, int low, int high){ if(low < high){ int mid = (low + high)/2; mergeSort(array, helper, low, mid); //sort the left half mergeSore(array, helper, mid + 1, high); // sort the right half merge(array, helper, low, mid, high); } } void merge(int[] array, int[] helper, int low, int mid, int high){ // copy all the elements from array into helper for(int i; i < array.lengh; i++){ helper[i] = array[i]; } int helperLeft = low; int helperRighe = mid + 1; int curr = low; // Iterate through helper array while(helperLeft <= mid && helperRight <= high){ if(helper[helperLeft] <= helper[helpRight]){ array[curr] = helper[helperLeft]; helperLeft++; }else{ array[curr] = helper[helperRighe]; helperRight; } curr++; } //copy the remaining element of the left half into target array int remain = mid - helperLeft; for(int i = 0; i < remain; i++){ array[i] = helper[i]; } }
ec4e8b9e874b096cd5858946aa034769595705d9
[ "Java", "C++" ]
8
C++
chuan1900/algorithm_practice
3f17d6d9189802bccc03556ce06a8339659f2c69
295d7b226fbd2dce822eb76cee6deea4a7bd3b8e
refs/heads/master
<file_sep>#include <iostream> #include <cstdlib> #include <ctime> #include <string> #include <vector> #include <algorithm> using namespace std; int main() { const int SuitNum = 4; const int FacesNum = 13; int CardNum = 0; string card = ""; int gameMode; bool gameContinue = true; //create arrays for card labels const string suits[] = { "Hearts", "Clubs", "Diamonds", "Spades" }; const string face[] = { "2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace" }; //Create vectors to store the decks in. vector<string> Cards; vector<string> faceValueCards; vector<string> suitTypeCards; //Generate full card deck for (int i = 0; i < SuitNum; i++) { //iterate through suits for (int j = 0; j < FacesNum; j++) {//iterate through faces card = face[j] + " of " + suits[i]; //declare card Cards.push_back(card); // add card to vector CardNum++;// raise card number for every card added to deck } } //Generate the deck for suits only for (int i = 0; i < SuitNum; i++) { card = suits[i]; suitTypeCards.push_back(card); CardNum++; } //Generate the deck for face values only for (int i = 0; i < FacesNum; i++) { card = face[i]; faceValueCards.push_back(card); CardNum++; } //time operator to make sure every time the program is run, it produces different random values srand(time(0)); //Description of game and user input required cout << "Card Guessing Game!" << endl << endl; cout << "Please choose which of the following game modes you would like to play! (Choose number)" << endl << endl; cout << "1. Guess face value only!" << endl << "2. Guess suit type only!" << endl << "3. Guess both face and suit!" << endl << endl; cin >> gameMode; while (gameContinue == true) { if (gameMode == 1) { random_shuffle(faceValueCards.begin(), faceValueCards.end()); int RCard = rand() % 13; string DrawCard = faceValueCards.at(RCard); cout << DrawCard << endl; string faceGuess; cout << "Please choose face value! (Enter 2-10, 'Jack', 'Queen', 'King', or 'Ace')" << endl; cin >> faceGuess; if (faceGuess == DrawCard) { cout << "Congratulations! You picked the correct face value! WINNER!"; //gameContinue = false; } else if (faceGuess != DrawCard) { cout << "Im sorry! You picked the incorrect face value. Please try again!" << endl << endl; } } else if (gameMode == 2) { random_shuffle(suitTypeCards.begin(), suitTypeCards.end()); int RCard = rand() % 4; string DrawCard = suitTypeCards.at(RCard); cout << DrawCard << endl; string suitGuess; cout << "Please choose suit! (Enter 'Hearts', 'Clubs', 'Diamonds', or 'Spades')" << endl; cin >> suitGuess; if (suitGuess == DrawCard) { cout << "Congratulations! You picked the correct face value! WINNER!" << endl; //gameContinue = false; } else if (suitGuess != DrawCard) { cout << "Im sorry! You picked the incorrect suit. Please try again!" << endl << endl; } } else if (gameMode == 3) { random_shuffle(Cards.begin(), Cards.end()); int RCard = rand() % 52; string DrawCard = Cards.at(RCard); cout << DrawCard << endl; string cardGuess; cout << "Please choose face and suit value of card!" << endl << "(Please enter in the following format:"; cout << " '(2-10, Jack, Queen, King, Ace) of (Hearts, Clubs, Diamonds, Spades)'" << endl; cin.ignore(); getline(cin, cardGuess); if (cardGuess == DrawCard) { cout << "Congratulations winner! You picked the correct face and suit, wow how lucky!!" << endl; //gameContinue = false; } else if (cardGuess != DrawCard) { cout << "Im sorry! You picked the wrong card, please try again!" << endl << endl; } } } return 0; }
fd405487889d045e8aab72e48dc910449d1fe7f6
[ "C++" ]
1
C++
kevinfair1/DeckOfCards
f9492f5acc39cf72bcc11e6a36df3912f6019e5f
2f01bb7f25b01451596ea139af05551d423ac350
refs/heads/main
<file_sep>import typing from Options import Choice, Range, Option, Toggle, DefaultOnToggle, DeathLink class Logic(Choice): option_no_glitches = 0 option_minor_glitches = 1 option_overworld_glitches = 2 option_hybrid_major_glitches = 3 option_no_logic = 4 alias_owg = 2 alias_hmg = 3 class Objective(Choice): option_crystals = 0 # option_pendants = 1 option_triforce_pieces = 2 option_pedestal = 3 option_bingo = 4 class Goal(Choice): option_kill_ganon = 0 option_kill_ganon_and_gt_agahnim = 1 option_hand_in = 2 class DungeonItem(Choice): value: int option_original_dungeon = 0 option_own_dungeons = 1 option_own_world = 2 option_any_world = 3 option_different_world = 4 alias_true = 3 alias_false = 0 @property def in_dungeon(self): return self.value in {0, 1} class bigkey_shuffle(DungeonItem): """Big Key Placement""" item_name_group = "Big Keys" displayname = "Big Key Shuffle" class smallkey_shuffle(DungeonItem): """Small Key Placement""" option_universal = 5 item_name_group = "Small Keys" displayname = "Small Key Shuffle" class compass_shuffle(DungeonItem): """Compass Placement""" item_name_group = "Compasses" displayname = "Compass Shuffle" class map_shuffle(DungeonItem): """Map Placement""" item_name_group = "Maps" displayname = "Map Shuffle" class Crystals(Range): range_start = 0 range_end = 7 class CrystalsTower(Crystals): default = 7 class CrystalsGanon(Crystals): default = 7 class TriforcePieces(Range): default = 30 range_start = 1 range_end = 90 class ShopItemSlots(Range): range_start = 0 range_end = 30 class WorldState(Choice): option_standard = 1 option_open = 0 option_inverted = 2 class Bosses(Choice): option_vanilla = 0 option_simple = 1 option_full = 2 option_chaos = 3 option_singularity = 4 class Enemies(Choice): option_vanilla = 0 option_shuffled = 1 option_chaos = 2 class Progressive(Choice): displayname = "Progressive Items" option_off = 0 option_grouped_random = 1 option_on = 2 alias_false = 0 alias_true = 2 default = 2 def want_progressives(self, random): return random.choice([True, False]) if self.value == self.option_grouped_random else bool(self.value) class Swordless(Toggle): """No swords. Curtains in Skull Woods and Agahnim\'s Tower are removed, Agahnim\'s Tower barrier can be destroyed with hammer. Misery Mire and Turtle Rock can be opened without a sword. Hammer damages Ganon. Ether and Bombos Tablet can be activated with Hammer (and Book).""" displayname = "Swordless" class Retro(Toggle): """Zelda-1 like mode. You have to purchase a quiver to shoot arrows using rupees and there are randomly placed take-any caves that contain one Sword and choices of Heart Container/Blue Potion.""" displayname = "Retro" class RestrictBossItem(Toggle): """Don't place dungeon-native items on the dungeon's boss.""" displayname = "Prevent Dungeon Item on Boss" class Hints(DefaultOnToggle): """Put item and entrance placement hints on telepathic tiles and some NPCs. Additionally King Zora and Bottle Merchant say what they're selling.""" displayname = "Hints" class EnemyShuffle(Toggle): """Randomize every enemy spawn. If mode is Standard, Hyrule Castle is left out (may result in visually wrong enemy sprites in that area.)""" displayname = "Enemy Shuffle" class KillableThieves(Toggle): """Makes Thieves killable.""" displayname = "Killable Thieves" class BushShuffle(Toggle): """Randomize chance that a bush contains an enemy as well as which enemy may spawn.""" displayname = "Bush Shuffle" class TileShuffle(Toggle): """Randomize flying tiles floor patterns.""" displayname = "Tile Shuffle" class PotShuffle(Toggle): """Shuffle contents of pots within "supertiles" (item will still be nearby original placement).""" displayname = "Pot Shuffle" class Palette(Choice): option_default = 0 option_good = 1 option_blackout = 2 option_puke = 3 option_classic = 4 option_grayscale = 5 option_negative = 6 option_dizzy = 7 option_sick = 8 class OWPalette(Palette): displayname = "Overworld Palette" class UWPalette(Palette): displayname = "Underworld Palette" class HUDPalette(Palette): displayname = "Menu Palette" class SwordPalette(Palette): displayname = "Sword Palette" class ShieldPalette(Palette): displayname = "Shield Palette" class LinkPalette(Palette): displayname = "Link Palette" class HeartBeep(Choice): displayname = "Heart Beep Rate" option_normal = 0 option_double = 1 option_half = 2 option_quarter = 3 option_off = 4 alias_false = 4 class HeartColor(Choice): displayname = "Heart Color" option_red = 0 option_blue = 1 option_green = 2 option_yellow = 3 class QuickSwap(DefaultOnToggle): displayname = "L/R Quickswapping" class MenuSpeed(Choice): displayname = "Menu Speed" option_normal = 0 option_instant = 1, option_double = 2 option_triple = 3 option_quadruple = 4 option_half = 5 class Music(DefaultOnToggle): displayname = "Play music" class ReduceFlashing(DefaultOnToggle): displayname = "Reduce Screen Flashes" class TriforceHud(Choice): displayname = "Display Method for Triforce Hunt" option_normal = 0 option_hide_goal = 1 option_hide_required = 2 option_hide_both = 3 class BeemizerRange(Range): value: int range_start = 0 range_end = 100 class BeemizerTotalChance(BeemizerRange): """Percentage chance for each junk-fill item (rupees, bombs, arrows) to be replaced with either a bee swarm trap or a single bottle-filling bee.""" default = 0 displayname = "Beemizer Total Chance" class BeemizerTrapChance(BeemizerRange): """Percentage chance for each replaced junk-fill item to be a bee swarm trap; all other replaced items are single bottle-filling bees.""" default = 60 displayname = "Beemizer Trap Chance" alttp_options: typing.Dict[str, type(Option)] = { "crystals_needed_for_gt": CrystalsTower, "crystals_needed_for_ganon": CrystalsGanon, "bigkey_shuffle": bigkey_shuffle, "smallkey_shuffle": smallkey_shuffle, "compass_shuffle": compass_shuffle, "map_shuffle": map_shuffle, "progressive": Progressive, "swordless": Swordless, "retro": Retro, "hints": Hints, "restrict_dungeon_item_on_boss": RestrictBossItem, "pot_shuffle": PotShuffle, "enemy_shuffle": EnemyShuffle, "killable_thieves": KillableThieves, "bush_shuffle": BushShuffle, "shop_item_slots": ShopItemSlots, "tile_shuffle": TileShuffle, "ow_palettes": OWPalette, "uw_palettes": UWPalette, "hud_palettes": HUDPalette, "sword_palettes": SwordPalette, "shield_palettes": ShieldPalette, "link_palettes": LinkPalette, "heartbeep": HeartBeep, "heartcolor": HeartColor, "quickswap": QuickSwap, "menuspeed": MenuSpeed, "music": Music, "reduceflashing": ReduceFlashing, "triforcehud": TriforceHud, "glitch_boots": DefaultOnToggle, "beemizer_total_chance": BeemizerTotalChance, "beemizer_trap_chance": BeemizerTrapChance, "death_link": DeathLink } <file_sep># Factorio Randomizer Setup Guide ## Required Software ##### Players - [Factorio](https://factorio.com) - Needed by Players and Hosts ##### Server Hosts - [Factorio](https://factorio.com) - Needed by Players and Hosts - [Archipelago](https://github.com/ArchipelagoMW/Archipelago/releases) - Needed by Hosts ## Create a Config (.yaml) File ### What is a config file and why do I need one? Your config file contains a set of configuration options which provide the generator with information about how it should generate your game. Each player of a multiworld will provide their own config file. This setup allows each player to enjoy an experience customized for their taste, and different players in the same multiworld can all have different options. ### Where do I get a config file? The [Player Settings](/games/Factorio/player-settings) page on the website allows you to configure your personal settings and export a config file from them. ### Verifying your config file If you would like to validate your config file to make sure it works, you may do so on the [YAML Validator](/mysterycheck) page. ## Connecting to Someone Else's Factorio Game Connecting to someone else's game is the simplest way to play Factorio with Archipelago. It allows multiple people to play in a single world, all contributing to the completion of the seed. 1. Acquire the Archipelago mod for this seed. It should be named `AP_*.zip`, where `*` is the seed number. 2. Copy the mod file into your Factorio `mods` folder, which by default is located at: `C:\Users\YourName\AppData\Roaming\Factorio\mods` 3. Get the server address from the person hosting the game you are joining 4. Launch Factorio 5. Click on "Multiplayer" in the main menu 6. Click on "Connect to address" 7. Enter the address into this box 8. Click "Connect" ## Prepare to Host Your Own Factorio Game ### Defining Some Terms In Archipelago, multiple Factorio worlds may be played simultaneously. Each of these worlds must be hosted by a Factorio server, which is connected to the Archipelago Server via middleware. This guide uses the following terms to refer to the software: - **Factorio Client** - The Factorio instance which will be used to play the game. - **Factorio Server** - The Factorio instance which will be used to host the Factorio world. Any number of Factorio Clients may connect to this server. - **Archipelago Client** - The middleware software used to connect the Factorio Server to the Archipelago Server. - **Archipelago Server** - The central Archipelago server, which connects all games to each other. ### What a Playable State Looks Like - An Archipelago Server - The generated Factorio Mod, created as a result of running `ArchipelagoGenerate.exe` - One running instance of `ArchipelagoFactorioClient.exe` (the Archipelago Client) per Factorio world - A running modded Factorio Server, which should have been started by the Archipelago Client automatically - A running modded Factorio Client ### Dedicated Server Setup To play Factorio with Archipelago, a dedicated server setup is required. This dedicated Factorio Server must be installed separately from your main Factorio Client installation. The recommended way to install two instances of Factorio on your computer is to download the Factorio installer file directly from [factorio.com](https://factorio.com/download). #### If you purchased Factorio on Steam, GOG, etc. You can register your copy of Factorio on [factorio.com](https://factorio.com/). You will be required to create an account, if you have not done so already. As part of that process, you will be able to enter your Factorio product code. This will allow you to download the game directly from their website. #### Download the Standalone Version It is recommended to download the standalone version of Factorio for use as a dedicated server. Doing so prevents any potential conflicts with your currently-installed version of Factorio. Download the file by clicking on the button appropriate to your operating system, and extract the folder to a convenient location (we recommend C:\Factorio or similar).<br /> <img src="/static/assets/tutorial/factorio/factorio-download.png" /> Next, you should launch your Factorio Server by running `factorio.exe`, which is located at: `bin/x64/factorio.exe`. You will be asked to log-in to your Factorio account using the same credentials you used on Factorio's website. After you have logged in, you may close the game. #### Configure your Archipelago Installation You must modify your `host.yaml` file inside your Archipelago installation directory so that it points to your standalone Factorio executable. Here is an example of the appropriate setup, note the double `\\` are required: ```yaml factorio_options: executable: C:\\factorio\\bin\\x64\\factorio" ``` With all that complete, you are now able to... ## Host Your Own Factorio Game 1. Obtain the Factorio mod for this Archipelago seed. It should be named `AP_*.zip`, where `*` is the seed number. 2. Install the mod into your Factorio Server by copying the zip file into the `mods` folder. 3. Install the mod into your Factorio Client by copying the zip file into the `mods` folder, which is likely located at `C:\Users\YourName\AppData\Roaming\Factorio\mods`. 4. Obtain the Archipelago Server address from the website's host room, or from the server host. 5. Run your Archipelago Client, which is named `ArchilepagoFactorioClient.exe`. This was installed along with Archipelago if you chose to include it during the installation process. 6. Enter `/connect [server-address]` into the input box at the bottom of the Archipelago Client and press "Enter" <br /><img src="/static/assets/tutorial/factorio/connect-to-ap-server.png" /> 7. Launch your Factorio Client 8. Click on "Multiplayer" in the main menu 9. Click on "Connect to address" 10. Enter `localhost` into the server address box 11. Click "Connect" ## Allowing Other People to Join Your Game 1. Ensure your Archipelago Client is running. 2. Ensure port `34197` is forwarded to the computer running the Archipelago Client. 3. Obtain your IP address by visiting [this website](https://whatismyip.com/). 4. Provide your IP address to anyone you want to join your game, and have them follow the steps for "Connecting to Someone Else's Factorio Game" above. ## Troubleshooting In case any problems should occur, the Archipelago Client will create a file `FactorioClient.txt` in the `/logs`. The contents of this file may help you troubleshoot an issue on your own and is vital for requesting help from other people in Archipelago. ## Additional Resources - [Alternate Tutorial by Umenen](https://docs.google.com/document/d/1yZPAaXB-QcetD8FJsmsFrenAHO5V6Y2ctMAyIoT9jS4) - [Factorio Speedrun Guide](https://www.youtube.com/watch?v=ExLrmK1c7tA) - [Factorio Wiki](https://wiki.factorio.com/) <file_sep>import string from .Items import RiskOfRainItem, item_table, item_pool_weights from .Locations import location_table, RiskOfRainLocation, base_location_table from .Rules import set_rules from BaseClasses import Region, Entrance, Item, MultiWorld from .Options import ror2_options from ..AutoWorld import World client_version = 1 class RiskOfRainWorld(World): """ Escape a chaotic alien planet by fighting through hordes of frenzied monsters – with your friends, or on your own. Combine loot in surprising ways and master each character until you become the havoc you feared upon your first crash landing. """ game: str = "Risk of Rain 2" options = ror2_options topology_present = False item_name_to_id = item_table location_name_to_id = location_table data_version = 2 forced_auto_forfeit = True def generate_basic(self): # shortcut for starting_inventory... The start_with_revive option lets you start with a Dio's Best Friend if self.world.start_with_revive[self.player].value: self.world.push_precollected(self.world.create_item("Dio's Best Friend", self.player)) # if presets are enabled generate junk_pool from the selected preset pool_option = self.world.item_weights[self.player].value if self.world.item_pool_presets[self.player].value: # generate chaos weights if the preset is chosen if pool_option == 5: junk_pool = { "Item Scrap, Green": self.world.random.randint(0, 80), "Item Scrap, Red": self.world.random.randint(0, 45), "Item Scrap, Yellow": self.world.random.randint(0, 30), "Item Scrap, White": self.world.random.randint(0, 100), "Common Item": self.world.random.randint(0, 100), "Uncommon Item": self.world.random.randint(0, 70), "Legendary Item": self.world.random.randint(0, 30), "Boss Item": self.world.random.randint(0, 20), "Lunar Item": self.world.random.randint(0, 60), "Equipment": self.world.random.randint(0, 40) } else: junk_pool = item_pool_weights[pool_option].copy() else: # generate junk pool from user created presets junk_pool = { "Item Scrap, Green": self.world.green_scrap[self.player].value, "Item Scrap, Red": self.world.red_scrap[self.player].value, "Item Scrap, Yellow": self.world.yellow_scrap[self.player].value, "Item Scrap, White": self.world.white_scrap[self.player].value, "Common Item": self.world.common_item[self.player].value, "Uncommon Item": self.world.uncommon_item[self.player].value, "Legendary Item": self.world.legendary_item[self.player].value, "Boss Item": self.world.boss_item[self.player].value, "Lunar Item": self.world.lunar_item[self.player].value, "Equipment": self.world.equipment[self.player].value } # remove lunar items from the pool if they're disabled in the yaml unless lunartic is rolled if not self.world.enable_lunar[self.player]: if not pool_option == 4: junk_pool.pop("Lunar Item") # Generate item pool itempool = [] # Add revive items for the player itempool += ["Dio's Best Friend"] * self.world.total_revivals[self.player] # Fill remaining items with randomly generated junk itempool += self.world.random.choices(list(junk_pool.keys()), weights=list(junk_pool.values()), k=self.world.total_locations[self.player] - self.world.total_revivals[self.player]) # Convert itempool into real items itempool = list(map(lambda name: self.create_item(name), itempool)) self.world.itempool += itempool def set_rules(self): set_rules(self.world, self.player) def create_regions(self): create_regions(self.world, self.player) def fill_slot_data(self): return { "itemPickupStep": self.world.item_pickup_step[self.player].value, "seed": "".join(self.world.slot_seeds[self.player].choice(string.digits) for i in range(16)), "totalLocations": self.world.total_locations[self.player].value, "totalRevivals": self.world.total_revivals[self.player].value, "startWithDio": self.world.start_with_revive[self.player].value } def create_item(self, name: str) -> Item: item_id = item_table[name] item = RiskOfRainItem(name, True, item_id, self.player) return item # generate locations based on player setting def create_regions(world, player: int): world.regions += [ create_region(world, player, 'Menu', None, ['Lobby']), create_region(world, player, 'Petrichor V', [location for location in base_location_table] + [f"ItemPickup{i}" for i in range(1, 1 + world.total_locations[player])]) ] world.get_entrance("Lobby", player).connect(world.get_region("Petrichor V", player)) world.get_location("Level One", player).place_locked_item(RiskOfRainItem("Beat Level One", True, None, player)) world.get_location("Level Two", player).place_locked_item(RiskOfRainItem("Beat Level Two", True, None, player)) world.get_location("Level Three", player).place_locked_item(RiskOfRainItem("Beat Level Three", True, None, player)) world.get_location("Level Four", player).place_locked_item(RiskOfRainItem("Beat Level Four", True, None, player)) world.get_location("Level Five", player).place_locked_item(RiskOfRainItem("Beat Level Five", True, None, player)) world.get_location("Victory", player).place_locked_item(RiskOfRainItem("Victory", True, None, player)) def create_region(world: MultiWorld, player: int, name: str, locations=None, exits=None): ret = Region(name, None, name, player) ret.world = world if locations: for location in locations: loc_id = location_table[location] location = RiskOfRainLocation(player, location, loc_id, ret) ret.locations.append(location) if exits: for exit in exits: ret.exits.append(Entrance(player, exit, ret)) return ret <file_sep>import collections from typing import Counter, Optional, Dict, Any, Tuple from flask import render_template from werkzeug.exceptions import abort import datetime from uuid import UUID from worlds.alttp import Items from WebHostLib import app, cache, Room from Utils import restricted_loads from worlds import lookup_any_item_id_to_name, lookup_any_location_id_to_name alttp_icons = { "Blue Shield": r"https://www.zeldadungeon.net/wiki/images/8/85/Fighters-Shield.png", "Red Shield": r"https://www.zeldadungeon.net/wiki/images/5/55/Fire-Shield.png", "Mirror Shield": r"https://www.zeldadungeon.net/wiki/images/8/84/Mirror-Shield.png", "Fighter Sword": r"https://oyster.ignimgs.com/mediawiki/apis.ign.com/the-legend-of-zelda-a-link-to-the-past/4/40/SFighterSword.png?width=1920", "Master Sword": r"https://oyster.ignimgs.com/mediawiki/apis.ign.com/the-legend-of-zelda-a-link-to-the-past/6/65/SMasterSword.png?width=1920", "Tempered Sword": r"https://oyster.ignimgs.com/mediawiki/apis.ign.com/the-legend-of-zelda-a-link-to-the-past/9/92/STemperedSword.png?width=1920", "Golden Sword": r"https://oyster.ignimgs.com/mediawiki/apis.ign.com/the-legend-of-zelda-a-link-to-the-past/2/28/SGoldenSword.png?width=1920", "Bow": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/b/bc/ALttP_Bow_%26_Arrows_Sprite.png?version=5f85a70e6366bf473544ef93b274f74c", "Silver Bow": r"https://oyster.ignimgs.com/mediawiki/apis.ign.com/the-legend-of-zelda-a-link-to-the-past/6/65/Bow.png?width=1920", "Green Mail": r"https://oyster.ignimgs.com/mediawiki/apis.ign.com/the-legend-of-zelda-a-link-to-the-past/c/c9/SGreenTunic.png?width=1920", "Blue Mail": r"https://oyster.ignimgs.com/mediawiki/apis.ign.com/the-legend-of-zelda-a-link-to-the-past/9/98/SBlueTunic.png?width=1920", "Red Mail": r"https://oyster.ignimgs.com/mediawiki/apis.ign.com/the-legend-of-zelda-a-link-to-the-past/7/74/SRedTunic.png?width=1920", "Power Glove": r"https://oyster.ignimgs.com/mediawiki/apis.ign.com/the-legend-of-zelda-a-link-to-the-past/f/f5/SPowerGlove.png?width=1920", "Titan Mitts": r"https://oyster.ignimgs.com/mediawiki/apis.ign.com/the-legend-of-zelda-a-link-to-the-past/c/c1/STitanMitt.png?width=1920", "Progressive Sword": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/c/cc/ALttP_Master_Sword_Sprite.png?version=55869db2a20e157cd3b5c8f556097725", "Pegasus Boots": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/ed/ALttP_Pegasus_Shoes_Sprite.png?version=405f42f97240c9dcd2b71ffc4bebc7f9", "Progressive Glove": r"https://oyster.ignimgs.com/mediawiki/apis.ign.com/the-legend-of-zelda-a-link-to-the-past/c/c1/STitanMitt.png?width=1920", "Flippers": r"https://oyster.ignimgs.com/mediawiki/apis.ign.com/the-legend-of-zelda-a-link-to-the-past/4/4c/ZoraFlippers.png?width=1920", "Moon Pearl": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/6/63/ALttP_Moon_Pearl_Sprite.png?version=d601542d5abcc3e006ee163254bea77e", "Progressive Bow": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/b/bc/ALttP_Bow_%26_Arrows_Sprite.png?version=cfb7648b3714cccc80e2b17b2adf00ed", "Blue Boomerang": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/c/c3/ALttP_Boomerang_Sprite.png?version=96127d163759395eb510b81a556d500e", "Red Boomerang": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/b/b9/ALttP_Magical_Boomerang_Sprite.png?version=47cddce7a07bc3e4c2c10727b491f400", "Hookshot": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/2/24/Hookshot.png?version=c90bc8e07a52e8090377bd6ef854c18b", "Mushroom": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/3/35/ALttP_Mushroom_Sprite.png?version=1f1acb30d71bd96b60a3491e54bbfe59", "Magic Powder": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/e5/ALttP_Magic_Powder_Sprite.png?version=c24e38effbd4f80496d35830ce8ff4ec", "Fire Rod": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/d/d6/FireRod.png?version=6eabc9f24d25697e2c4cd43ddc8207c0", "Ice Rod": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/d/d7/ALttP_Ice_Rod_Sprite.png?version=1f944148223d91cfc6a615c92286c3bc", "Bombos": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/8/8c/ALttP_Bombos_Medallion_Sprite.png?version=f4d6aba47fb69375e090178f0fc33b26", "Ether": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/3/3c/Ether.png?version=34027651a5565fcc5a83189178ab17b5", "Quake": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/5/56/ALttP_Quake_Medallion_Sprite.png?version=efd64d451b1831bd59f7b7d6b61b5879", "Lamp": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/6/63/ALttP_Lantern_Sprite.png?version=e76eaa1ec509c9a5efb2916698d5a4ce", "Hammer": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/d/d1/ALttP_Hammer_Sprite.png?version=e0adec227193818dcaedf587eba34500", "Shovel": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/c/c4/ALttP_Shovel_Sprite.png?version=e73d1ce0115c2c70eaca15b014bd6f05", "Flute": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/d/db/Flute.png?version=ec4982b31c56da2c0c010905c5c60390", "Bug Catching Net": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/5/54/Bug-CatchingNet.png?version=4d40e0ee015b687ff75b333b968d8be6", "Book of Mudora": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/2/22/ALttP_Book_of_Mudora_Sprite.png?version=11e4632bba54f6b9bf921df06ac93744", "Bottle": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/ef/ALttP_Magic_Bottle_Sprite.png?version=fd98ab04db775270cbe79fce0235777b", "Cane of Somaria": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/e1/ALttP_Cane_of_Somaria_Sprite.png?version=8cc1900dfd887890badffc903bb87943", "Cane of Byrna": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/b/bc/ALttP_Cane_of_Byrna_Sprite.png?version=758b607c8cbe2cf1900d42a0b3d0fb54", "Cape": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/1/1c/ALttP_Magic_Cape_Sprite.png?version=6b77f0d609aab0c751307fc124736832", "Magic Mirror": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/e5/ALttP_Magic_Mirror_Sprite.png?version=e035dbc9cbe2a3bd44aa6d047762b0cc", "Triforce": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/4/4e/TriforceALttPTitle.png?version=dc398e1293177581c16303e4f9d12a48", "Small Key": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/f/f1/ALttP_Small_Key_Sprite.png?version=4f35d92842f0de39d969181eea03774e", "Big Key": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/3/33/ALttP_Big_Key_Sprite.png?version=136dfa418ba76c8b4e270f466fc12f4d", "Chest": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/7/73/ALttP_Treasure_Chest_Sprite.png?version=5f530ecd98dcb22251e146e8049c0dda", "Light World": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/e7/ALttP_Soldier_Green_Sprite.png?version=d650d417934cd707a47e496489c268a6", "Dark World": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/9/94/ALttP_Moblin_Sprite.png?version=ebf50e33f4657c377d1606bcc0886ddc", "Hyrule Castle": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/d/d3/ALttP_Ball_and_Chain_Trooper_Sprite.png?version=1768a87c06d29cc8e7ddd80b9fa516be", "Agahnims Tower": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/1/1e/ALttP_Agahnim_Sprite.png?version=365956e61b0c2191eae4eddbe591dab5", "Desert Palace": r"https://www.zeldadungeon.net/wiki/images/2/25/Lanmola-ALTTP-Sprite.png", "Eastern Palace": r"https://www.zeldadungeon.net/wiki/images/d/dc/RedArmosKnight.png", "Tower of Hera": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/3/3c/ALttP_Moldorm_Sprite.png?version=c588257bdc2543468e008a6b30f262a7", "Palace of Darkness": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/ed/ALttP_Helmasaur_King_Sprite.png?version=ab8a4a1cfd91d4fc43466c56cba30022", "Swamp Palace": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/7/73/ALttP_Arrghus_Sprite.png?version=b098be3122e53f751b74f4a5ef9184b5", "Skull Woods": r"https://alttp-wiki.net/images/6/6a/Mothula.png", "Thieves Town": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/8/86/ALttP_Blind_the_Thief_Sprite.png?version=3833021bfcd112be54e7390679047222", "Ice Palace": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/3/33/ALttP_Kholdstare_Sprite.png?version=e5a1b0e8b2298e550d85f90bf97045c0", "Misery Mire": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/8/85/ALttP_Vitreous_Sprite.png?version=92b2e9cb0aa63f831760f08041d8d8d8", "Turtle Rock": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/9/91/ALttP_Trinexx_Sprite.png?version=0cc867d513952aa03edd155597a0c0be", "Ganons Tower": r"https://gamepedia.cursecdn.com/zelda_gamepedia_en/b/b9/ALttP_Ganon_Sprite.png?version=956f51f054954dfff53c1a9d4f929c74" } def get_alttp_id(item_name): return Items.item_table[item_name][2] app.jinja_env.filters["location_name"] = lambda location: lookup_any_location_id_to_name.get(location, location) app.jinja_env.filters['item_name'] = lambda id: lookup_any_item_id_to_name.get(id, id) links = {"Bow": "Progressive Bow", "Silver Arrows": "Progressive Bow", "Silver Bow": "Progressive Bow", "Progressive Bow (Alt)": "Progressive Bow", "Bottle (Red Potion)": "Bottle", "Bottle (Green Potion)": "Bottle", "Bottle (Blue Potion)": "Bottle", "Bottle (Fairy)": "Bottle", "Bottle (Bee)": "Bottle", "Bottle (Good Bee)": "Bottle", "Fighter Sword": "Progressive Sword", "Master Sword": "Progressive Sword", "Tempered Sword": "Progressive Sword", "Golden Sword": "Progressive Sword", "Power Glove": "Progressive Glove", "Titans Mitts": "Progressive Glove" } levels = {"Fighter Sword": 1, "Master Sword": 2, "Tempered Sword": 3, "Golden Sword": 4, "Power Glove": 1, "Titans Mitts": 2, "Bow": 1, "Silver Bow": 2} multi_items = {get_alttp_id(name) for name in ("Progressive Sword", "Progressive Bow", "Bottle", "Progressive Glove")} links = {get_alttp_id(key): get_alttp_id(value) for key, value in links.items()} levels = {get_alttp_id(key): value for key, value in levels.items()} tracking_names = ["Progressive Sword", "Progressive Bow", "Book of Mudora", "Hammer", "Hookshot", "Magic Mirror", "Flute", "Pegasus Boots", "Progressive Glove", "Flippers", "Moon Pearl", "Blue Boomerang", "Red Boomerang", "Bug Catching Net", "Cape", "Shovel", "Lamp", "Mushroom", "Magic Powder", "Cane of Somaria", "Cane of Byrna", "Fire Rod", "Ice Rod", "Bombos", "Ether", "Quake", "Bottle", "Triforce"] default_locations = { 'Light World': {1572864, 1572865, 60034, 1572867, 1572868, 60037, 1572869, 1572866, 60040, 59788, 60046, 60175, 1572880, 60049, 60178, 1572883, 60052, 60181, 1572885, 60055, 60184, 191256, 60058, 60187, 1572884, 1572886, 1572887, 1572906, 60202, 60205, 59824, 166320, 1010170, 60208, 60211, 60214, 60217, 59836, 60220, 60223, 59839, 1573184, 60226, 975299, 1573188, 1573189, 188229, 60229, 60232, 1573193, 1573194, 60235, 1573187, 59845, 59854, 211407, 60238, 59857, 1573185, 1573186, 1572882, 212328, 59881, 59761, 59890, 59770, 193020, 212605}, 'Dark World': {59776, 59779, 975237, 1572870, 60043, 1572881, 60190, 60193, 60196, 60199, 60840, 1573190, 209095, 1573192, 1573191, 60241, 60244, 60247, 60250, 59884, 59887, 60019, 60022, 60028, 60031}, 'Desert Palace': {1573216, 59842, 59851, 59791, 1573201, 59830}, 'Eastern Palace': {1573200, 59827, 59893, 59767, 59833, 59773}, 'Hyrule Castle': {60256, 60259, 60169, 60172, 59758, 59764, 60025, 60253}, 'Agahnims Tower': {60082, 60085}, 'Tower of Hera': {1573218, 59878, 59821, 1573202, 59896, 59899}, 'Swamp Palace': {60064, 60067, 60070, 59782, 59785, 60073, 60076, 60079, 1573204, 60061}, 'Thieves Town': {59905, 59908, 59911, 59914, 59917, 59920, 59923, 1573206}, 'Skull Woods': {59809, 59902, 59848, 59794, 1573205, 59800, 59803, 59806}, 'Ice Palace': {59872, 59875, 59812, 59818, 59860, 59797, 1573207, 59869}, '<NAME>': {60001, 60004, 60007, 60010, 60013, 1573208, 59866, 59998}, 'Turtle Rock': {59938, 59941, 59944, 1573209, 59947, 59950, 59953, 59956, 59926, 59929, 59932, 59935}, 'Palace of Darkness': {59968, 59971, 59974, 59977, 59980, 59983, 59986, 1573203, 59989, 59959, 59992, 59962, 59995, 59965}, 'Ganons Tower': {60160, 60163, 60166, 60088, 60091, 60094, 60097, 60100, 60103, 60106, 60109, 60112, 60115, 60118, 60121, 60124, 60127, 1573217, 60130, 60133, 60136, 60139, 60142, 60145, 60148, 60151, 60157}, 'Total': set()} key_only_locations = { 'Light World': set(), 'Dark World': set(), 'Desert Palace': {0x140031, 0x14002b, 0x140061, 0x140028}, 'Eastern Palace': {0x14005b, 0x140049}, 'Hyrule Castle': {0x140037, 0x140034, 0x14000d, 0x14003d}, 'Agahnims Tower': {0x140061, 0x140052}, 'Tower of Hera': set(), 'Swamp Palace': {0x140019, 0x140016, 0x140013, 0x140010, 0x14000a}, 'Thieves Town': {0x14005e, 0x14004f}, 'Skull Woods': {0x14002e, 0x14001c}, 'Ice Palace': {0x140004, 0x140022, 0x140025, 0x140046}, 'Misery Mire': {0x140055, 0x14004c, 0x140064}, 'Turtle Rock': {0x140058, 0x140007}, 'Palace of Darkness': set(), 'Ganons Tower': {0x140040, 0x140043, 0x14003a, 0x14001f}, 'Total': set() } location_to_area = {} for area, locations in default_locations.items(): for location in locations: location_to_area[location] = area for area, locations in key_only_locations.items(): for location in locations: location_to_area[location] = area checks_in_area = {area: len(checks) for area, checks in default_locations.items()} checks_in_area["Total"] = 216 ordered_areas = ('Light World', 'Dark World', 'Hyrule Castle', 'Agahnims Tower', 'Eastern Palace', 'Desert Palace', 'Tower of Hera', 'Palace of Darkness', 'Swamp Palace', 'Skull Woods', 'Thieves Town', 'Ice Palace', 'Misery Mire', 'Turtle Rock', 'Ganons Tower', "Total") tracking_ids = [] for item in tracking_names: tracking_ids.append(get_alttp_id(item)) small_key_ids = {} big_key_ids = {} ids_small_key = {} ids_big_key = {} for item_name, data in Items.item_table.items(): if "Key" in item_name: area = item_name.split("(")[1][:-1] if "Small" in item_name: small_key_ids[area] = data[2] ids_small_key[data[2]] = area else: big_key_ids[area] = data[2] ids_big_key[data[2]] = area from MultiServer import get_item_name_from_id, Context def attribute_item(inventory, team, recipient, item): target_item = links.get(item, item) if item in levels: # non-progressive inventory[team][recipient][target_item] = max(inventory[team][recipient][target_item], levels[item]) else: inventory[team][recipient][target_item] += 1 def attribute_item_solo(inventory, item): """Adds item to inventory counter, converts everything to progressive.""" target_item = links.get(item, item) if item in levels: # non-progressive inventory[target_item] = max(inventory[target_item], levels[item]) else: inventory[target_item] += 1 @app.template_filter() def render_timedelta(delta: datetime.timedelta): hours, minutes = divmod(delta.total_seconds() / 60, 60) hours = str(int(hours)) minutes = str(int(minutes)).zfill(2) return f"{hours}:{minutes}" _multidata_cache = {} def get_location_table(checks_table: dict) -> dict: loc_to_area = {} for area, locations in checks_table.items(): if area == "Total": continue for location in locations: loc_to_area[location] = area return loc_to_area def get_static_room_data(room: Room): result = _multidata_cache.get(room.seed.id, None) if result: return result multidata = Context._decompress(room.seed.multidata) # in > 100 players this can take a bit of time and is the main reason for the cache locations: Dict[int, Dict[int, Tuple[int, int]]] = multidata['locations'] names: Dict[int, Dict[int, str]] = multidata["names"] seed_checks_in_area = checks_in_area.copy() use_door_tracker = False if "tags" in multidata: use_door_tracker = "DR" in multidata["tags"] if use_door_tracker: for area, checks in key_only_locations.items(): seed_checks_in_area[area] += len(checks) seed_checks_in_area["Total"] = 249 player_checks_in_area = {playernumber: {areaname: len(multidata["checks_in_area"][playernumber][areaname]) if areaname != "Total" else multidata["checks_in_area"][playernumber]["Total"] for areaname in ordered_areas} for playernumber in range(1, len(names[0]) + 1)} player_location_to_area = {playernumber: get_location_table(multidata["checks_in_area"][playernumber]) for playernumber in range(1, len(names[0]) + 1)} result = locations, names, use_door_tracker, player_checks_in_area, player_location_to_area, \ multidata["precollected_items"], \ multidata["games"] _multidata_cache[room.seed.id] = result return result @app.route('/tracker/<suuid:tracker>/<int:tracked_team>/<int:tracked_player>') @cache.memoize(timeout=60) # multisave is currently created at most every minute def getPlayerTracker(tracker: UUID, tracked_team: int, tracked_player: int): # Team and player must be positive and greater than zero if tracked_team < 0 or tracked_player < 1: abort(404) room: Optional[Room] = Room.get(tracker=tracker) if not room: abort(404) # Collect seed information and pare it down to a single player locations, names, use_door_tracker, seed_checks_in_area, player_location_to_area, \ precollected_items, games = get_static_room_data(room) player_name = names[tracked_team][tracked_player - 1] location_to_area = player_location_to_area[tracked_player] inventory = collections.Counter() checks_done = {loc_name: 0 for loc_name in default_locations} # Add starting items to inventory starting_items = precollected_items[tracked_player] if starting_items: for item_id in starting_items: attribute_item_solo(inventory, item_id) if room.multisave: multisave: Dict[str, Any] = restricted_loads(room.multisave) else: multisave: Dict[str, Any] = {} # Add items to player inventory for (ms_team, ms_player), locations_checked in multisave.get("location_checks", {}).items(): # Skip teams and players not matching the request player_locations = locations[ms_player] if ms_team == tracked_team: # If the player does not have the item, do nothing for location in locations_checked: if location in player_locations: item, recipient = player_locations[location] if recipient == tracked_player: # a check done for the tracked player attribute_item_solo(inventory, item) if ms_player == tracked_player: # a check done by the tracked player checks_done[location_to_area[location]] += 1 checks_done["Total"] += 1 if games[tracked_player] == "A Link to the Past": return __renderAlttpTracker(multisave, room, locations, inventory, tracked_team, tracked_player, player_name, \ seed_checks_in_area, checks_done) elif games[tracked_player] == "Minecraft": return __renderMinecraftTracker(multisave, room, locations, inventory, tracked_team, tracked_player, player_name) elif games[tracked_player] == "Ocarina of Time": return __renderOoTTracker(multisave, room, locations, inventory, tracked_team, tracked_player, player_name) elif games[tracked_player] == "Timespinner": return __renderTimespinnerTracker(multisave, room, locations, inventory, tracked_team, tracked_player, player_name) else: return __renderGenericTracker(multisave, room, locations, inventory, tracked_team, tracked_player, player_name) def __renderAlttpTracker(multisave: Dict[str, Any], room: Room, locations: Dict[int, Dict[int, Tuple[int, int]]], inventory: Counter, team: int, player: int, playerName: str, seed_checks_in_area: Dict[int, Dict[str, int]], checks_done: Dict[str, int]) -> str: # Note the presence of the triforce item game_state = multisave.get("client_game_state", {}).get((team, player), 0) if game_state == 30: inventory[106] = 1 # Triforce # Progressive items need special handling for icons and class progressive_items = { "Progressive Sword": 94, "Progressive Glove": 97, "Progressive Bow": 100, "Progressive Mail": 96, "Progressive Shield": 95, } progressive_names = { "Progressive Sword": [None, 'Fighter Sword', 'Master Sword', 'Tempered Sword', 'Golden Sword'], "Progressive Glove": [None, 'Power Glove', 'Titan Mitts'], "Progressive Bow": [None, "Bow", "Silver Bow"], "Progressive Mail": ["Green Mail", "Blue Mail", "Red Mail"], "Progressive Shield": [None, "Blue Shield", "Red Shield", "Mirror Shield"] } # Determine which icon to use display_data = {} for item_name, item_id in progressive_items.items(): level = min(inventory[item_id], len(progressive_names[item_name]) - 1) display_name = progressive_names[item_name][level] acquired = True if not display_name: acquired = False display_name = progressive_names[item_name][level + 1] base_name = item_name.split(maxsplit=1)[1].lower() display_data[base_name + "_acquired"] = acquired display_data[base_name + "_url"] = alttp_icons[display_name] # The single player tracker doesn't care about overworld, underworld, and total checks. Maybe it should? sp_areas = ordered_areas[2:15] player_big_key_locations = set() player_small_key_locations = set() for loc_data in locations.values(): for item_id, item_player in loc_data.values(): if item_player == player: if item_id in ids_big_key: player_big_key_locations.add(ids_big_key[item_id]) elif item_id in ids_small_key: player_small_key_locations.add(ids_small_key[item_id]) return render_template("lttpTracker.html", inventory=inventory, player_name=playerName, room=room, icons=alttp_icons, checks_done=checks_done, checks_in_area=seed_checks_in_area[player], acquired_items={lookup_any_item_id_to_name[id] for id in inventory}, small_key_ids=small_key_ids, big_key_ids=big_key_ids, sp_areas=sp_areas, key_locations=player_small_key_locations, big_key_locations=player_big_key_locations, **display_data) def __renderMinecraftTracker(multisave: Dict[str, Any], room: Room, locations: Dict[int, Dict[int, Tuple[int, int]]], inventory: Counter, team: int, player: int, playerName: str) -> str: icons = { "Wooden Pickaxe": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/d/d2/Wooden_Pickaxe_JE3_BE3.png", "Stone Pickaxe": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/c/c4/Stone_Pickaxe_JE2_BE2.png", "Iron Pickaxe": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/d/d1/Iron_Pickaxe_JE3_BE2.png", "Diamond Pickaxe": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/e/e7/Diamond_Pickaxe_JE3_BE3.png", "Wooden Sword": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/d/d5/Wooden_Sword_JE2_BE2.png", "Stone Sword": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/b/b1/Stone_Sword_JE2_BE2.png", "Iron Sword": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/8/8e/Iron_Sword_JE2_BE2.png", "Diamond Sword": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/4/44/Diamond_Sword_JE3_BE3.png", "Leather Tunic": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/b/b7/Leather_Tunic_JE4_BE2.png", "Iron Chestplate": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/3/31/Iron_Chestplate_JE2_BE2.png", "Diamond Chestplate": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/e/e0/Diamond_Chestplate_JE3_BE2.png", "Iron Ingot": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/f/fc/Iron_Ingot_JE3_BE2.png", "Block of Iron": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/7/7e/Block_of_Iron_JE4_BE3.png", "Brewing Stand": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/f/fa/Brewing_Stand.png", "Ender Pearl": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/f/f6/Ender_Pearl_JE3_BE2.png", "Bucket": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/f/fc/Bucket_JE2_BE2.png", "Bow": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/a/ab/Bow_%28Pull_2%29_JE1_BE1.png", "Shield": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/c/c6/Shield_JE2_BE1.png", "Red Bed": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/d/dc/Red_Bed_JE4_BE3.png", "Netherite Scrap": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/3/33/Netherite_Scrap_JE2_BE1.png", "Flint and Steel": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/9/94/Flint_and_Steel_JE4_BE2.png", "Enchanting Table": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/3/31/Enchanting_Table.gif", "Fishing Rod": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/7/7f/Fishing_Rod_JE2_BE2.png", "Campfire": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/9/91/Campfire_JE2_BE2.gif", "Water Bottle": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/7/75/Water_Bottle_JE2_BE2.png", "Dragon Head": "https://static.wikia.nocookie.net/minecraft_gamepedia/images/b/b6/Dragon_Head.png", } minecraft_location_ids = { "Story": [42073, 42080, 42081, 42023, 42082, 42027, 42039, 42085, 42002, 42009, 42010, 42070, 42041, 42049, 42090, 42004, 42031, 42025, 42029, 42051, 42077, 42089], "Nether": [42017, 42044, 42069, 42058, 42034, 42060, 42066, 42076, 42064, 42071, 42021, 42062, 42008, 42061, 42033, 42011, 42006, 42019, 42000, 42040, 42001, 42015, 42014], "The End": [42052, 42005, 42012, 42032, 42030, 42042, 42018, 42038, 42046], "Adventure": [42047, 42086, 42087, 42050, 42059, 42055, 42072, 42003, 42035, 42016, 42020, 42048, 42054, 42068, 42043, 42074, 42075, 42024, 42026, 42037, 42045, 42056, 42088], "Husbandry": [42065, 42067, 42078, 42022, 42007, 42079, 42013, 42028, 42036, 42057, 42063, 42053, 42083, 42084, 42091] } display_data = {} # Determine display for progressive items progressive_items = { "Progressive Tools": 45013, "Progressive Weapons": 45012, "Progressive Armor": 45014, "Progressive Resource Crafting": 45001 } progressive_names = { "Progressive Tools": ["Wooden Pickaxe", "Stone Pickaxe", "Iron Pickaxe", "Diamond Pickaxe"], "Progressive Weapons": ["Wooden Sword", "Stone Sword", "Iron Sword", "Diamond Sword"], "Progressive Armor": ["Leather Tunic", "Iron Chestplate", "Diamond Chestplate"], "Progressive Resource Crafting": ["Iron Ingot", "Iron Ingot", "Block of Iron"] } for item_name, item_id in progressive_items.items(): level = min(inventory[item_id], len(progressive_names[item_name]) - 1) display_name = progressive_names[item_name][level] base_name = item_name.split(maxsplit=1)[1].lower().replace(' ', '_') display_data[base_name + "_url"] = icons[display_name] # Multi-items multi_items = { "3 Ender Pearls": 45029, "8 Netherite Scrap": 45015 } for item_name, item_id in multi_items.items(): base_name = item_name.split()[-1].lower() count = inventory[item_id] if count >= 0: display_data[base_name + "_count"] = count # Victory condition game_state = multisave.get("client_game_state", {}).get((team, player), 0) display_data['game_finished'] = game_state == 30 # Turn location IDs into advancement tab counts checked_locations = multisave.get("location_checks", {}).get((team, player), set()) lookup_name = lambda id: lookup_any_location_id_to_name[id] location_info = {tab_name: {lookup_name(id): (id in checked_locations) for id in tab_locations} for tab_name, tab_locations in minecraft_location_ids.items()} checks_done = {tab_name: len([id for id in tab_locations if id in checked_locations]) for tab_name, tab_locations in minecraft_location_ids.items()} checks_done['Total'] = len(checked_locations) checks_in_area = {tab_name: len(tab_locations) for tab_name, tab_locations in minecraft_location_ids.items()} checks_in_area['Total'] = sum(checks_in_area.values()) return render_template("minecraftTracker.html", inventory=inventory, icons=icons, acquired_items={lookup_any_item_id_to_name[id] for id in inventory if id in lookup_any_item_id_to_name}, player=player, team=team, room=room, player_name=playerName, checks_done=checks_done, checks_in_area=checks_in_area, location_info=location_info, **display_data) def __renderOoTTracker(multisave: Dict[str, Any], room: Room, locations: Dict[int, Dict[int, Tuple[int, int]]], inventory: Counter, team: int, player: int, playerName: str) -> str: icons = { "Fairy Ocarina": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/9/97/OoT_Fairy_Ocarina_Icon.png", "Ocarina of Time": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/4/4e/OoT_Ocarina_of_Time_Icon.png", "Slingshot": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/3/32/OoT_Fairy_Slingshot_Icon.png", "Boomerang": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/d/d5/OoT_Boomerang_Icon.png", "Bottle": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/f/fc/OoT_Bottle_Icon.png", "Rutos Letter": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/2/21/OoT_Letter_Icon.png", "Bombs": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/1/11/OoT_Bomb_Icon.png", "Bombchus": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/3/36/OoT_Bombchu_Icon.png", "Lens of Truth": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/0/05/OoT_Lens_of_Truth_Icon.png", "Bow": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/9/9a/OoT_Fairy_Bow_Icon.png", "Hookshot": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/7/77/OoT_Hookshot_Icon.png", "Longshot": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/a/a4/OoT_Longshot_Icon.png", "Megaton Hammer": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/9/93/OoT_Megaton_Hammer_Icon.png", "Fire Arrows": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/1/1e/OoT_Fire_Arrow_Icon.png", "Ice Arrows": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/3/3c/OoT_Ice_Arrow_Icon.png", "Light Arrows": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/7/76/OoT_Light_Arrow_Icon.png", "Dins Fire": r"https://static.wikia.nocookie.net/zelda_gamepedia_en/images/d/da/OoT_Din%27s_Fire_Icon.png", "Farores Wind": r"https://static.wikia.nocookie.net/zelda_gamepedia_en/images/7/7a/OoT_Farore%27s_Wind_Icon.png", "Nayrus Love": r"https://static.wikia.nocookie.net/zelda_gamepedia_en/images/b/be/OoT_Nayru%27s_Love_Icon.png", "Kokiri Sword": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/5/53/OoT_Kokiri_Sword_Icon.png", "Biggoron Sword": r"https://static.wikia.nocookie.net/zelda_gamepedia_en/images/2/2e/OoT_Giant%27s_Knife_Icon.png", "Mirror Shield": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/b/b0/OoT_Mirror_Shield_Icon_2.png", "Goron Bracelet": r"https://static.wikia.nocookie.net/zelda_gamepedia_en/images/b/b7/OoT_Goron%27s_Bracelet_Icon.png", "Silver Gauntlets": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/b/b9/OoT_Silver_Gauntlets_Icon.png", "Golden Gauntlets": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/6/6a/OoT_Golden_Gauntlets_Icon.png", "Goron Tunic": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/1/1c/OoT_Goron_Tunic_Icon.png", "Zora Tunic": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/2/2c/OoT_Zora_Tunic_Icon.png", "Silver Scale": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/4/4e/OoT_Silver_Scale_Icon.png", "Gold Scale": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/9/95/OoT_Golden_Scale_Icon.png", "Iron Boots": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/3/34/OoT_Iron_Boots_Icon.png", "Hover Boots": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/2/22/OoT_Hover_Boots_Icon.png", "Adults Wallet": r"https://static.wikia.nocookie.net/zelda_gamepedia_en/images/f/f9/OoT_Adult%27s_Wallet_Icon.png", "Giants Wallet": r"https://static.wikia.nocookie.net/zelda_gamepedia_en/images/8/87/OoT_Giant%27s_Wallet_Icon.png", "Small Magic": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/9/9f/OoT3D_Magic_Jar_Icon.png", "Large Magic": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/3/3e/OoT3D_Large_Magic_Jar_Icon.png", "Gerudo Membership Card": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/4/4e/OoT_Gerudo_Token_Icon.png", "Gold Skulltula Token": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/4/47/OoT_Token_Icon.png", "Triforce Piece": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/0/0b/SS_Triforce_Piece_Icon.png", "Triforce": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/6/68/ALttP_Triforce_Title_Sprite.png", "Zeldas Lullaby": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/2/21/Grey_Note.png", "Eponas Song": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/2/21/Grey_Note.png", "Sarias Song": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/2/21/Grey_Note.png", "Suns Song": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/2/21/Grey_Note.png", "Song of Time": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/2/21/Grey_Note.png", "Song of Storms": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/2/21/Grey_Note.png", "Minuet of Forest": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/e/e4/Green_Note.png", "Bolero of Fire": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/f/f0/Red_Note.png", "Serenade of Water": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/0/0f/Blue_Note.png", "Requiem of Spirit": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/a/a4/Orange_Note.png", "Nocturne of Shadow": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/9/97/Purple_Note.png", "Prelude of Light": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/9/90/Yellow_Note.png", "Small Key": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/e/e5/OoT_Small_Key_Icon.png", "Boss Key": "https://static.wikia.nocookie.net/zelda_gamepedia_en/images/4/40/OoT_Boss_Key_Icon.png", } display_data = {} # Determine display for progressive items progressive_items = { "Progressive Hookshot": 66128, "Progressive Strength Upgrade": 66129, "Progressive Wallet": 66133, "Progressive Scale": 66134, "Magic Meter": 66138, "Ocarina": 66139, } progressive_names = { "Progressive Hookshot": ["Hookshot", "Hookshot", "Longshot"], "Progressive Strength Upgrade": ["Goron Bracelet", "Goron Bracelet", "Silver Gauntlets", "Golden Gauntlets"], "Progressive Wallet": ["Adults Wallet", "Adults Wallet", "Giants Wallet", "Giants Wallet"], "Progressive Scale": ["Silver Scale", "Silver Scale", "Gold Scale"], "Magic Meter": ["Small Magic", "Small Magic", "Large Magic"], "Ocarina": ["Fairy Ocarina", "Fairy Ocarina", "Ocarina of Time"] } for item_name, item_id in progressive_items.items(): level = min(inventory[item_id], len(progressive_names[item_name])-1) display_name = progressive_names[item_name][level] if item_name.startswith("Progressive"): base_name = item_name.split(maxsplit=1)[1].lower().replace(' ', '_') else: base_name = item_name.lower().replace(' ', '_') display_data[base_name+"_url"] = icons[display_name] if base_name == "hookshot": display_data['hookshot_length'] = {0: '', 1: 'H', 2: 'L'}.get(level) if base_name == "wallet": display_data['wallet_size'] = {0: '99', 1: '200', 2: '500', 3: '999'}.get(level) # Determine display for bottles. Show letter if it's obtained, determine bottle count bottle_ids = [66015, 66020, 66021, 66140, 66141, 66142, 66143, 66144, 66145, 66146, 66147, 66148] display_data['bottle_count'] = min(sum(map(lambda item_id: inventory[item_id], bottle_ids)), 4) display_data['bottle_url'] = icons['Rutos Letter'] if inventory[66021] > 0 else icons['Bottle'] # Determine bombchu display display_data['has_bombchus'] = any(map(lambda item_id: inventory[item_id] > 0, [66003, 66106, 66107, 66137])) # Multi-items multi_items = { "Gold Skulltula Token": 66091, "Triforce Piece": 66202, } for item_name, item_id in multi_items.items(): base_name = item_name.split()[-1].lower() count = inventory[item_id] display_data[base_name+"_count"] = inventory[item_id] # Gather dungeon locations area_id_ranges = { "Overworld": (67000, 67280), "Deku Tree": (67281, 67303), "Dodongo's Cavern": (67304, 67334), "Jabu Jabu's Belly": (67335, 67359), "Bottom of the Well": (67360, 67384), "Forest Temple": (67385, 67420), "Fire Temple": (67421, 67457), "Water Temple": (67458, 67484), "Shadow Temple": (67485, 67532), "Spirit Temple": (67533, 67582), "Ice Cavern": (67583, 67596), "Gerudo Training Grounds": (67597, 67635), "Ganon's Castle": (67636, 67673), } def lookup_and_trim(id, area): full_name = lookup_any_location_id_to_name[id] if id == 67673: return full_name[13:] # Ganons Tower Boss Key Chest if area != 'Overworld': return full_name[len(area):] # trim dungeon name. leaves an extra space that doesn't display, or trims fully for DC/Jabu/GC return full_name checked_locations = multisave.get("location_checks", {}).get((team, player), set()).intersection(set(locations[player])) location_info = {area: {lookup_and_trim(id, area): id in checked_locations for id in range(min_id, max_id+1) if id in locations[player]} for area, (min_id, max_id) in area_id_ranges.items()} checks_done = {area: len(list(filter(lambda x: x, location_info[area].values()))) for area in area_id_ranges} checks_in_area = {area: len([id for id in range(min_id, max_id+1) if id in locations[player]]) for area, (min_id, max_id) in area_id_ranges.items()} checks_done['Total'] = sum(checks_done.values()) checks_in_area['Total'] = sum(checks_in_area.values()) # Give skulltulas on non-tracked locations non_tracked_locations = multisave.get("location_checks", {}).get((team, player), set()).difference(set(locations[player])) for id in non_tracked_locations: if "GS" in lookup_and_trim(id, ''): display_data["token_count"] += 1 # Gather small and boss key info small_key_counts = { "Forest Temple": inventory[66175], "Fire Temple": inventory[66176], "Water Temple": inventory[66177], "Spirit Temple": inventory[66178], "Shadow Temple": inventory[66179], "Bottom of the Well": inventory[66180], "Gerudo Training Grounds": inventory[66181], "Ganon's Castle": inventory[66183], } boss_key_counts = { "Forest Temple": '✔' if inventory[66149] else '✕', "Fire Temple": '✔' if inventory[66150] else '✕', "Water Temple": '✔' if inventory[66151] else '✕', "Spirit Temple": '✔' if inventory[66152] else '✕', "Shadow Temple": '✔' if inventory[66153] else '✕', "Ganon's Castle": '✔' if inventory[66154] else '✕', } # Victory condition game_state = multisave.get("client_game_state", {}).get((team, player), 0) display_data['game_finished'] = game_state == 30 return render_template("ootTracker.html", inventory=inventory, player=player, team=team, room=room, player_name=playerName, icons=icons, acquired_items={lookup_any_item_id_to_name[id] for id in inventory}, checks_done=checks_done, checks_in_area=checks_in_area, location_info=location_info, small_key_counts=small_key_counts, boss_key_counts=boss_key_counts, **display_data) def __renderTimespinnerTracker(multisave: Dict[str, Any], room: Room, locations: Dict[int, Dict[int, Tuple[int, int]]], inventory: Counter, team: int, player: int, playerName: str) -> str: icons = { "Timespinner Wheel": "https://timespinnerwiki.com/mediawiki/images/7/76/Timespinner_Wheel.png", "Timespinner Spindle": "https://timespinnerwiki.com/mediawiki/images/1/1a/Timespinner_Spindle.png", "Timespinner Gear 1": "https://timespinnerwiki.com/mediawiki/images/3/3c/Timespinner_Gear_1.png", "Timespinner Gear 2": "https://timespinnerwiki.com/mediawiki/images/e/e9/Timespinner_Gear_2.png", "Timespinner Gear 3": "https://timespinnerwiki.com/mediawiki/images/2/22/Timespinner_Gear_3.png", "Talaria Attachment": "https://timespinnerwiki.com/mediawiki/images/6/61/Talaria_Attachment.png", "Succubus Hairpin": "https://timespinnerwiki.com/mediawiki/images/4/49/Succubus_Hairpin.png", "Lightwall": "https://timespinnerwiki.com/mediawiki/images/0/03/Lightwall.png", "Celestial Sash": "https://timespinnerwiki.com/mediawiki/images/f/f1/Celestial_Sash.png", "Twin Pyramid Key": "https://timespinnerwiki.com/mediawiki/images/4/49/Twin_Pyramid_Key.png", "Security Keycard D": "https://timespinnerwiki.com/mediawiki/images/1/1b/Security_Keycard_D.png", "Security Keycard C": "https://timespinnerwiki.com/mediawiki/images/e/e5/Security_Keycard_C.png", "Security Keycard B": "https://timespinnerwiki.com/mediawiki/images/f/f6/Security_Keycard_B.png", "Security Keycard A": "https://timespinnerwiki.com/mediawiki/images/b/b9/Security_Keycard_A.png", "Library Keycard V": "https://timespinnerwiki.com/mediawiki/images/5/50/Library_Keycard_V.png", "Tablet": "https://timespinnerwiki.com/mediawiki/images/a/a0/Tablet.png", "Elevator Keycard": "https://timespinnerwiki.com/mediawiki/images/5/55/Elevator_Keycard.png", "Oculus Ring": "https://timespinnerwiki.com/mediawiki/images/8/8d/Oculus_Ring.png", "Water Mask": "https://timespinnerwiki.com/mediawiki/images/0/04/Water_Mask.png", "Gas Mask": "https://timespinnerwiki.com/mediawiki/images/2/2e/Gas_Mask.png", "Djinn Inferno": "https://timespinnerwiki.com/mediawiki/images/f/f6/Djinn_Inferno.png", "Pyro Ring": "https://timespinnerwiki.com/mediawiki/images/2/2c/Pyro_Ring.png", "Infernal Flames": "https://timespinnerwiki.com/mediawiki/images/1/1f/Infernal_Flames.png", "Fire Orb": "https://timespinnerwiki.com/mediawiki/images/3/3e/Fire_Orb.png", "Royal Ring": "https://timespinnerwiki.com/mediawiki/images/f/f3/Royal_Ring.png", "Plasma Geyser": "https://timespinnerwiki.com/mediawiki/images/1/12/Plasma_Geyser.png", "Plasma Orb": "https://timespinnerwiki.com/mediawiki/images/4/44/Plasma_Orb.png", } timespinner_location_ids = { "Present": [ 1337000, 1337001, 1337002, 1337003, 1337004, 1337005, 1337006, 1337007, 1337008, 1337009, 1337010, 1337011, 1337012, 1337013, 1337014, 1337015, 1337016, 1337017, 1337018, 1337019, 1337020, 1337021, 1337022, 1337023, 1337024, 1337025, 1337026, 1337027, 1337028, 1337029, 1337030, 1337031, 1337032, 1337033, 1337034, 1337035, 1337036, 1337037, 1337038, 1337039, 1337040, 1337041, 1337042, 1337043, 1337044, 1337045, 1337046, 1337047, 1337048, 1337049, 1337050, 1337051, 1337052, 1337053, 1337054, 1337055, 1337056, 1337057, 1337058, 1337059, 1337060, 1337061, 1337062, 1337063, 1337064, 1337065, 1337066, 1337067, 1337068, 1337069, 1337070, 1337071, 1337072, 1337073, 1337074, 1337075, 1337076, 1337077, 1337078, 1337079, 1337080, 1337081, 1337082, 1337083, 1337084, 1337085, 1337156, 1337157, 1337159, 1337160, 1337161, 1337162, 1337163, 1337164, 1337165, 1337166, 1337167, 1337168, 1337169, 1337170], "Past": [ 1337086, 1337087, 1337088, 1337089, 1337090, 1337091, 1337092, 1337093, 1337094, 1337095, 1337096, 1337097, 1337098, 1337099, 1337100, 1337101, 1337102, 1337103, 1337104, 1337105, 1337106, 1337107, 1337108, 1337109, 1337110, 1337111, 1337112, 1337113, 1337114, 1337115, 1337116, 1337117, 1337118, 1337119, 1337120, 1337121, 1337122, 1337123, 1337124, 1337125, 1337126, 1337127, 1337128, 1337129, 1337130, 1337131, 1337132, 1337133, 1337134, 1337135, 1337136, 1337137, 1337138, 1337139, 1337140, 1337141, 1337142, 1337143, 1337144, 1337145, 1337146, 1337147, 1337148, 1337149, 1337150, 1337151, 1337152, 1337153, 1337154, 1337155], "Ancient Pyramid": [1337246, 1337247, 1337248, 1337249] } display_data = {} # Victory condition game_state = multisave.get("client_game_state", {}).get((team, player), 0) display_data['game_finished'] = game_state == 30 # Turn location IDs into advancement tab counts checked_locations = multisave.get("location_checks", {}).get((team, player), set()) lookup_name = lambda id: lookup_any_location_id_to_name[id] location_info = {tab_name: {lookup_name(id): (id in checked_locations) for id in tab_locations} for tab_name, tab_locations in timespinner_location_ids.items()} checks_done = {tab_name: len([id for id in tab_locations if id in checked_locations]) for tab_name, tab_locations in timespinner_location_ids.items()} checks_done['Total'] = len(checked_locations) checks_in_area = {tab_name: len(tab_locations) for tab_name, tab_locations in timespinner_location_ids.items()} checks_in_area['Total'] = sum(checks_in_area.values()) return render_template("timespinnerTracker.html", inventory=inventory, icons=icons, acquired_items={lookup_any_item_id_to_name[id] for id in inventory if id in lookup_any_item_id_to_name}, player=player, team=team, room=room, player_name=playerName, checks_done=checks_done, checks_in_area=checks_in_area, location_info=location_info, **display_data) def __renderGenericTracker(multisave: Dict[str, Any], room: Room, locations: Dict[int, Dict[int, Tuple[int, int]]], inventory: Counter, team: int, player: int, playerName: str) -> str: checked_locations = multisave.get("location_checks", {}).get((team, player), set()) player_received_items = {} for order_index, networkItem in enumerate( multisave.get('received_items', {}).get((team, player), []), start=1 ): player_received_items[networkItem.item] = order_index return render_template("genericTracker.html", inventory=inventory, player=player, team=team, room=room, player_name=playerName, checked_locations=checked_locations, not_checked_locations=set(locations[player]) - checked_locations, received_items=player_received_items) @app.route('/tracker/<suuid:tracker>') @cache.memoize(timeout=60) # multisave is currently created at most every minute def getTracker(tracker: UUID): room: Room = Room.get(tracker=tracker) if not room: abort(404) locations, names, use_door_tracker, seed_checks_in_area, player_location_to_area, \ precollected_items, games = get_static_room_data(room) inventory = {teamnumber: {playernumber: collections.Counter() for playernumber in range(1, len(team) + 1)} for teamnumber, team in enumerate(names)} checks_done = {teamnumber: {playernumber: {loc_name: 0 for loc_name in default_locations} for playernumber in range(1, len(team) + 1)} for teamnumber, team in enumerate(names)} hints = {team: set() for team in range(len(names))} if room.multisave: multisave = restricted_loads(room.multisave) else: multisave = {} if "hints" in multisave: for (team, slot), slot_hints in multisave["hints"].items(): hints[team] |= set(slot_hints) for (team, player), locations_checked in multisave.get("location_checks", {}).items(): player_locations = locations[player] if precollected_items: precollected = precollected_items[player] for item_id in precollected: attribute_item(inventory, team, player, item_id) for location in locations_checked: if location not in player_locations or location not in player_location_to_area[player]: continue item, recipient = player_locations[location] attribute_item(inventory, team, recipient, item) checks_done[team][player][player_location_to_area[player][location]] += 1 checks_done[team][player]["Total"] += 1 for (team, player), game_state in multisave.get("client_game_state", {}).items(): if game_state == 30: inventory[team][player][106] = 1 # Triforce player_big_key_locations = {playernumber: set() for playernumber in range(1, len(names[0]) + 1)} player_small_key_locations = {playernumber: set() for playernumber in range(1, len(names[0]) + 1)} for loc_data in locations.values(): for item_id, item_player in loc_data.values(): if item_id in ids_big_key: player_big_key_locations[item_player].add(ids_big_key[item_id]) elif item_id in ids_small_key: player_small_key_locations[item_player].add(ids_small_key[item_id]) group_big_key_locations = set() group_key_locations = set() for player in range(1, len(names[0]) + 1): group_key_locations |= player_small_key_locations[player] group_big_key_locations |= player_big_key_locations[player] activity_timers = {} now = datetime.datetime.utcnow() for (team, player), timestamp in multisave.get("client_activity_timers", []): activity_timers[team, player] = now - datetime.datetime.utcfromtimestamp(timestamp) player_names = {} for team, names in enumerate(names): for player, name in enumerate(names, 1): player_names[(team, player)] = name long_player_names = player_names.copy() for (team, player), alias in multisave.get("name_aliases", {}).items(): player_names[(team, player)] = alias long_player_names[(team, player)] = f"{alias} ({long_player_names[(team, player)]})" video = {} for (team, player), data in multisave.get("video", []): video[(team, player)] = data return render_template("tracker.html", inventory=inventory, get_item_name_from_id=get_item_name_from_id, lookup_id_to_name=Items.lookup_id_to_name, player_names=player_names, tracking_names=tracking_names, tracking_ids=tracking_ids, room=room, icons=alttp_icons, multi_items=multi_items, checks_done=checks_done, ordered_areas=ordered_areas, checks_in_area=seed_checks_in_area, activity_timers=activity_timers, key_locations=group_key_locations, small_key_ids=small_key_ids, big_key_ids=big_key_ids, video=video, big_key_locations=group_big_key_locations, hints=hints, long_player_names=long_player_names) <file_sep> from BaseClasses import Entrance from .Regions import TimeOfDay class OOTEntrance(Entrance): game: str = 'Ocarina of Time' def __init__(self, player, name='', parent=None): super(OOTEntrance, self).__init__(player, name, parent) self.access_rules = [] self.reverse = None self.replaces = None self.assumed = None self.type = None self.shuffled = False self.data = None self.primary = False self.always = False self.never = False <file_sep>from collections import deque import logging from .SaveContext import SaveContext from BaseClasses import CollectionState from worlds.generic.Rules import set_rule, add_rule, add_item_rule, forbid_item from ..AutoWorld import LogicMixin class OOTLogic(LogicMixin): def _oot_has_stones(self, count, player): return self.has_group("stones", player, count) def _oot_has_medallions(self, count, player): return self.has_group("medallions", player, count) def _oot_has_dungeon_rewards(self, count, player): return self.has_group("rewards", player, count) def _oot_has_bottle(self, player): return self.has_group("bottles", player) # Used for fall damage and other situations where damage is unavoidable def _oot_can_live_dmg(self, player, hearts): mult = self.world.worlds[player].damage_multiplier if hearts*4 >= 3: return mult != 'ohko' and mult != 'quadruple' else: return mult != 'ohko' # This function operates by assuming different behavior based on the "level of recursion", handled manually. # If it's called while self.age[player] is None, then it will set the age variable and then attempt to reach the region. # If self.age[player] is not None, then it will compare it to the 'age' parameter, and return True iff they are equal. # This lets us fake the OOT accessibility check that cares about age. Unfortunately it's still tied to the ground region. def _oot_reach_as_age(self, regionname, age, player): if self.age[player] is None: self.age[player] = age can_reach = self.world.get_region(regionname, player).can_reach(self) self.age[player] = None return can_reach return self.age[player] == age # Store the age before calling this! def _oot_update_age_reachable_regions(self, player): self.stale[player] = False for age in ['child', 'adult']: self.age[player] = age rrp = getattr(self, f'{age}_reachable_regions')[player] bc = getattr(self, f'{age}_blocked_connections')[player] queue = deque(getattr(self, f'{age}_blocked_connections')[player]) start = self.world.get_region('Menu', player) # init on first call - this can't be done on construction since the regions don't exist yet if not start in rrp: rrp.add(start) bc.update(start.exits) queue.extend(start.exits) # run BFS on all connections, and keep track of those blocked by missing items while queue: connection = queue.popleft() new_region = connection.connected_region if new_region in rrp: bc.remove(connection) elif connection.can_reach(self): rrp.add(new_region) bc.remove(connection) bc.update(new_region.exits) queue.extend(new_region.exits) self.path[new_region] = (new_region.name, self.path.get(connection, None)) # Sets extra rules on various specific locations not handled by the rule parser. def set_rules(ootworld): logger = logging.getLogger('') world = ootworld.world player = ootworld.player if ootworld.logic_rules != 'no_logic': if ootworld.triforce_hunt: world.completion_condition[player] = lambda state: state.has('Triforce Piece', player, ootworld.triforce_goal) else: world.completion_condition[player] = lambda state: state.has('Triforce', player) # ganon can only carry triforce world.get_location('Ganon', player).item_rule = lambda item: item.name == 'Triforce' # is_child = ootworld.parser.parse_rule('is_child') guarantee_hint = ootworld.parser.parse_rule('guarantee_hint') for location in filter(lambda location: location.name in ootworld.shop_prices or 'Deku Scrub' in location.name, ootworld.get_locations()): if location.type == 'Shop': location.price = ootworld.shop_prices[location.name] add_rule(location, create_shop_rule(location, ootworld.parser)) if ootworld.dungeon_mq['Forest Temple'] and ootworld.shuffle_bosskeys == 'dungeon' and ootworld.shuffle_smallkeys == 'dungeon' and ootworld.tokensanity == 'off': # First room chest needs to be a small key. Make sure the boss key isn't placed here. location = world.get_location('Forest Temple MQ First Room Chest', player) forbid_item(location, 'Boss Key (Forest Temple)', ootworld.player) if ootworld.shuffle_song_items == 'song' and not ootworld.starting_songs: # Sheik in Ice Cavern is the only song location in a dungeon; need to ensure that it cannot be anything else. # This is required if map/compass included, or any_dungeon shuffle. location = world.get_location('Sheik in Ice Cavern', player) add_item_rule(location, lambda item: item.player == player and item.type == 'Song') for name in ootworld.always_hints: add_rule(world.get_location(name, player), guarantee_hint) # TODO: re-add hints once they are working # if location.type == 'HintStone' and ootworld.hints == 'mask': # location.add_rule(is_child) def create_shop_rule(location, parser): def required_wallets(price): if price > 500: return 3 if price > 200: return 2 if price > 99: return 1 return 0 return parser.parse_rule('(Progressive_Wallet, %d)' % required_wallets(location.price)) def limit_to_itemset(location, itemset): old_rule = location.item_rule location.item_rule = lambda item: item.name in itemset and old_rule(item) # This function should be run once after the shop items are placed in the world. # It should be run before other items are placed in the world so that logic has # the correct checks for them. This is safe to do since every shop is still # accessible when all items are obtained and every shop item is not. # This function should also be called when a world is copied if the original world # had called this function because the world.copy does not copy the rules def set_shop_rules(ootworld): found_bombchus = ootworld.parser.parse_rule('found_bombchus') wallet = ootworld.parser.parse_rule('Progressive_Wallet') wallet2 = ootworld.parser.parse_rule('(Progressive_Wallet, 2)') for location in filter(lambda location: location.item and location.item.type == 'Shop', ootworld.get_locations()): # Add wallet requirements if location.item.name in ['Buy Arrows (50)', 'Buy Fish', 'Buy Goron Tunic', 'Buy Bombchu (20)', 'Buy Bombs (30)']: add_rule(location, wallet) elif location.item.name in ['Buy Zora Tunic', 'Buy Blue Fire']: add_rule(location, wallet2) # Add adult only checks if location.item.name in ['Buy Goron Tunic', 'Buy Zora Tunic']: add_rule(location, ootworld.parser.parse_rule('is_adult', location)) # Add item prerequisite checks if location.item.name in ['Buy Blue Fire', 'Buy Blue Potion', 'Buy Bottle Bug', 'Buy Fish', 'Buy Green Potion', 'Buy Poe', 'Buy Red Potion [30]', 'Buy Red Potion [40]', 'Buy Red Potion [50]', 'Buy Fairy\'s Spirit']: add_rule(location, lambda state: CollectionState._oot_has_bottle(state, ootworld.player)) if location.item.name in ['Buy Bombchu (10)', 'Buy Bombchu (20)', 'Buy Bombchu (5)']: add_rule(location, found_bombchus) # This function should be ran once after setting up entrances and before placing items # The goal is to automatically set item rules based on age requirements in case entrances were shuffled def set_entrances_based_rules(ootworld): if ootworld.world.accessibility == 'beatable': return all_state = ootworld.world.get_all_state(False) for location in filter(lambda location: location.type == 'Shop', ootworld.get_locations()): # If a shop is not reachable as adult, it can't have Goron Tunic or Zora Tunic as child can't buy these if not all_state._oot_reach_as_age(location.parent_region.name, 'adult', ootworld.player): forbid_item(location, 'Buy Goron Tunic', ootworld.player) forbid_item(location, 'Buy Zora Tunic', ootworld.player) <file_sep>import os import shutil import sys import sysconfig from pathlib import Path import cx_Freeze from kivy_deps import sdl2, glew from Utils import version_tuple is_64bits = sys.maxsize > 2 ** 32 arch_folder = "exe.{platform}-{version}".format(platform=sysconfig.get_platform(), version=sysconfig.get_python_version()) buildfolder = Path("build", arch_folder) sbuildfolder = str(buildfolder) libfolder = Path(buildfolder, "lib") library = Path(libfolder, "library.zip") print("Outputting to: " + sbuildfolder) icon = os.path.join("data", "icon.ico") mcicon = os.path.join("data", "mcicon.ico") if os.path.exists("X:/pw.txt"): print("Using signtool") with open("X:/pw.txt") as f: pw = f.read() signtool = r'signtool sign /f X:/_SITS_Zertifikat_.pfx /p ' + pw + r' /fd sha256 /tr http://timestamp.digicert.com/ ' else: signtool = None from hashlib import sha3_512 import base64 def _threaded_hash(filepath): hasher = sha3_512() hasher.update(open(filepath, "rb").read()) return base64.b85encode(hasher.digest()).decode() os.makedirs(buildfolder, exist_ok=True) def manifest_creation(folder, create_hashes=False): # Since the setup is now split into components and the manifest is not, # it makes most sense to just remove the hashes for now. Not aware of anyone using them. hashes = {} manifestpath = os.path.join(folder, "manifest.json") if create_hashes: from concurrent.futures import ThreadPoolExecutor pool = ThreadPoolExecutor() for dirpath, dirnames, filenames in os.walk(folder): for filename in filenames: path = os.path.join(dirpath, filename) hashes[os.path.relpath(path, start=folder)] = pool.submit(_threaded_hash, path) import json manifest = { "buildtime": buildtime.isoformat(sep=" ", timespec="seconds"), "hashes": {path: hash.result() for path, hash in hashes.items()}, "version": version_tuple} json.dump(manifest, open(manifestpath, "wt"), indent=4) print("Created Manifest") def remove_sprites_from_folder(folder): for file in os.listdir(folder): if file != ".gitignore": os.remove(folder / file) scripts = { # Core "MultiServer.py": ("ArchipelagoServer", False, icon), "Generate.py": ("ArchipelagoGenerate", False, icon), "CommonClient.py": ("ArchipelagoTextClient", True, icon), # LttP "LttPClient.py": ("ArchipelagoLttPClient", True, icon), "LttPAdjuster.py": ("ArchipelagoLttPAdjuster", True, icon), # Factorio "FactorioClient.py": ("ArchipelagoFactorioClient", True, icon), # Minecraft "MinecraftClient.py": ("ArchipelagoMinecraftClient", False, mcicon), } exes = [] for script, (scriptname, gui, icon) in scripts.items(): exes.append(cx_Freeze.Executable( script=script, target_name=scriptname + ("" if sys.platform == "linux" else ".exe"), icon=icon, base="Win32GUI" if sys.platform == "win32" and gui else None )) import datetime buildtime = datetime.datetime.utcnow() cx_Freeze.setup( name="Archipelago", version=f"{version_tuple.major}.{version_tuple.minor}.{version_tuple.build}", description="Archipelago", executables=exes, options={ "build_exe": { "packages": ["websockets", "worlds", "kivy"], "includes": [], "excludes": ["numpy", "Cython", "PySide2", "PIL", "pandas"], "zip_include_packages": ["*"], "zip_exclude_packages": ["worlds", "kivy"], "include_files": [], "include_msvcr": False, "replace_paths": [("*", "")], "optimize": 1, "build_exe": buildfolder }, }, ) def installfile(path, keep_content=False): lbuildfolder = buildfolder print('copying', path, '->', lbuildfolder) if path.is_dir(): lbuildfolder /= path.name if lbuildfolder.is_dir() and not keep_content: shutil.rmtree(lbuildfolder) shutil.copytree(path, lbuildfolder, dirs_exist_ok=True) elif path.is_file(): shutil.copy(path, lbuildfolder) else: print('Warning,', path, 'not found') for folder in sdl2.dep_bins + glew.dep_bins: shutil.copytree(folder, libfolder, dirs_exist_ok=True) print('copying', folder, '->', libfolder) extra_data = ["LICENSE", "data", "EnemizerCLI", "host.yaml", "SNI", "meta.yaml"] for data in extra_data: installfile(Path(data)) os.makedirs(buildfolder / "Players", exist_ok=True) from WebHostLib.options import create create() from worlds.AutoWorld import AutoWorldRegister for worldname, worldtype in AutoWorldRegister.world_types.items(): if not worldtype.hidden: file_name = worldname+".yaml" shutil.copyfile(os.path.join("WebHostLib", "static", "generated", "configs", file_name), buildfolder / "Players" / file_name) try: from maseya import z3pr except ImportError: print("Maseya Palette Shuffle not found, skipping data files.") else: # maseya Palette Shuffle exists and needs its data files print("Maseya Palette Shuffle found, including data files...") file = z3pr.__file__ installfile(Path(os.path.dirname(file)) / "data", keep_content=True) if signtool: for exe in exes: print(f"Signing {exe.target_name}") os.system(signtool + os.path.join(buildfolder, exe.target_name)) print(f"Signing SNI") os.system(signtool + os.path.join(buildfolder, "SNI", "SNI.exe")) print(f"Signing OoT Utils") for exe_path in (("Compress", "Compress.exe"), ("Decompress", "Decompress.exe")): os.system(signtool + os.path.join(buildfolder, "lib", "worlds", "oot", "data", *exe_path)) remove_sprites_from_folder(buildfolder / "data" / "sprites" / "alttpr") manifest_creation(buildfolder) <file_sep>from typing import Dict from BaseClasses import MultiWorld from Options import Toggle class StartWithJewelryBox(Toggle): "Start with Jewelry Box unlocked" display_name = "Start with Jewelry Box" #class ProgressiveVerticalMovement(Toggle): # "Always find vertical movement in the following order Succubus Hairpin -> Light Wall -> Celestial Sash" # display_name = "Progressive vertical movement" #class ProgressiveKeycards(Toggle): # "Always find Security Keycard's in the following order D -> C -> B -> A" # display_name = "Progressive keycards" class DownloadableItems(Toggle): "With the tablet you will be able to download items at terminals" display_name = "Downloadable items" class FacebookMode(Toggle): "Requires Oculus Rift(ng) to spot the weakspots in walls and floors" display_name = "Facebook mode" class StartWithMeyef(Toggle): "Start with Meyef, ideal for when you want to play multiplayer." display_name = "Start with Meyef" class QuickSeed(Toggle): "Start with Talaria Attachment, Nyoom!" display_name = "Quick seed" class SpecificKeycards(Toggle): "Keycards can only open corresponding doors" display_name = "Specific Keycards" class Inverted(Toggle): "Start in the past" display_name = "Inverted" #class StinkyMaw(Toggle): # "Require gasmask for Maw" # display_name = "Stinky Maw" # Some options that are available in the timespinner randomizer arent currently implemented timespinner_options: Dict[str, Toggle] = { "StartWithJewelryBox": StartWithJewelryBox, #"ProgressiveVerticalMovement": ProgressiveVerticalMovement, #"ProgressiveKeycards": ProgressiveKeycards, "DownloadableItems": DownloadableItems, "FacebookMode": FacebookMode, "StartWithMeyef": StartWithMeyef, "QuickSeed": QuickSeed, "SpecificKeycards": SpecificKeycards, "Inverted": Inverted, #"StinkyMaw": StinkyMaw } def is_option_enabled(world: MultiWorld, player: int, name: str) -> bool: option = getattr(world, name, None) if option == None: return False return int(option[player].value) > 0<file_sep>"""Outputs a Factorio Mod to facilitate integration with Archipelago""" import os import zipfile from typing import Optional import threading import json import jinja2 import Utils import shutil from . import Options from BaseClasses import MultiWorld from .Technologies import tech_table, rocket_recipes, recipes, free_sample_blacklist, progressive_technology_table, \ base_tech_table, tech_to_progressive_lookup, progressive_tech_table template_env: Optional[jinja2.Environment] = None data_template: Optional[jinja2.Template] = None data_final_template: Optional[jinja2.Template] = None locale_template: Optional[jinja2.Template] = None control_template: Optional[jinja2.Template] = None template_load_lock = threading.Lock() base_info = { "version": Utils.__version__, "title": "Archipelago", "author": "Berserker", "homepage": "https://archipelago.gg", "description": "Integration client for the Archipelago Randomizer", "factorio_version": "1.1" } recipe_time_scales = { # using random.triangular Options.RecipeTime.option_fast: (0.25, 1), # 0.5, 2, 0.5 average -> 1.0 Options.RecipeTime.option_normal: (0.5, 2, 0.5), Options.RecipeTime.option_slow: (1, 4), # 0.25, 4, 0.25 average -> 1.5 Options.RecipeTime.option_chaos: (0.25, 4, 0.25), Options.RecipeTime.option_vanilla: None } def generate_mod(world, output_directory: str): player = world.player multiworld = world.world global data_final_template, locale_template, control_template, data_template with template_load_lock: if not data_final_template: mod_template_folder = os.path.join(os.path.dirname(__file__), "data", "mod_template") template_env: Optional[jinja2.Environment] = \ jinja2.Environment(loader=jinja2.FileSystemLoader([mod_template_folder])) data_template = template_env.get_template("data.lua") data_final_template = template_env.get_template("data-final-fixes.lua") locale_template = template_env.get_template(r"locale/en/locale.cfg") control_template = template_env.get_template("control.lua") # get data for templates player_names = {x: multiworld.player_name[x] for x in multiworld.player_ids} locations = [] for location in multiworld.get_filled_locations(player): if location.address: locations.append((location.name, location.item.name, location.item.player, location.item.advancement)) mod_name = f"AP-{multiworld.seed_name}-P{player}-{multiworld.player_name[player]}" tech_cost_scale = {0: 0.1, 1: 0.25, 2: 0.5, 3: 1, 4: 2, 5: 5, 6: 10}[multiworld.tech_cost[player].value] random = multiworld.slot_seeds[player] def flop_random(low, high, base=None): """Guarentees 50% below base and 50% above base, uniform distribution in each direction.""" if base: distance = random.random() if random.randint(0, 1): return base + (high-base) * distance else: return base - (base-low) * distance return random.uniform(low, high) template_data = {"locations": locations, "player_names": player_names, "tech_table": tech_table, "base_tech_table": base_tech_table, "tech_to_progressive_lookup": tech_to_progressive_lookup, "mod_name": mod_name, "allowed_science_packs": multiworld.max_science_pack[player].get_allowed_packs(), "tech_cost_scale": tech_cost_scale, "custom_technologies": multiworld.worlds[player].custom_technologies, "tech_tree_layout_prerequisites": multiworld.tech_tree_layout_prerequisites[player], "slot_name": multiworld.player_name[player], "seed_name": multiworld.seed_name, "starting_items": multiworld.starting_items[player], "recipes": recipes, "random": random, "flop_random": flop_random, "static_nodes": multiworld.worlds[player].static_nodes, "recipe_time_scale": recipe_time_scales[multiworld.recipe_time[player].value], "free_sample_blacklist": {item : 1 for item in free_sample_blacklist}, "progressive_technology_table": {tech.name : tech.progressive for tech in progressive_technology_table.values()}, "custom_recipes": world.custom_recipes} for factorio_option in Options.factorio_options: template_data[factorio_option] = getattr(multiworld, factorio_option)[player].value if getattr(multiworld, "silo")[player].value == Options.Silo.option_randomize_recipe: template_data["free_sample_blacklist"]["rocket-silo"] = 1 control_code = control_template.render(**template_data) data_template_code = data_template.render(**template_data) data_final_fixes_code = data_final_template.render(**template_data) mod_dir = os.path.join(output_directory, mod_name + "_" + Utils.__version__) en_locale_dir = os.path.join(mod_dir, "locale", "en") os.makedirs(en_locale_dir, exist_ok=True) shutil.copytree(os.path.join(os.path.dirname(__file__), "data", "mod"), mod_dir, dirs_exist_ok=True) with open(os.path.join(mod_dir, "data.lua"), "wt") as f: f.write(data_template_code) with open(os.path.join(mod_dir, "data-final-fixes.lua"), "wt") as f: f.write(data_final_fixes_code) with open(os.path.join(mod_dir, "control.lua"), "wt") as f: f.write(control_code) locale_content = locale_template.render(**template_data) with open(os.path.join(en_locale_dir, "locale.cfg"), "wt") as f: f.write(locale_content) info = base_info.copy() info["name"] = mod_name with open(os.path.join(mod_dir, "info.json"), "wt") as f: json.dump(info, f, indent=4) # zip the result zf_path = os.path.join(mod_dir + ".zip") with zipfile.ZipFile(zf_path, compression=zipfile.ZIP_DEFLATED, mode='w') as zf: for root, dirs, files in os.walk(mod_dir): for file in files: zf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), os.path.join(mod_dir, '..'))) shutil.rmtree(mod_dir) <file_sep>def create_regions(world, player: int): from . import create_region from .Locations import lookup_name_to_id as location_lookup_name_to_id world.regions += [ create_region(world, player, 'Menu', None, ['Lifepod 5']), create_region(world, player, 'Planet 4546B', [location for location in location_lookup_name_to_id]) ] <file_sep>from typing import Tuple from BaseClasses import MultiWorld from .Options import is_option_enabled def get_pyramid_keys_unlock(world: MultiWorld, player: int) -> str: present_teleportation_gates: Tuple[str, ...] = ( "GateKittyBoss", "GateLeftLibrary", "GateMilitairyGate", "GateSealedCaves", "GateSealedSirensCave", "GateLakeDesolation" ) past_teleportation_gates: Tuple[str, ...] = ( "GateLakeSirineRight", "GateAccessToPast", "GateCastleRamparts", "GateCastleKeep", "GateRoyalTowers", "GateMaw", "GateCavesOfBanishment" ) if is_option_enabled(world, player, "Inverted"): gates = present_teleportation_gates else: gates = (*past_teleportation_gates, *present_teleportation_gates) return world.random.choice(gates)<file_sep>from argparse import Namespace from BaseClasses import MultiWorld from worlds.alttp.Dungeons import create_dungeons, get_dungeon_item_pool from worlds.alttp.EntranceShuffle import link_inverted_entrances from worlds.alttp.InvertedRegions import create_inverted_regions from worlds.alttp.ItemPool import difficulties from worlds.alttp.Items import ItemFactory from worlds.alttp.Regions import mark_light_world_regions from worlds.alttp.Shops import create_shops from test.TestBase import TestBase from worlds import AutoWorld class TestInverted(TestBase): def setUp(self): self.world = MultiWorld(1) args = Namespace() for name, option in AutoWorld.AutoWorldRegister.world_types["A Link to the Past"].options.items(): setattr(args, name, {1: option.from_any(option.default)}) self.world.set_options(args) self.world.set_default_common_options() self.world.difficulty_requirements[1] = difficulties['normal'] self.world.mode[1] = "inverted" create_inverted_regions(self.world, 1) create_dungeons(self.world, 1) create_shops(self.world, 1) link_inverted_entrances(self.world, 1) self.world.worlds[1].create_items() self.world.required_medallions[1] = ['Ether', 'Quake'] self.world.itempool.extend(get_dungeon_item_pool(self.world)) self.world.itempool.extend(ItemFactory(['Green Pendant', 'Red Pendant', 'Blue Pendant', 'Beat Agahnim 1', 'Beat Agahnim 2', 'Crystal 1', 'Crystal 2', 'Crystal 3', 'Crystal 4', 'Crystal 5', 'Crystal 6', 'Crystal 7'], 1)) self.world.get_location('Agahnim 1', 1).item = None self.world.get_location('Agahnim 2', 1).item = None mark_light_world_regions(self.world, 1) self.world.worlds[1].set_rules() <file_sep>from __future__ import annotations import typing from Options import Choice, OptionDict, ItemDict, Option, DefaultOnToggle, Range, DeathLink from schema import Schema, Optional, And, Or # schema helpers FloatRange = lambda low, high: And(Or(int, float), lambda f: low <= f <= high) LuaBool = Or(bool, And(int, lambda n: n in (0, 1))) class MaxSciencePack(Choice): """Maximum level of science pack required to complete the game.""" displayname = "Maximum Required Science Pack" option_automation_science_pack = 0 option_logistic_science_pack = 1 option_military_science_pack = 2 option_chemical_science_pack = 3 option_production_science_pack = 4 option_utility_science_pack = 5 option_space_science_pack = 6 default = 6 def get_allowed_packs(self): return {option.replace("_", "-") for option, value in self.options.items() if value <= self.value} - \ {"space-science-pack"} # with rocket launch being the goal, post-launch techs don't make sense @classmethod def get_ordered_science_packs(cls): return [option.replace("_", "-") for option, value in sorted(cls.options.items(), key=lambda pair: pair[1])] def get_max_pack(self): return self.get_ordered_science_packs()[self.value].replace("_", "-") class TechCost(Choice): """How expensive are the technologies.""" displayname = "Technology Cost Scale" option_very_easy = 0 option_easy = 1 option_kind = 2 option_normal = 3 option_hard = 4 option_very_hard = 5 option_insane = 6 default = 3 class Silo(Choice): """Ingredients to craft rocket silo or auto-place if set to spawn.""" displayname = "Rocket Silo" option_vanilla = 0 option_randomize_recipe = 1 option_spawn = 2 default = 0 class FreeSamples(Choice): """Get free items with your technologies.""" displayname = "Free Samples" option_none = 0 option_single_craft = 1 option_half_stack = 2 option_stack = 3 default = 3 class TechTreeLayout(Choice): """Selects how the tech tree nodes are interwoven.""" displayname = "Technology Tree Layout" option_single = 0 option_small_diamonds = 1 option_medium_diamonds = 2 option_large_diamonds = 3 option_small_pyramids = 4 option_medium_pyramids = 5 option_large_pyramids = 6 option_small_funnels = 7 option_medium_funnels = 8 option_large_funnels = 9 default = 0 class TechTreeInformation(Choice): """How much information should be displayed in the tech tree.""" displayname = "Technology Tree Information" option_none = 0 option_advancement = 1 option_full = 2 default = 2 class RecipeTime(Choice): """randomize the time it takes for any recipe to craft, this includes smelting, chemical lab, hand crafting etc.""" displayname = "Recipe Time" option_vanilla = 0 option_fast = 1 option_normal = 2 option_slow = 4 option_chaos = 5 class Progressive(Choice): displayname = "Progressive Technologies" option_off = 0 option_grouped_random = 1 option_on = 2 alias_false = 0 alias_true = 2 default = 2 def want_progressives(self, random): return random.choice([True, False]) if self.value == self.option_grouped_random else bool(self.value) class RecipeIngredients(Choice): """Select if rocket, or rocket + science pack ingredients should be random.""" displayname = "Random Recipe Ingredients Level" option_rocket = 0 option_science_pack = 1 class FactorioStartItems(ItemDict): displayname = "Starting Items" verify_item_name = False default = {"burner-mining-drill": 19, "stone-furnace": 19} class TrapCount(Range): range_end = 4 class AttackTrapCount(TrapCount): """Trap items that when received trigger an attack on your base.""" displayname = "Attack Traps" class EvolutionTrapCount(TrapCount): """Trap items that when received increase the enemy evolution.""" displayname = "Evolution Traps" class EvolutionTrapIncrease(Range): displayname = "Evolution Trap % Effect" range_start = 1 default = 10 range_end = 100 class FactorioWorldGen(OptionDict): displayname = "World Generation" # FIXME: do we want default be a rando-optimized default or in-game DS? value: typing.Dict[str, typing.Dict[str, typing.Any]] default = { "terrain_segmentation": 0.5, "water": 1.5, "autoplace_controls": { "coal": {"frequency": 1, "size": 3, "richness": 6}, "copper-ore": {"frequency": 1, "size": 3, "richness": 6}, "crude-oil": {"frequency": 1, "size": 3, "richness": 6}, "enemy-base": {"frequency": 1, "size": 1, "richness": 1}, "iron-ore": {"frequency": 1, "size": 3, "richness": 6}, "stone": {"frequency": 1, "size": 3, "richness": 6}, "trees": {"frequency": 1, "size": 1, "richness": 1}, "uranium-ore": {"frequency": 1, "size": 3, "richness": 6} }, "seed": None, "starting_area": 1, "peaceful_mode": False, "cliff_settings": { "name": "cliff", "cliff_elevation_0": 10, "cliff_elevation_interval": 40, "richness": 1 }, "property_expression_names": { "control-setting:moisture:bias": 0, "control-setting:moisture:frequency:multiplier": 1, "control-setting:aux:bias": 0, "control-setting:aux:frequency:multiplier": 1 }, "pollution": { "enabled": True, "diffusion_ratio": 0.02, "ageing": 1, "enemy_attack_pollution_consumption_modifier": 1, "min_pollution_to_damage_trees": 60, "pollution_restored_per_tree_damage": 10 }, "enemy_evolution": { "enabled": True, "time_factor": 40.0e-7, "destroy_factor": 200.0e-5, "pollution_factor": 9.0e-7 }, "enemy_expansion": { "enabled": True, "max_expansion_distance": 7, "settler_group_min_size": 5, "settler_group_max_size": 20, "min_expansion_cooldown": 14400, "max_expansion_cooldown": 216000 } } schema = Schema({ "basic": { Optional("terrain_segmentation"): FloatRange(0.166, 6), Optional("water"): FloatRange(0.166, 6), Optional("autoplace_controls"): { str: { "frequency": FloatRange(0, 6), "size": FloatRange(0, 6), "richness": FloatRange(0.166, 6) } }, Optional("seed"): Or(None, And(int, lambda n: n >= 0)), Optional("starting_area"): FloatRange(0.166, 6), Optional("peaceful_mode"): LuaBool, Optional("cliff_settings"): { "name": str, "cliff_elevation_0": FloatRange(0, 99), "cliff_elevation_interval": FloatRange(0.066, 241), # 40/frequency "richness": FloatRange(0, 6) }, Optional("property_expression_names"): Schema({ "control-setting:moisture:bias": FloatRange(-0.5, 0.5), "control-setting:moisture:frequency:multiplier": FloatRange(0.166, 6), "control-setting:aux:bias": FloatRange(-0.5, 0.5), "control-setting:aux:frequency:multiplier": FloatRange(0.166, 6) }, ignore_extra_keys=True) }, "advanced": { Optional("pollution"): { Optional("enabled"): LuaBool, Optional("diffusion_ratio"): FloatRange(0, 0.25), Optional("ageing"): FloatRange(0.1, 4), Optional("enemy_attack_pollution_consumption_modifier"): FloatRange(0.1, 4), Optional("min_pollution_to_damage_trees"): FloatRange(0, 9999), Optional("pollution_restored_per_tree_damage"): FloatRange(0, 9999) }, Optional("enemy_evolution"): { Optional("enabled"): LuaBool, Optional("time_factor"): FloatRange(0, 1000e-7), Optional("destroy_factor"): FloatRange(0, 1000e-5), Optional("pollution_factor"): FloatRange(0, 1000e-7), }, Optional("enemy_expansion"): { Optional("enabled"): LuaBool, Optional("max_expansion_distance"): FloatRange(2, 20), Optional("settler_group_min_size"): FloatRange(1, 20), Optional("settler_group_max_size"): FloatRange(1, 50), Optional("min_expansion_cooldown"): FloatRange(3600, 216000), Optional("max_expansion_cooldown"): FloatRange(18000, 648000) } } }) def __init__(self, value: typing.Dict[str, typing.Any]): advanced = {"pollution", "enemy_evolution", "enemy_expansion"} self.value = { "basic": {key: value[key] for key in value.keys() - advanced}, "advanced": {key: value[key] for key in value.keys() & advanced} } # verify min_values <= max_values def optional_min_lte_max(container, min_key, max_key): min_val = container.get(min_key, None) max_val = container.get(max_key, None) if min_val is not None and max_val is not None and min_val > max_val: raise ValueError(f"{min_key} can't be bigger than {max_key}") enemy_expansion = self.value["advanced"].get("enemy_expansion", {}) optional_min_lte_max(enemy_expansion, "settler_group_min_size", "settler_group_max_size") optional_min_lte_max(enemy_expansion, "min_expansion_cooldown", "max_expansion_cooldown") @classmethod def from_any(cls, data: typing.Dict[str, typing.Any]) -> FactorioWorldGen: if type(data) == dict: return cls(data) else: raise NotImplementedError(f"Cannot Convert from non-dictionary, got {type(data)}") class ImportedBlueprint(DefaultOnToggle): displayname = "Blueprints" factorio_options: typing.Dict[str, type(Option)] = { "max_science_pack": MaxSciencePack, "tech_tree_layout": TechTreeLayout, "tech_cost": TechCost, "silo": Silo, "free_samples": FreeSamples, "tech_tree_information": TechTreeInformation, "starting_items": FactorioStartItems, "recipe_time": RecipeTime, "recipe_ingredients": RecipeIngredients, "imported_blueprints": ImportedBlueprint, "world_gen": FactorioWorldGen, "progressive": Progressive, "evolution_traps": EvolutionTrapCount, "attack_traps": AttackTrapCount, "evolution_trap_increase": EvolutionTrapIncrease, "death_link": DeathLink } <file_sep>import typing from Options import Option, DefaultOnToggle, Range, Choice class TotalLocations(Range): """Number of location checks which are added to the Risk of Rain playthrough.""" displayname = "Total Locations" range_start = 10 range_end = 100 default = 20 class TotalRevivals(Range): """Number of `Dio's Best Friend` item put in the item pool.""" displayname = "Total Revivals Available" range_start = 0 range_end = 10 default = 4 class ItemPickupStep(Range): """Number of items to pick up before an AP Check is completed. Setting to 1 means every other pickup. Setting to 2 means every third pickup. So on...""" displayname = "Item Pickup Step" range_start = 0 range_end = 5 default = 2 class AllowLunarItems(DefaultOnToggle): """Allows Lunar items in the item pool.""" displayname = "Enable Lunar Item Shuffling" class StartWithRevive(DefaultOnToggle): """Start the game with a `Dio's Best Friend` item.""" displayname = "Start with a Revive" class GreenScrap(Range): """Weight of Green Scraps in the item pool.""" displayname = "Green Scraps" range_start = 0 range_end = 100 default = 16 class RedScrap(Range): """Weight of Red Scraps in the item pool.""" displayname = "Red Scraps" range_start = 0 range_end = 100 default = 4 class YellowScrap(Range): """Weight of yellow scraps in the item pool.""" displayname = "Yellow Scraps" range_start = 0 range_end = 100 default = 1 class WhiteScrap(Range): """Weight of white scraps in the item pool.""" displayname = "White Scraps" range_start = 0 range_end = 100 default = 32 class CommonItem(Range): """Weight of common items in the item pool.""" displayname = "Common Items" range_start = 0 range_end = 100 default = 64 class UncommonItem(Range): """Weight of uncommon items in the item pool.""" displayname = "Uncommon Items" range_start = 0 range_end = 100 default = 32 class LegendaryItem(Range): """Weight of legendary items in the item pool.""" displayname = "Legendary Items" range_start = 0 range_end = 100 default = 8 class BossItem(Range): """Weight of boss items in the item pool.""" displayname = "Boss Items" range_start = 0 range_end = 100 default = 4 class LunarItem(Range): """Weight of lunar items in the item pool.""" displayname = "Lunar Items" range_start = 0 range_end = 100 default = 16 class Equipment(Range): """Weight of equipment items in the item pool.""" displayname = "Equipment" range_start = 0 range_end = 100 default = 32 class ItemPoolPresetToggle(DefaultOnToggle): """Will use the item weight presets when set to true, otherwise will use the custom set item pool weights.""" displayname = "Item Weight Presets" class ItemWeights(Choice): """Preset choices for determining the weights of the item pool.<br> New is a test for a potential adjustment to the default weights.<br> Uncommon puts a large number of uncommon items in the pool.<br> Legendary puts a large number of legendary items in the pool.<br> Lunartic makes everything a lunar item.<br> Chaos generates the pool completely at random with rarer items having a slight cap to prevent this option being too easy.<br> No Scraps removes all scrap items from the item pool.<br> Even generates the item pool with every item having an even weight.<br> Scraps Only will be only scrap items in the item pool.""" displayname = "Item Weights" option_default = 0 option_new = 1 option_uncommon = 2 option_legendary = 3 option_lunartic = 4 option_chaos = 5 option_no_scraps = 6 option_even = 7 option_scraps_only = 8 #define a dictionary for the weights of the generated item pool. ror2_weights: typing.Dict[str, type(Option)] = { "green_scrap": GreenScrap, "red_scrap": RedScrap, "yellow_scrap": YellowScrap, "white_scrap": WhiteScrap, "common_item": CommonItem, "uncommon_item": UncommonItem, "legendary_item": LegendaryItem, "boss_item": BossItem, "lunar_item": LunarItem, "equipment": Equipment } ror2_options: typing.Dict[str, type(Option)] = { "total_locations": TotalLocations, "total_revivals": TotalRevivals, "start_with_revive": StartWithRevive, "item_pickup_step": ItemPickupStep, "enable_lunar": AllowLunarItems, "item_weights": ItemWeights, "item_pool_presets": ItemPoolPresetToggle, **ror2_weights }<file_sep># Risk of Rain 2 ## Where is the settings page? The player settings page for this game is located <a href="../player-settings">here</a>. It contains all the options you need to configure and export a config file. ## What does randomization do to this game? Risk of Rain is already a random game, by virtue of being a roguelite. The Archipelago mod implements pure multiworld functionality in which certain chests (made clear via a location check progress bar) will send an item out to the multiworld. The items that _would have been_ in those chests will be returned to the Risk of Rain player via grants by other players in other worlds. ## What Risk of Rain items can appear in other players' worlds? The Risk of Rain items are: * `Common Item` (White items) * `Uncommon Item` (Green items) * `Boss Item` (Yellow items) * `Legendary Item` (Red items) * `Lunar Item` (Blue items) * `Equipment` (Orange items) * `Dio's Best Friend` (Used if you set the YAML setting `total_revives_available` above `0`) Each item grants you a random in-game item from the category it belongs to. When an item is granted by another world to the Risk of Rain player (one of the items listed above) then a random in-game item of that tier will appear in the Risk of Rain player's inventory. If the item grant is an `Equipment` and the player already has an equipment item equipped then the _item that was equipped_ will be dropped on the ground and _the new equipment_ will take it's place. (If you want the old one back, pick it up.) ## What does another world's item look like in Risk of Rain? When the Risk of Rain player fills up their location check bar then the next spawned item will become an item grant for another player's world. The item in Risk of Rain will disappear in a poof of smoke and the grant will automatically go out to the multiworld. ## What is the item pickup step? The item pickup step is a YAML setting which allows you to set how many items you need to spawn before the _next_ item that is spawned disappears (in a poof of smoke) and goes out to the multiworld. <file_sep>import collections from ..AutoWorld import World from BaseClasses import Region, Entrance, Location, Item from .Technologies import base_tech_table, recipe_sources, base_technology_table, advancement_technologies, \ all_ingredient_names, all_product_sources, required_technologies, get_rocket_requirements, rocket_recipes, \ progressive_technology_table, common_tech_table, tech_to_progressive_lookup, progressive_tech_table, \ get_science_pack_pools, Recipe, recipes, technology_table, tech_table, factorio_base_id, useless_technologies from .Shapes import get_shapes from .Mod import generate_mod from .Options import factorio_options, Silo, TechTreeInformation import logging class FactorioItem(Item): game = "Factorio" all_items = tech_table.copy() all_items["Attack Trap"] = factorio_base_id - 1 all_items["Evolution Trap"] = factorio_base_id - 2 class Factorio(World): """ Factorio is a game about automation. You play as an engineer who has crash landed on the planet Nauvis, an inhospitable world filled with dangerous creatures called biters. Build a factory, research new technologies, and become more efficient in your quest to build a rocket and return home. """ game: str = "Factorio" static_nodes = {"automation", "logistics", "rocket-silo"} custom_recipes = {} additional_advancement_technologies = set() item_name_to_id = all_items location_name_to_id = base_tech_table data_version = 5 def generate_basic(self): player = self.player want_progressives = collections.defaultdict(lambda: self.world.progressive[player]. want_progressives(self.world.random)) skip_silo = self.world.silo[player].value == Silo.option_spawn evolution_traps_wanted = self.world.evolution_traps[player].value attack_traps_wanted = self.world.attack_traps[player].value traps_wanted = ["Evolution Trap"] * evolution_traps_wanted + ["Attack Trap"] * attack_traps_wanted self.world.random.shuffle(traps_wanted) for tech_name in base_tech_table: if traps_wanted and tech_name in useless_technologies: self.world.itempool.append(self.create_item(traps_wanted.pop())) elif skip_silo and tech_name == "rocket-silo": pass else: progressive_item_name = tech_to_progressive_lookup.get(tech_name, tech_name) want_progressive = want_progressives[progressive_item_name] item_name = progressive_item_name if want_progressive else tech_name tech_item = self.create_item(item_name) if tech_name in self.static_nodes: self.world.get_location(tech_name, player).place_locked_item(tech_item) else: self.world.itempool.append(tech_item) map_basic_settings = self.world.world_gen[player].value["basic"] if map_basic_settings.get("seed", None) is None: # allow seed 0 map_basic_settings["seed"] = self.world.slot_seeds[player].randint(0, 2 ** 32 - 1) # 32 bit uint self.sending_visible = self.world.tech_tree_information[player] == TechTreeInformation.option_full generate_output = generate_mod def create_regions(self): player = self.player menu = Region("Menu", None, "Menu", player, self.world) crash = Entrance(player, "Crash Land", menu) menu.exits.append(crash) nauvis = Region("Nauvis", None, "Nauvis", player, self.world) skip_silo = self.world.silo[self.player].value == Silo.option_spawn for tech_name, tech_id in base_tech_table.items(): if skip_silo and tech_name == "rocket-silo": continue tech = Location(player, tech_name, tech_id, nauvis) nauvis.locations.append(tech) tech.game = "Factorio" location = Location(player, "Rocket Launch", None, nauvis) nauvis.locations.append(location) location.game = "Factorio" event = Item("Victory", True, None, player) event.game = "Factorio" self.world.push_item(location, event, False) location.event = location.locked = True for ingredient in self.world.max_science_pack[self.player].get_allowed_packs(): location = Location(player, f"Automate {ingredient}", None, nauvis) location.game = "Factorio" nauvis.locations.append(location) event = Item(f"Automated {ingredient}", True, None, player) self.world.push_item(location, event, False) location.event = location.locked = True crash.connect(nauvis) self.world.regions += [menu, nauvis] def set_rules(self): world = self.world player = self.player self.custom_technologies = self.set_custom_technologies() self.set_custom_recipes() shapes = get_shapes(self) if world.logic[player] != 'nologic': from worlds.generic import Rules for ingredient in self.world.max_science_pack[self.player].get_allowed_packs(): location = world.get_location(f"Automate {ingredient}", player) if self.world.recipe_ingredients[self.player]: custom_recipe = self.custom_recipes[ingredient] location.access_rule = lambda state, ingredient=ingredient, custom_recipe=custom_recipe: \ (ingredient not in technology_table or state.has(ingredient, player)) and \ all(state.has(technology.name, player) for sub_ingredient in custom_recipe.ingredients for technology in required_technologies[sub_ingredient]) else: location.access_rule = lambda state, ingredient=ingredient: \ all(state.has(technology.name, player) for technology in required_technologies[ingredient]) skip_silo = self.world.silo[self.player].value == Silo.option_spawn for tech_name, technology in self.custom_technologies.items(): if skip_silo and tech_name == "rocket-silo": continue location = world.get_location(tech_name, player) Rules.set_rule(location, technology.build_rule(player)) prequisites = shapes.get(tech_name) if prequisites: locations = {world.get_location(requisite, player) for requisite in prequisites} Rules.add_rule(location, lambda state, locations=locations: all(state.can_reach(loc) for loc in locations)) silo_recipe = None if self.world.silo[self.player].value == Silo.option_spawn \ else self.custom_recipes["rocket-silo"] \ if "rocket-silo" in self.custom_recipes \ else next(iter(all_product_sources.get("rocket-silo"))) part_recipe = self.custom_recipes["rocket-part"] victory_tech_names = get_rocket_requirements(silo_recipe, part_recipe) world.get_location("Rocket Launch", player).access_rule = lambda state: all(state.has(technology, player) for technology in victory_tech_names) world.completion_condition[player] = lambda state: state.has('Victory', player) def collect_item(self, state, item, remove=False): if item.advancement and item.name in progressive_technology_table: prog_table = progressive_technology_table[item.name].progressive if remove: for item_name in reversed(prog_table): if state.has(item_name, item.player): return item_name else: for item_name in prog_table: if not state.has(item_name, item.player): return item_name return super(Factorio, self).collect_item(state, item, remove) def get_required_client_version(self) -> tuple: return max((0, 1, 6), super(Factorio, self).get_required_client_version()) options = factorio_options @classmethod def stage_write_spoiler(cls, world, spoiler_handle): factorio_players = world.get_game_players(cls.game) spoiler_handle.write('\n\nFactorio Recipes:\n') for player in factorio_players: name = world.get_player_name(player) for recipe in world.worlds[player].custom_recipes.values(): spoiler_handle.write(f"\n{recipe.name} ({name}): {recipe.ingredients} -> {recipe.products}") def make_balanced_recipe(self, original: Recipe, pool: list, factor: float = 1) -> Recipe: """Generate a recipe from pool with time and cost similar to original * factor""" new_ingredients = {} self.world.random.shuffle(pool) target_raw = int(sum((count for ingredient, count in original.base_cost.items())) * factor) target_energy = original.total_energy * factor target_num_ingredients = len(original.ingredients) remaining_raw = target_raw remaining_energy = target_energy remaining_num_ingredients = target_num_ingredients fallback_pool = [] # fill all but one slot with random ingredients, last with a good match while remaining_num_ingredients > 0 and len(pool) > 0: if remaining_num_ingredients == 1: max_raw = 1.1 * remaining_raw min_raw = 0.9 * remaining_raw max_energy = 1.1 * remaining_energy min_energy = 1.1 * remaining_energy else: max_raw = remaining_raw * 0.75 min_raw = (remaining_raw - max_raw) / remaining_num_ingredients max_energy = remaining_energy * 0.75 min_energy = (remaining_energy - max_energy) / remaining_num_ingredients ingredient = pool.pop() if ingredient in all_product_sources: ingredient_recipe = min(all_product_sources[ingredient], key=lambda recipe: recipe.rel_cost) ingredient_raw = sum((count for ingredient, count in ingredient_recipe.base_cost.items())) ingredient_energy = ingredient_recipe.total_energy else: # assume simple ore TODO: remove if tree when mining data is harvested from Factorio ingredient_raw = 1 ingredient_energy = 2 min_num_raw = min_raw / ingredient_raw max_num_raw = max_raw / ingredient_raw min_num_energy = min_energy / ingredient_energy max_num_energy = max_energy / ingredient_energy min_num = int(max(1, min_num_raw, min_num_energy)) max_num = int(min(1000, max_num_raw, max_num_energy)) if min_num > max_num: fallback_pool.append(ingredient) continue # can't use that ingredient num = self.world.random.randint(min_num, max_num) new_ingredients[ingredient] = num remaining_raw -= num * ingredient_raw remaining_energy -= num * ingredient_energy remaining_num_ingredients -= 1 # fill failed slots with whatever we got pool = fallback_pool while remaining_num_ingredients > 0 and len(pool) > 0: ingredient = pool.pop() if ingredient not in recipes: logging.warning(f"missing recipe for {ingredient}") continue ingredient_recipe = recipes[ingredient] ingredient_raw = sum((count for ingredient, count in ingredient_recipe.base_cost.items())) ingredient_energy = ingredient_recipe.total_energy num_raw = remaining_raw / ingredient_raw / remaining_num_ingredients num_energy = remaining_energy / ingredient_energy / remaining_num_ingredients num = int(min(num_raw, num_energy)) if num < 1: continue new_ingredients[ingredient] = num remaining_raw -= num * ingredient_raw remaining_energy -= num * ingredient_energy remaining_num_ingredients -= 1 if remaining_num_ingredients > 1: logging.warning("could not randomize recipe") return Recipe(original.name, original.category, new_ingredients, original.products, original.energy) def set_custom_technologies(self): custom_technologies = {} allowed_packs = self.world.max_science_pack[self.player].get_allowed_packs() for technology_name, technology in base_technology_table.items(): custom_technologies[technology_name] = technology.get_custom(self.world, allowed_packs, self.player) return custom_technologies def set_custom_recipes(self): original_rocket_part = recipes["rocket-part"] science_pack_pools = get_science_pack_pools() valid_pool = sorted(science_pack_pools[self.world.max_science_pack[self.player].get_max_pack()]) self.world.random.shuffle(valid_pool) self.custom_recipes = {"rocket-part": Recipe("rocket-part", original_rocket_part.category, {valid_pool[x]: 10 for x in range(3)}, original_rocket_part.products, original_rocket_part.energy)} self.additional_advancement_technologies = {tech.name for tech in self.custom_recipes["rocket-part"].recursive_unlocking_technologies} if self.world.recipe_ingredients[self.player]: valid_pool = [] for pack in self.world.max_science_pack[self.player].get_ordered_science_packs(): valid_pool += sorted(science_pack_pools[pack]) self.world.random.shuffle(valid_pool) if pack in recipes: # skips over space science pack original = recipes[pack] new_ingredients = {} for _ in original.ingredients: new_ingredients[valid_pool.pop()] = 1 new_recipe = Recipe(pack, original.category, new_ingredients, original.products, original.energy) self.additional_advancement_technologies |= {tech.name for tech in new_recipe.recursive_unlocking_technologies} self.custom_recipes[pack] = new_recipe if self.world.silo[self.player].value == Silo.option_randomize_recipe: valid_pool = [] for pack in sorted(self.world.max_science_pack[self.player].get_allowed_packs()): valid_pool += sorted(science_pack_pools[pack]) new_recipe = self.make_balanced_recipe(recipes["rocket-silo"], valid_pool, factor=(self.world.max_science_pack[self.player].value + 1) / 7) self.additional_advancement_technologies |= {tech.name for tech in new_recipe.recursive_unlocking_technologies} self.custom_recipes["rocket-silo"] = new_recipe # handle marking progressive techs as advancement prog_add = set() for tech in self.additional_advancement_technologies: if tech in tech_to_progressive_lookup: prog_add.add(tech_to_progressive_lookup[tech]) self.additional_advancement_technologies |= prog_add def create_item(self, name: str) -> Item: if name in tech_table: return FactorioItem(name, name in advancement_technologies or name in self.additional_advancement_technologies, tech_table[name], self.player) item = FactorioItem(name, False, all_items[name], self.player) if "Trap" in name: item.trap = True return item <file_sep>import typing if typing.TYPE_CHECKING: import BaseClasses CollectionRule = typing.Callable[[BaseClasses.CollectionState], bool] ItemRule = typing.Callable[[BaseClasses.Item], bool] else: CollectionRule = typing.Callable[[object], bool] ItemRule = typing.Callable[[object], bool] def locality_rules(world, player: int): if world.local_items[player].value: for location in world.get_locations(): if location.player != player: forbid_items_for_player(location, world.local_items[player].value, player) if world.non_local_items[player].value: for location in world.get_locations(): if location.player == player: forbid_items_for_player(location, world.non_local_items[player].value, player) def exclusion_rules(world, player: int, exclude_locations: typing.Set[str]): for loc_name in exclude_locations: try: location = world.get_location(loc_name, player) except KeyError as e: # failed to find the given location. Check if it's a legitimate location if loc_name not in world.worlds[player].location_name_to_id: raise Exception(f"Unable to exclude location {loc_name} in player {player}'s world.") from e else: add_item_rule(location, lambda i: not (i.advancement or i.never_exclude)) location.excluded = True def set_rule(spot, rule: CollectionRule): spot.access_rule = rule def add_rule(spot, rule: CollectionRule, combine='and'): old_rule = spot.access_rule if combine == 'or': spot.access_rule = lambda state: rule(state) or old_rule(state) else: spot.access_rule = lambda state: rule(state) and old_rule(state) def forbid_item(location, item: str, player: int): old_rule = location.item_rule location.item_rule = lambda i: (i.name != item or i.player != player) and old_rule(i) def forbid_items_for_player(location, items: typing.Set[str], player: int): old_rule = location.item_rule location.item_rule = lambda i: (i.player != player or i.name not in items) and old_rule(i) def forbid_items(location, items: typing.Set[str]): """unused, but kept as a debugging tool.""" old_rule = location.item_rule location.item_rule = lambda i: i.name not in items and old_rule(i) def add_item_rule(location, rule: ItemRule): old_rule = location.item_rule location.item_rule = lambda item: rule(item) and old_rule(item) def item_in_locations(state, item: str, player: int, locations: typing.Sequence): for location in locations: if item_name(state, location[0], location[1]) == (item, player): return True return False def item_name(state, location: str, player: int) -> typing.Optional[typing.Tuple[str, int]]: location = state.world.get_location(location, player) if location.item is None: return None return location.item.name, location.item.player <file_sep>from __future__ import annotations import typing import enum from json import JSONEncoder, JSONDecoder import websockets from Utils import Version class JSONMessagePart(typing.TypedDict, total=False): text: str # optional type: str color: str # mainly for items, optional found: bool class ClientStatus(enum.IntEnum): CLIENT_UNKNOWN = 0 CLIENT_CONNECTED = 5 CLIENT_READY = 10 CLIENT_PLAYING = 20 CLIENT_GOAL = 30 class Permission(enum.IntEnum): disabled = 0b000 # 0, completely disables access enabled = 0b001 # 1, allows manual use goal = 0b010 # 2, allows manual use after goal completion auto = 0b110 # 6, forces use after goal completion, only works for forfeit auto_enabled = 0b111 # 7, forces use after goal completion, allows manual use any time @staticmethod def from_text(text: str): data = 0 if "auto" in text: data |= 0b110 elif "goal" in text: data |= 0b010 if "enabled" in text: data |= 0b001 return Permission(data) class NetworkPlayer(typing.NamedTuple): team: int slot: int alias: str name: str class NetworkItem(typing.NamedTuple): item: int location: int player: int def _scan_for_TypedTuples(obj: typing.Any) -> typing.Any: if isinstance(obj, tuple) and hasattr(obj, "_fields"): # NamedTuple is not actually a parent class data = obj._asdict() data["class"] = obj.__class__.__name__ return data if isinstance(obj, (tuple, list, set)): return tuple(_scan_for_TypedTuples(o) for o in obj) if isinstance(obj, dict): return {key: _scan_for_TypedTuples(value) for key, value in obj.items()} return obj _encode = JSONEncoder( ensure_ascii=False, check_circular=False, ).encode def encode(obj): return _encode(_scan_for_TypedTuples(obj)) def get_any_version(data: dict) -> Version: data = {key.lower(): value for key, value in data.items()} # .NET version classes have capitalized keys return Version(int(data["major"]), int(data["minor"]), int(data["build"])) whitelist = {"NetworkPlayer": NetworkPlayer, "NetworkItem": NetworkItem, } custom_hooks = { "Version": get_any_version } def _object_hook(o: typing.Any) -> typing.Any: if isinstance(o, dict): hook = custom_hooks.get(o.get("class", None), None) if hook: return hook(o) cls = whitelist.get(o.get("class", None), None) if cls: for key in tuple(o): if key not in cls._fields: del (o[key]) return cls(**o) return o decode = JSONDecoder(object_hook=_object_hook).decode class Endpoint: socket: websockets.WebSocketServerProtocol def __init__(self, socket): self.socket = socket async def disconnect(self): raise NotImplementedError class HandlerMeta(type): def __new__(mcs, name, bases, attrs): handlers = attrs["handlers"] = {} trigger: str = "_handle_" for base in bases: handlers.update(base.handlers) handlers.update({handler_name[len(trigger):]: method for handler_name, method in attrs.items() if handler_name.startswith(trigger)}) orig_init = attrs.get('__init__', None) if not orig_init: for base in bases: orig_init = getattr(base, '__init__', None) if orig_init: break def __init__(self, *args, **kwargs): # turn functions into bound methods self.handlers = {name: method.__get__(self, type(self)) for name, method in handlers.items()} if orig_init: orig_init(self, *args, **kwargs) attrs['__init__'] = __init__ return super(HandlerMeta, mcs).__new__(mcs, name, bases, attrs) class JSONTypes(str, enum.Enum): color = "color" text = "text" player_id = "player_id" player_name = "player_name" item_name = "item_name" item_id = "item_id" location_name = "location_name" location_id = "location_id" entrance_name = "entrance_name" class JSONtoTextParser(metaclass=HandlerMeta): def __init__(self, ctx): self.ctx = ctx def __call__(self, input_object: typing.List[JSONMessagePart]) -> str: return "".join(self.handle_node(section) for section in input_object) def handle_node(self, node: JSONMessagePart): node_type = node.get("type", None) handler = self.handlers.get(node_type, self.handlers["text"]) return handler(node) def _handle_color(self, node: JSONMessagePart): codes = node["color"].split(";") buffer = "".join(color_code(code) for code in codes) return buffer + self._handle_text(node) + color_code("reset") def _handle_text(self, node: JSONMessagePart): return node.get("text", "") def _handle_player_id(self, node: JSONMessagePart): player = int(node["text"]) node["color"] = 'magenta' if player == self.ctx.slot else 'yellow' node["text"] = self.ctx.player_names[player] return self._handle_color(node) # for other teams, spectators etc.? Only useful if player isn't in the clientside mapping def _handle_player_name(self, node: JSONMessagePart): node["color"] = 'yellow' return self._handle_color(node) def _handle_item_name(self, node: JSONMessagePart): # todo: use a better info source from worlds.alttp.Items import progression_items node["color"] = 'green' if node.get("found", False) else 'cyan' if node["text"] in progression_items: node["color"] += ";white_bg" return self._handle_color(node) def _handle_item_id(self, node: JSONMessagePart): item_id = int(node["text"]) node["text"] = self.ctx.item_name_getter(item_id) return self._handle_item_name(node) def _handle_location_name(self, node: JSONMessagePart): node["color"] = 'blue_bg;white' return self._handle_color(node) def _handle_location_id(self, node: JSONMessagePart): item_id = int(node["text"]) node["text"] = self.ctx.location_name_getter(item_id) return self._handle_item_name(node) def _handle_entrance_name(self, node: JSONMessagePart): node["color"] = 'blue' return self._handle_color(node) class RawJSONtoTextParser(JSONtoTextParser): def _handle_color(self, node: JSONMessagePart): return self._handle_text(node) color_codes = {'reset': 0, 'bold': 1, 'underline': 4, 'black': 30, 'red': 31, 'green': 32, 'yellow': 33, 'blue': 34, 'magenta': 35, 'cyan': 36, 'white': 37, 'black_bg': 40, 'red_bg': 41, 'green_bg': 42, 'yellow_bg': 43, 'blue_bg': 44, 'purple_bg': 45, 'cyan_bg': 46, 'white_bg': 47} def color_code(*args): return '\033[' + ';'.join([str(color_codes[arg]) for arg in args]) + 'm' def color(text, *args): return color_code(*args) + text + color_code('reset') def add_json_text(parts: list, text: typing.Any, **kwargs) -> None: parts.append({"text": str(text), **kwargs}) class Hint(typing.NamedTuple): receiving_player: int finding_player: int location: int item: int found: bool entrance: str = "" def re_check(self, ctx, team) -> Hint: if self.found: return self found = self.location in ctx.location_checks[team, self.finding_player] if found: return Hint(self.receiving_player, self.finding_player, self.location, self.item, found, self.entrance) return self def __hash__(self): return hash((self.receiving_player, self.finding_player, self.location, self.item, self.entrance)) def as_network_message(self) -> dict: parts = [] add_json_text(parts, "[Hint]: ") add_json_text(parts, self.receiving_player, type="player_id") add_json_text(parts, "'s ") add_json_text(parts, self.item, type="item_id", found=self.found) add_json_text(parts, " is at ") add_json_text(parts, self.location, type="location_id") add_json_text(parts, " in ") add_json_text(parts, self.finding_player, type="player_id") if self.entrance: add_json_text(parts, "'s World at ") add_json_text(parts, self.entrance, type="entrance_name") else: add_json_text(parts, "'s World") if self.found: add_json_text(parts, ". (found)") else: add_json_text(parts, ".") return {"cmd": "PrintJSON", "data": parts, "type": "Hint", "receiving": self.receiving_player, "item": NetworkItem(self.item, self.location, self.finding_player)} @property def local(self): return self.receiving_player == self.finding_player <file_sep>from ..generic.Rules import set_rule from .Locations import exclusion_table, events_table from BaseClasses import MultiWorld from ..AutoWorld import LogicMixin class MinecraftLogic(LogicMixin): def _mc_has_iron_ingots(self, player: int): return self.has('Progressive Tools', player) and self.has('Progressive Resource Crafting', player) def _mc_has_gold_ingots(self, player: int): return self.has('Progressive Resource Crafting', player) and (self.has('Progressive Tools', player, 2) or self.can_reach('The Nether', 'Region', player)) def _mc_has_diamond_pickaxe(self, player: int): return self.has('Progressive Tools', player, 3) and self._mc_has_iron_ingots(player) def _mc_craft_crossbow(self, player: int): return self.has('Archery', player) and self._mc_has_iron_ingots(player) def _mc_has_bottle(self, player: int): return self.has('Bottles', player) and self.has('Progressive Resource Crafting', player) def _mc_can_enchant(self, player: int): return self.has('Enchanting', player) and self._mc_has_diamond_pickaxe(player) # mine obsidian and lapis def _mc_can_use_anvil(self, player: int): return self.has('Enchanting', player) and self.has('Progressive Resource Crafting', player, 2) and self._mc_has_iron_ingots(player) def _mc_fortress_loot(self, player: int): # saddles, blaze rods, wither skulls return self.can_reach('Nether Fortress', 'Region', player) and self._mc_basic_combat(player) def _mc_can_brew_potions(self, player: int): return self.has('Blaze Rods', player) and self.has('Brewing', player) and self._mc_has_bottle(player) def _mc_can_piglin_trade(self, player: int): return self._mc_has_gold_ingots(player) and ( self.can_reach('The Nether', 'Region', player) or self.can_reach('Bastion Remnant', 'Region', player)) def _mc_enter_stronghold(self, player: int): return self.has('Blaze Rods', player) and self.has('Brewing', player) and self.has('3 Ender Pearls', player) # Difficulty-dependent functions def _mc_combat_difficulty(self, player: int): return self.world.combat_difficulty[player].current_key def _mc_can_adventure(self, player: int): if self._mc_combat_difficulty(player) == 'easy': return self.has('Progressive Weapons', player, 2) and self._mc_has_iron_ingots(player) elif self._mc_combat_difficulty(player) == 'hard': return True return self.has('Progressive Weapons', player) and (self.has('Progressive Resource Crafting', player) or self.has('Campfire', player)) def _mc_basic_combat(self, player: int): if self._mc_combat_difficulty(player) == 'easy': return self.has('Progressive Weapons', player, 2) and self.has('Progressive Armor', player) and \ self.has('Shield', player) and self._mc_has_iron_ingots(player) elif self._mc_combat_difficulty(player) == 'hard': return True return self.has('Progressive Weapons', player) and (self.has('Progressive Armor', player) or self.has('Shield', player)) and self._mc_has_iron_ingots(player) def _mc_complete_raid(self, player: int): reach_regions = self.can_reach('Village', 'Region', player) and self.can_reach('Pillager Outpost', 'Region', player) if self._mc_combat_difficulty(player) == 'easy': return reach_regions and \ self.has('Progressive Weapons', player, 3) and self.has('Progressive Armor', player, 2) and \ self.has('Shield', player) and self.has('Archery', player) and \ self.has('Progressive Tools', player, 2) and self._mc_has_iron_ingots(player) elif self._mc_combat_difficulty(player) == 'hard': # might be too hard? return reach_regions and self.has('Progressive Weapons', player, 2) and self._mc_has_iron_ingots(player) and \ (self.has('Progressive Armor', player) or self.has('Shield', player)) return reach_regions and self.has('Progressive Weapons', player, 2) and self._mc_has_iron_ingots(player) and \ self.has('Progressive Armor', player) and self.has('Shield', player) def _mc_can_kill_wither(self, player: int): normal_kill = self.has("Progressive Weapons", player, 3) and self.has("Progressive Armor", player, 2) and self._mc_can_brew_potions(player) and self._mc_can_enchant(player) if self._mc_combat_difficulty(player) == 'easy': return self._mc_fortress_loot(player) and normal_kill and self.has('Archery', player) elif self._mc_combat_difficulty(player) == 'hard': # cheese kill using bedrock ceilings return self._mc_fortress_loot(player) and (normal_kill or self.can_reach('The Nether', 'Region', player) or self.can_reach('The End', 'Region', player)) return self._mc_fortress_loot(player) and normal_kill def _mc_can_kill_ender_dragon(self, player: int): # Since it is possible to kill the dragon without getting any of the advancements related to it, we need to require that it can be respawned. respawn_dragon = self.can_reach('The Nether', 'Region', player) and self.has('Progressive Resource Crafting', player) if self._mc_combat_difficulty(player) == 'easy': return respawn_dragon and self.has("Progressive Weapons", player, 3) and self.has("Progressive Armor", player, 2) and \ self.has('Archery', player) and self._mc_can_brew_potions(player) and self._mc_can_enchant(player) if self._mc_combat_difficulty(player) == 'hard': return respawn_dragon and ((self.has('Progressive Weapons', player, 2) and self.has('Progressive Armor', player)) or \ (self.has('Progressive Weapons', player, 1) and self.has('Bed', player))) return respawn_dragon and self.has('Progressive Weapons', player, 2) and self.has('Progressive Armor', player) and self.has('Archery', player) def _mc_has_structure_compass(self, entrance_name: str, player: int): if not self.world.structure_compasses[player]: return True return self.has(f"Structure Compass ({self.world.get_entrance(entrance_name, player).connected_region.name})", player) def set_rules(world: MultiWorld, player: int): def reachable_locations(state): postgame_advancements = exclusion_table['postgame'].copy() for event in events_table.keys(): postgame_advancements.add(event) return [location for location in world.get_locations() if location.player == player and location.name not in postgame_advancements and location.can_reach(state)] # Retrieves the appropriate structure compass for the given entrance def get_struct_compass(entrance_name): struct = world.get_entrance(entrance_name, player).connected_region.name return f"Structure Compass ({struct})" # 92 total advancements. Goal is to complete X advancements and then Free the End. # There are 5 advancements which cannot be included for dragon spawning (4 postgame, Free the End) # Hence the true maximum is (92 - 5) = 87 goal = world.advancement_goal[player] egg_shards = min(world.egg_shards_required[player], world.egg_shards_available[player]) can_complete = lambda state: len(reachable_locations(state)) >= goal and state.has("Dragon Egg Shard", player, egg_shards) and state.can_reach('The End', 'Region', player) and state._mc_can_kill_ender_dragon(player) if world.logic[player] != 'nologic': world.completion_condition[player] = lambda state: state.has('Victory', player) set_rule(world.get_entrance("Nether Portal", player), lambda state: state.has('Flint and Steel', player) and (state.has('Bucket', player) or state.has('Progressive Tools', player, 3)) and state._mc_has_iron_ingots(player)) set_rule(world.get_entrance("End Portal", player), lambda state: state._mc_enter_stronghold(player) and state.has('3 Ender Pearls', player, 4)) set_rule(world.get_entrance("Overworld Structure 1", player), lambda state: state._mc_can_adventure(player) and state._mc_has_structure_compass("Overworld Structure 1", player)) set_rule(world.get_entrance("Overworld Structure 2", player), lambda state: state._mc_can_adventure(player) and state._mc_has_structure_compass("Overworld Structure 2", player)) set_rule(world.get_entrance("Nether Structure 1", player), lambda state: state._mc_can_adventure(player) and state._mc_has_structure_compass("Nether Structure 1", player)) set_rule(world.get_entrance("Nether Structure 2", player), lambda state: state._mc_can_adventure(player) and state._mc_has_structure_compass("Nether Structure 2", player)) set_rule(world.get_entrance("The End Structure", player), lambda state: state._mc_can_adventure(player) and state._mc_has_structure_compass("The End Structure", player)) set_rule(world.get_location("Ender Dragon", player), lambda state: can_complete(state)) set_rule(world.get_location("Blaze Spawner", player), lambda state: state._mc_fortress_loot(player)) set_rule(world.get_location("Who is Cutting Onions?", player), lambda state: state._mc_can_piglin_trade(player)) set_rule(world.get_location("Oh Shiny", player), lambda state: state._mc_can_piglin_trade(player)) set_rule(world.get_location("Suit Up", player), lambda state: state.has("Progressive Armor", player) and state._mc_has_iron_ingots(player)) set_rule(world.get_location("Very Very Frightening", player), lambda state: state.has("Channeling Book", player) and state._mc_can_use_anvil(player) and state._mc_can_enchant(player) and \ ((world.get_region('Village', player).entrances[0].parent_region.name != 'The End' and state.can_reach('Village', 'Region', player)) or state.can_reach('Zombie Doctor', 'Location', player))) # need villager into the overworld for lightning strike set_rule(world.get_location("Hot Stuff", player), lambda state: state.has("Bucket", player) and state._mc_has_iron_ingots(player)) set_rule(world.get_location("Free the End", player), lambda state: can_complete(state)) set_rule(world.get_location("A Furious Cocktail", player), lambda state: state._mc_can_brew_potions(player) and state.has("Fishing Rod", player) and # Water Breathing state.can_reach('The Nether', 'Region', player) and # Regeneration, Fire Resistance, gold nuggets state.can_reach('Village', 'Region', player) and # Night Vision, Invisibility state.can_reach('Bring Home the Beacon', 'Location', player)) # Resistance set_rule(world.get_location("Best Friends Forever", player), lambda state: True) set_rule(world.get_location("Bring Home the Beacon", player), lambda state: state._mc_can_kill_wither(player) and state._mc_has_diamond_pickaxe(player) and state.has("Progressive Resource Crafting", player, 2)) set_rule(world.get_location("Not Today, Thank You", player), lambda state: state.has("Shield", player) and state._mc_has_iron_ingots(player)) set_rule(world.get_location("Isn't It Iron Pick", player), lambda state: state.has("Progressive Tools", player, 2) and state._mc_has_iron_ingots(player)) set_rule(world.get_location("Local Brewery", player), lambda state: state._mc_can_brew_potions(player)) set_rule(world.get_location("The Next Generation", player), lambda state: can_complete(state)) set_rule(world.get_location("Fishy Business", player), lambda state: state.has("Fishing Rod", player)) set_rule(world.get_location("Hot Tourist Destinations", player), lambda state: True) set_rule(world.get_location("This Boat Has Legs", player), lambda state: (state._mc_fortress_loot(player) or state._mc_complete_raid(player)) and state.has("Saddle", player) and state.has("Fishing Rod", player)) set_rule(world.get_location("<NAME>", player), lambda state: state.has("Archery", player)) set_rule(world.get_location("Nether", player), lambda state: True) set_rule(world.get_location("Great View From Up Here", player), lambda state: state._mc_basic_combat(player)) set_rule(world.get_location("How Did We Get Here?", player), lambda state: state._mc_can_brew_potions(player) and state._mc_has_gold_ingots(player) and # Absorption state.can_reach('End City', 'Region', player) and # Levitation state.can_reach('The Nether', 'Region', player) and # potion ingredients state.has("Fishing Rod", player) and state.has("Archery",player) and # Pufferfish, Nautilus Shells; spectral arrows state.can_reach("Bring Home the Beacon", "Location", player) and # Haste state.can_reach("Hero of the Village", "Location", player)) # Bad Omen, Hero of the Village set_rule(world.get_location("Bullseye", player), lambda state: state.has("Archery", player) and state.has("Progressive Tools", player, 2) and state._mc_has_iron_ingots(player)) set_rule(world.get_location("Spooky Scary Skeleton", player), lambda state: state._mc_basic_combat(player)) set_rule(world.get_location("Two by Two", player), lambda state: state._mc_has_iron_ingots(player) and state._mc_can_adventure(player)) # shears > seagrass > turtles; nether > striders; gold carrots > horses skips ingots set_rule(world.get_location("Stone Age", player), lambda state: True) set_rule(world.get_location("Two Birds, One Arrow", player), lambda state: state._mc_craft_crossbow(player) and state._mc_can_enchant(player)) set_rule(world.get_location("We Need to Go Deeper", player), lambda state: True) set_rule(world.get_location("Who's the Pillager Now?", player), lambda state: state._mc_craft_crossbow(player)) set_rule(world.get_location("Getting an Upgrade", player), lambda state: state.has("Progressive Tools", player)) set_rule(world.get_location("Tactical Fishing", player), lambda state: state.has("Bucket", player) and state._mc_has_iron_ingots(player)) set_rule(world.get_location("Zombie Doctor", player), lambda state: state._mc_can_brew_potions(player) and state._mc_has_gold_ingots(player)) set_rule(world.get_location("The City at the End of the Game", player), lambda state: True) set_rule(world.get_location("Ice Bucket Challenge", player), lambda state: state._mc_has_diamond_pickaxe(player)) set_rule(world.get_location("Remote Getaway", player), lambda state: True) set_rule(world.get_location("Into Fire", player), lambda state: state._mc_basic_combat(player)) set_rule(world.get_location("War Pigs", player), lambda state: state._mc_basic_combat(player)) set_rule(world.get_location("Take Aim", player), lambda state: state.has("Archery", player)) set_rule(world.get_location("Total Beelocation", player), lambda state: state.has("Silk Touch Book", player) and state._mc_can_use_anvil(player) and state._mc_can_enchant(player)) set_rule(world.get_location("Arbalistic", player), lambda state: state._mc_craft_crossbow(player) and state.has("Piercing IV Book", player) and state._mc_can_use_anvil(player) and state._mc_can_enchant(player)) set_rule(world.get_location("The End... Again...", player), lambda state: can_complete(state)) set_rule(world.get_location("Acquire Hardware", player), lambda state: state._mc_has_iron_ingots(player)) set_rule(world.get_location("Not Quite \"Nine\" Lives", player), lambda state: state._mc_can_piglin_trade(player) and state.has("Progressive Resource Crafting", player, 2)) set_rule(world.get_location("Cover Me With Diamonds", player), lambda state: state.has("Progressive Armor", player, 2) and state.can_reach("Diamonds!", "Location", player)) set_rule(world.get_location("Sky's the Limit", player), lambda state: state._mc_basic_combat(player)) set_rule(world.get_location("Hired Help", player), lambda state: state.has("Progressive Resource Crafting", player, 2) and state._mc_has_iron_ingots(player)) set_rule(world.get_location("Return to Sender", player), lambda state: True) set_rule(world.get_location("Sweet Dreams", player), lambda state: state.has("Bed", player) or state.can_reach('Village', 'Region', player)) set_rule(world.get_location("You Need a Mint", player), lambda state: can_complete(state) and state._mc_has_bottle(player)) set_rule(world.get_location("Adventure", player), lambda state: True) set_rule(world.get_location("Monsters Hunted", player), lambda state: can_complete(state) and state._mc_can_kill_wither(player) and state.has("Fishing Rod", player)) # pufferfish for Water Breathing set_rule(world.get_location("Enchanter", player), lambda state: state._mc_can_enchant(player)) set_rule(world.get_location("Voluntary Exile", player), lambda state: state._mc_basic_combat(player)) set_rule(world.get_location("Eye Spy", player), lambda state: state._mc_enter_stronghold(player)) set_rule(world.get_location("The End", player), lambda state: True) set_rule(world.get_location("Serious Dedication", player), lambda state: state.can_reach("Hidden in the Depths", "Location", player) and state._mc_has_gold_ingots(player)) set_rule(world.get_location("Postmortal", player), lambda state: state._mc_complete_raid(player)) set_rule(world.get_location("Monster Hunter", player), lambda state: True) set_rule(world.get_location("Adventuring Time", player), lambda state: state._mc_can_adventure(player)) set_rule(world.get_location("A Seedy Place", player), lambda state: True) set_rule(world.get_location("Those Were the Days", player), lambda state: True) set_rule(world.get_location("Hero of the Village", player), lambda state: state._mc_complete_raid(player)) set_rule(world.get_location("Hidden in the Depths", player), lambda state: state._mc_can_brew_potions(player) and state.has("Bed", player) and state._mc_has_diamond_pickaxe(player)) # bed mining :) set_rule(world.get_location("Beaconator", player), lambda state: state._mc_can_kill_wither(player) and state._mc_has_diamond_pickaxe(player) and state.has("Progressive Resource Crafting", player, 2)) set_rule(world.get_location("Withering Heights", player), lambda state: state._mc_can_kill_wither(player)) set_rule(world.get_location("A Balanced Diet", player), lambda state: state._mc_has_bottle(player) and state._mc_has_gold_ingots(player) and # honey bottle; gapple state.has("Progressive Resource Crafting", player, 2) and state.can_reach('The End', 'Region', player)) # notch apple, chorus fruit set_rule(world.get_location("Subspace Bubble", player), lambda state: state._mc_has_diamond_pickaxe(player)) set_rule(world.get_location("Husbandry", player), lambda state: True) set_rule(world.get_location("Country Lode, Take Me Home", player), lambda state: state.can_reach("Hidden in the Depths", "Location", player) and state._mc_has_gold_ingots(player)) set_rule(world.get_location("Bee Our Guest", player), lambda state: state.has("Campfire", player) and state._mc_has_bottle(player)) set_rule(world.get_location("What a Deal!", player), lambda state: True) set_rule(world.get_location("Uneasy Alliance", player), lambda state: state._mc_has_diamond_pickaxe(player) and state.has('Fishing Rod', player)) set_rule(world.get_location("Diamonds!", player), lambda state: state.has("Progressive Tools", player, 2) and state._mc_has_iron_ingots(player)) set_rule(world.get_location("A Terrible Fortress", player), lambda state: True) # since you don't have to fight anything set_rule(world.get_location("A Throwaway Joke", player), lambda state: True) # kill drowned set_rule(world.get_location("Minecraft", player), lambda state: True) set_rule(world.get_location("Sticky Situation", player), lambda state: state.has("Campfire", player) and state._mc_has_bottle(player)) set_rule(world.get_location("Ol' Betsy", player), lambda state: state._mc_craft_crossbow(player)) set_rule(world.get_location("Cover Me in Debris", player), lambda state: state.has("Progressive Armor", player, 2) and state.has("8 Netherite Scrap", player, 2) and state.has("Progressive Resource Crafting", player) and state.can_reach("Diamonds!", "Location", player) and state.can_reach("Hidden in the Depths", "Location", player)) set_rule(world.get_location("The End?", player), lambda state: True) set_rule(world.get_location("The Parrots and the Bats", player), lambda state: True) set_rule(world.get_location("A Complete Catalogue", player), lambda state: True) # kill fish for raw set_rule(world.get_location("Getting Wood", player), lambda state: True) set_rule(world.get_location("Time to Mine!", player), lambda state: True) set_rule(world.get_location("Hot Topic", player), lambda state: state.has("Progressive Resource Crafting", player)) set_rule(world.get_location("Bake Bread", player), lambda state: True) set_rule(world.get_location("The Lie", player), lambda state: state._mc_has_iron_ingots(player) and state.has("Bucket", player)) set_rule(world.get_location("On a Rail", player), lambda state: state._mc_has_iron_ingots(player) and state.has('Progressive Tools', player, 2)) # powered rails set_rule(world.get_location("Time to Strike!", player), lambda state: True) set_rule(world.get_location("Cow Tipper", player), lambda state: True) set_rule(world.get_location("When Pigs Fly", player), lambda state: (state._mc_fortress_loot(player) or state._mc_complete_raid(player)) and state.has("Saddle", player) and state.has("Fishing Rod", player) and state._mc_can_adventure(player)) set_rule(world.get_location("Overkill", player), lambda state: state._mc_can_brew_potions(player) and (state.has("Progressive Weapons", player) or state.can_reach('The Nether', 'Region', player))) # strength 1 + stone axe crit OR strength 2 + wood axe crit set_rule(world.get_location("Librarian", player), lambda state: state.has("Enchanting", player)) set_rule(world.get_location("Overpowered", player), lambda state: state.has("Progressive Resource Crafting", player, 2) and state._mc_has_gold_ingots(player)) <file_sep>from BaseClasses import MultiWorld from ..AutoWorld import LogicMixin from ..generic.Rules import set_rule class RiskOfRainLogic(LogicMixin): def _ror_has_items(self, player: int, amount: int) -> bool: count: int = self.item_count("Common Item", player) + self.item_count("Uncommon Item", player) + \ self.item_count("Legendary Item", player) + self.item_count("Boss Item", player) + \ self.item_count("Lunar Item", player) + self.item_count("Equipment", player) + \ self.item_count("Dio's Best Friend", player) + self.item_count("Item Scrap, White", player) + \ self.item_count("Item Scrap, Green", player) + self.item_count("Item Scrap, Red", player) + \ self.item_count("Item Scrap, Yellow", player) return count >= amount def set_rules(world: MultiWorld, player: int): # divide by 5 since 5 levels (then commencement) items_per_level = max(int(world.total_locations[player] / 5 / (world.item_pickup_step[player]+1)), 1) # lock item pickup access based on level completion for i in range(1, items_per_level): set_rule(world.get_location(f"ItemPickup{i}", player), lambda state: True) for i in range(items_per_level, 2*items_per_level): set_rule(world.get_location(f"ItemPickup{i}", player), lambda state: state.has("Beat Level One", player)) for i in range(2*items_per_level, 3*items_per_level): set_rule(world.get_location(f"ItemPickup{i}", player), lambda state: state.has("Beat Level Two", player)) for i in range(3*items_per_level, 4*items_per_level): set_rule(world.get_location(f"ItemPickup{i}", player), lambda state: state.has("Beat Level Three", player)) for i in range(4*items_per_level, world.total_locations[player] + 1): set_rule(world.get_location(f"ItemPickup{i}", player), lambda state: state.has("Beat Level Four", player)) # require items to beat each stage set_rule(world.get_location("Level Two", player), lambda state: state.has("Beat Level One", player) and state._ror_has_items(player, items_per_level)) set_rule(world.get_location("Level Three", player), lambda state: state._ror_has_items(player, 2 * items_per_level) and state.has("Beat Level Two", player)) set_rule(world.get_location("Level Four", player), lambda state: state._ror_has_items(player, 3 * items_per_level) and state.has("Beat Level Three", player)) set_rule(world.get_location("Level Five", player), lambda state: state._ror_has_items(player, 4 * items_per_level) and state.has("Beat Level Four", player)) set_rule(world.get_location("Victory", player), lambda state: state._ror_has_items(player, 5 * items_per_level) and state.has("Beat Level Five", player)) world.completion_condition[player] = lambda state: state.has("Victory", player)<file_sep>from typing import NamedTuple class Location(NamedTuple): code: int vanilla_item: str<file_sep>function filter_ingredients(ingredients, ingredient_filter) local new_ingredient_list = {} for _, ingredient_table in pairs(ingredients) do if ingredient_filter[ingredient_table[1]] then -- name of ingredient_table table.insert(new_ingredient_list, ingredient_table) end end return new_ingredient_list end function add_ingredients(ingredients, added_ingredients) local new_ingredient_list = table.deepcopy(ingredients) for new_ingredient, count in pairs(added_ingredients) do local found = false for _, old_ingredient in pairs(ingredients) do if old_ingredient[1] == new_ingredient then found = true break end end if not found then table.insert(new_ingredient_list, {new_ingredient, count}) end end return new_ingredient_list end function get_any_stack_size(name) local item = game.item_prototypes[name] if item ~= nil then return item.stack_size end item = game.equipment_prototypes[name] if item ~= nil then return item.stack_size end -- failsafe return 1 end -- from https://stackoverflow.com/a/40180465 -- split("a,b,c", ",") => {"a", "b", "c"} function split(s, sep) local fields = {} sep = sep or " " local pattern = string.format("([^%s]+)", sep) string.gsub(s, pattern, function(c) fields[#fields + 1] = c end) return fields end<file_sep>from __future__ import annotations import typing def tuplize_version(version: str) -> Version: return Version(*(int(piece, 10) for piece in version.split("."))) class Version(typing.NamedTuple): major: int minor: int build: int __version__ = "0.1.9" version_tuple = tuplize_version(__version__) import builtins import os import subprocess import sys import pickle import functools import io import collections import importlib from yaml import load, dump, safe_load try: from yaml import CLoader as Loader except ImportError: from yaml import Loader def int16_as_bytes(value): value = value & 0xFFFF return [value & 0xFF, (value >> 8) & 0xFF] def int32_as_bytes(value): value = value & 0xFFFFFFFF return [value & 0xFF, (value >> 8) & 0xFF, (value >> 16) & 0xFF, (value >> 24) & 0xFF] def pc_to_snes(value): return ((value << 1) & 0x7F0000) | (value & 0x7FFF) | 0x8000 def snes_to_pc(value): return ((value & 0x7F0000) >> 1) | (value & 0x7FFF) def cache_argsless(function): if function.__code__.co_argcount: raise Exception("Can only cache 0 argument functions with this cache.") result = sentinel = object() def _wrap(): nonlocal result if result is sentinel: result = function() return result return _wrap def is_frozen() -> bool: return getattr(sys, 'frozen', False) def local_path(*path): if local_path.cached_path: return os.path.join(local_path.cached_path, *path) elif is_frozen(): if hasattr(sys, "_MEIPASS"): # we are running in a PyInstaller bundle local_path.cached_path = sys._MEIPASS # pylint: disable=protected-access,no-member else: # cx_Freeze local_path.cached_path = os.path.dirname(os.path.abspath(sys.argv[0])) else: import __main__ if hasattr(__main__, "__file__"): # we are running in a normal Python environment local_path.cached_path = os.path.dirname(os.path.abspath(__main__.__file__)) else: # pray local_path.cached_path = os.path.abspath(".") return os.path.join(local_path.cached_path, *path) local_path.cached_path = None def output_path(*path): if output_path.cached_path: return os.path.join(output_path.cached_path, *path) output_path.cached_path = local_path(get_options()["general_options"]["output_path"]) path = os.path.join(output_path.cached_path, *path) os.makedirs(os.path.dirname(path), exist_ok=True) return path output_path.cached_path = None def open_file(filename): if sys.platform == 'win32': os.startfile(filename) else: open_command = 'open' if sys.platform == 'darwin' else 'xdg-open' subprocess.call([open_command, filename]) parse_yaml = safe_load unsafe_parse_yaml = functools.partial(load, Loader=Loader) @cache_argsless def get_public_ipv4() -> str: import socket import urllib.request import logging ip = socket.gethostbyname(socket.gethostname()) try: ip = urllib.request.urlopen('https://checkip.amazonaws.com/').read().decode('utf8').strip() except Exception as e: try: ip = urllib.request.urlopen('https://v4.ident.me').read().decode('utf8').strip() except: logging.exception(e) pass # we could be offline, in a local game, so no point in erroring out return ip @cache_argsless def get_public_ipv6() -> str: import socket import urllib.request import logging ip = socket.gethostbyname(socket.gethostname()) try: ip = urllib.request.urlopen('https://v6.ident.me').read().decode('utf8').strip() except Exception as e: logging.exception(e) pass # we could be offline, in a local game, or ipv6 may not be available return ip @cache_argsless def get_default_options() -> dict: # Refer to host.yaml for comments as to what all these options mean. options = { "general_options": { "output_path": "output", }, "factorio_options": { "executable": "factorio\\bin\\x64\\factorio", }, "lttp_options": { "rom_file": "Zelda no Densetsu - Kamigami no Triforce (Japan).sfc", "sni": "SNI", "rom_start": True, }, "server_options": { "host": None, "port": 38281, "password": <PASSWORD>, "multidata": None, "savefile": None, "disable_save": False, "loglevel": "info", "server_password": None, "disable_item_cheat": False, "location_check_points": 1, "hint_cost": 10, "forfeit_mode": "goal", "collect_mode": "disabled", "remaining_mode": "goal", "auto_shutdown": 0, "compatibility": 2, "log_network": 0 }, "generator": { "teams": 1, "enemizer_path": "EnemizerCLI/EnemizerCLI.Core.exe", "player_files_path": "Players", "players": 0, "weights_file_path": "weights.yaml", "meta_file_path": "meta.yaml", "spoiler": 2, "glitch_triforce_room": 1, "race": 0, "plando_options": "bosses", }, "minecraft_options": { "forge_directory": "Minecraft Forge server", "max_heap_size": "2G" }, "oot_options": { "rom_file": "The Legend of Zelda - Ocarina of Time.z64", } } return options def update_options(src: dict, dest: dict, filename: str, keys: list) -> dict: import logging for key, value in src.items(): new_keys = keys.copy() new_keys.append(key) option_name = '.'.join(new_keys) if key not in dest: dest[key] = value if filename.endswith("options.yaml"): logging.info(f"Warning: {filename} is missing {option_name}") elif isinstance(value, dict): if not isinstance(dest.get(key, None), dict): if filename.endswith("options.yaml"): logging.info(f"Warning: {filename} has {option_name}, but it is not a dictionary. overwriting.") dest[key] = value else: dest[key] = update_options(value, dest[key], filename, new_keys) return dest @cache_argsless def get_options() -> dict: if not hasattr(get_options, "options"): locations = ("options.yaml", "host.yaml", local_path("options.yaml"), local_path("host.yaml")) for location in locations: if os.path.exists(location): with open(location) as f: options = parse_yaml(f.read()) get_options.options = update_options(get_default_options(), options, location, list()) break else: raise FileNotFoundError(f"Could not find {locations[1]} to load options.") return get_options.options def get_item_name_from_id(code: int) -> str: from worlds import lookup_any_item_id_to_name return lookup_any_item_id_to_name.get(code, f'Unknown item (ID:{code})') def get_location_name_from_id(code: int) -> str: from worlds import lookup_any_location_id_to_name return lookup_any_location_id_to_name.get(code, f'Unknown location (ID:{code})') def persistent_store(category: str, key: typing.Any, value: typing.Any): path = local_path("_persistent_storage.yaml") storage: dict = persistent_load() category = storage.setdefault(category, {}) category[key] = value with open(path, "wt") as f: f.write(dump(storage)) def persistent_load() -> typing.Dict[dict]: storage = getattr(persistent_load, "storage", None) if storage: return storage path = local_path("_persistent_storage.yaml") storage: dict = {} if os.path.exists(path): try: with open(path, "r") as f: storage = unsafe_parse_yaml(f.read()) except Exception as e: import logging logging.debug(f"Could not read store: {e}") if storage is None: storage = {} persistent_load.storage = storage return storage def get_adjuster_settings(romfile: str, skip_questions: bool = False) -> typing.Tuple[str, bool]: if hasattr(get_adjuster_settings, "adjuster_settings"): adjuster_settings = getattr(get_adjuster_settings, "adjuster_settings") else: adjuster_settings = persistent_load().get("adjuster", {}).get("last_settings_3", {}) if adjuster_settings: import pprint from worlds.alttp.Rom import get_base_rom_path adjuster_settings.rom = romfile adjuster_settings.baserom = get_base_rom_path() adjuster_settings.world = None whitelist = {"music", "menuspeed", "heartbeep", "heartcolor", "ow_palettes", "quickswap", "uw_palettes", "sprite"} printed_options = {name: value for name, value in vars(adjuster_settings).items() if name in whitelist} if hasattr(adjuster_settings, "sprite_pool"): sprite_pool = {} for sprite in getattr(adjuster_settings, "sprite_pool"): if sprite in sprite_pool: sprite_pool[sprite] += 1 else: sprite_pool[sprite] = 1 if sprite_pool: printed_options["sprite_pool"] = sprite_pool if hasattr(get_adjuster_settings, "adjust_wanted"): adjust_wanted = getattr(get_adjuster_settings, "adjust_wanted") elif persistent_load().get("adjuster", {}).get("never_adjust", False): # never adjust, per user request return romfile, False elif skip_questions: return romfile, False else: adjust_wanted = input(f"Last used adjuster settings were found. Would you like to apply these? \n" f"{pprint.pformat(printed_options)}\n" f"Enter yes, no or never: ") if adjust_wanted and adjust_wanted.startswith("y"): if hasattr(adjuster_settings, "sprite_pool"): from LttPAdjuster import AdjusterWorld adjuster_settings.world = AdjusterWorld(getattr(adjuster_settings, "sprite_pool")) adjusted = True import LttPAdjuster _, romfile = LttPAdjuster.adjust(adjuster_settings) if hasattr(adjuster_settings, "world"): delattr(adjuster_settings, "world") elif adjust_wanted and "never" in adjust_wanted: persistent_store("adjuster", "never_adjust", True) return romfile, False else: adjusted = False import logging if not hasattr(get_adjuster_settings, "adjust_wanted"): logging.info(f"Skipping post-patch adjustment") get_adjuster_settings.adjuster_settings = adjuster_settings get_adjuster_settings.adjust_wanted = adjust_wanted return romfile, adjusted return romfile, False @cache_argsless def get_unique_identifier(): uuid = persistent_load().get("client", {}).get("uuid", None) if uuid: return uuid import uuid uuid = uuid.getnode() persistent_store("client", "uuid", uuid) return uuid safe_builtins = { 'set', 'frozenset', } class RestrictedUnpickler(pickle.Unpickler): def __init__(self, *args, **kwargs): super(RestrictedUnpickler, self).__init__(*args, **kwargs) self.options_module = importlib.import_module("Options") self.net_utils_module = importlib.import_module("NetUtils") self.generic_properties_module = importlib.import_module("worlds.generic") def find_class(self, module, name): if module == "builtins" and name in safe_builtins: return getattr(builtins, name) # used by MultiServer -> savegame/multidata if module == "NetUtils" and name in {"NetworkItem", "ClientStatus", "Hint"}: return getattr(self.net_utils_module, name) # Options and Plando are unpickled by WebHost -> Generate if module == "worlds.generic" and name in {"PlandoItem", "PlandoConnection"}: return getattr(self.generic_properties_module, name) if module.endswith("Options"): if module == "Options": mod = self.options_module else: mod = importlib.import_module(module) obj = getattr(mod, name) if issubclass(obj, self.options_module.Option): return obj # Forbid everything else. raise pickle.UnpicklingError("global '%s.%s' is forbidden" % (module, name)) def restricted_loads(s): """Helper function analogous to pickle.loads().""" return RestrictedUnpickler(io.BytesIO(s)).load() class KeyedDefaultDict(collections.defaultdict): def __missing__(self, key): self[key] = value = self.default_factory(key) return value def get_text_between(text: str, start: str, end: str) -> str: return text[text.index(start) + len(start): text.rindex(end)] <file_sep>import zipfile import lzma import json import base64 import MultiServer import uuid from flask import request, flash, redirect, url_for, session, render_template from pony.orm import flush, select from WebHostLib import app, Seed, Room, Slot from Utils import parse_yaml accepted_zip_contents = {"patches": ".apbp", "spoiler": ".txt", "multidata": ".archipelago"} banned_zip_contents = (".sfc",) def upload_zip_to_db(zfile: zipfile.ZipFile, owner=None, meta={"race": False}, sid=None): if not owner: owner = session["_id"] infolist = zfile.infolist() slots = set() spoiler = "" multidata = None for file in infolist: if file.filename.endswith(banned_zip_contents): return "Uploaded data contained a rom file, which is likely to contain copyrighted material. " \ "Your file was deleted." elif file.filename.endswith(".apbp"): data = zfile.open(file, "r").read() yaml_data = parse_yaml(lzma.decompress(data).decode("utf-8-sig")) if yaml_data["version"] < 2: return "Old format cannot be uploaded (outdated .apbp)", 500 metadata = yaml_data["meta"] slots.add(Slot(data=data, player_name=metadata["player_name"], player_id=metadata["player_id"], game="A Link to the Past")) elif file.filename.endswith(".apmc"): data = zfile.open(file, "r").read() metadata = json.loads(base64.b64decode(data).decode("utf-8")) slots.add(Slot(data=data, player_name=metadata["player_name"], player_id=metadata["player_id"], game="Minecraft")) elif file.filename.endswith(".zip"): # Factorio mods need a specific name or they do not function _, seed_name, slot_id, slot_name = file.filename.rsplit("_", 1)[0].split("-", 3) slots.add(Slot(data=zfile.open(file, "r").read(), player_name=slot_name, player_id=int(slot_id[1:]), game="Factorio")) elif file.filename.endswith(".apz5"): # .apz5 must be named specifically since they don't contain any metadata _, seed_name, slot_id, slot_name = file.filename.split('.')[0].split('_', 3) slots.add(Slot(data=zfile.open(file, "r").read(), player_name=slot_name, player_id=int(slot_id[1:]), game="Ocarina of Time")) elif file.filename.endswith(".txt"): spoiler = zfile.open(file, "r").read().decode("utf-8-sig") elif file.filename.endswith(".archipelago"): try: multidata = zfile.open(file).read() MultiServer.Context._decompress(multidata) except: flash("Could not load multidata. File may be corrupted or incompatible.") else: multidata = zfile.open(file).read() if multidata: flush() # commit slots seed = Seed(multidata=multidata, spoiler=spoiler, slots=slots, owner=owner, meta=json.dumps(meta), id=sid if sid else uuid.uuid4()) flush() # create seed for slot in slots: slot.seed = seed return seed else: flash("No multidata was found in the zip file, which is required.") @app.route('/uploads', methods=['GET', 'POST']) def uploads(): if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') else: file = request.files['file'] # if user does not select file, browser also # submit an empty part without filename if file.filename == '': flash('No selected file') elif file and allowed_file(file.filename): if file.filename.endswith(".zip"): with zipfile.ZipFile(file, 'r') as zfile: res = upload_zip_to_db(zfile) if type(res) == str: return res elif res: return redirect(url_for("viewSeed", seed=res.id)) else: try: multidata = file.read() MultiServer.Context._decompress(multidata) except: flash("Could not load multidata. File may be corrupted or incompatible.") raise else: seed = Seed(multidata=multidata, owner=session["_id"]) flush() # place into DB and generate ids return redirect(url_for("viewSeed", seed=seed.id)) else: flash("Not recognized file format. Awaiting a .archipelago file or .zip containing one.") return render_template("hostGame.html") @app.route('/user-content', methods=['GET']) def user_content(): rooms = select(room for room in Room if room.owner == session["_id"]) seeds = select(seed for seed in Seed if seed.owner == session["_id"]) return render_template("userContent.html", rooms=rooms, seeds=seeds) def allowed_file(filename): return filename.endswith(('.archipelago', ".zip")) <file_sep>from __future__ import annotations import copy from enum import Enum, unique import logging import json import functools from collections import OrderedDict, Counter, deque from typing import List, Dict, Optional, Set, Iterable, Union, Any, Tuple import secrets import random import Options import Utils class MultiWorld(): debug_types = False player_name: Dict[int, str] _region_cache: Dict[int, Dict[str, Region]] difficulty_requirements: dict required_medallions: dict dark_room_logic: Dict[int, str] restrict_dungeon_item_on_boss: Dict[int, bool] plando_texts: List[Dict[str, str]] plando_items: List plando_connections: List worlds: Dict[int, Any] is_race: bool = False precollected_items: Dict[int, List[Item]] class AttributeProxy(): def __init__(self, rule): self.rule = rule def __getitem__(self, player) -> bool: return self.rule(player) def __init__(self, players: int): self.random = random.Random() # world-local random state is saved for multiple generations running concurrently self.players = players self.glitch_triforce = False self.algorithm = 'balanced' self.dungeons: Dict[Tuple[str, int], Dungeon] = {} self.regions = [] self.shops = [] self.itempool = [] self.seed = None self.seed_name: str = "Unavailable" self.precollected_items = {player: [] for player in self.player_ids} self.state = CollectionState(self) self._cached_entrances = None self._cached_locations = None self._entrance_cache = {} self._location_cache = {} self.required_locations = [] self.light_world_light_cone = False self.dark_world_light_cone = False self.rupoor_cost = 10 self.aga_randomness = True self.lock_aga_door_in_escape = False self.save_and_quit_from_boss = True self.custom = False self.customitemarray = [] self.shuffle_ganon = True self.dynamic_regions = [] self.dynamic_locations = [] self.spoiler = Spoiler(self) self.fix_trock_doors = self.AttributeProxy( lambda player: self.shuffle[player] != 'vanilla' or self.mode[player] == 'inverted') self.fix_skullwoods_exit = self.AttributeProxy( lambda player: self.shuffle[player] not in ['vanilla', 'simple', 'restricted', 'dungeonssimple']) self.fix_palaceofdarkness_exit = self.AttributeProxy( lambda player: self.shuffle[player] not in ['vanilla', 'simple', 'restricted', 'dungeonssimple']) self.fix_trock_exit = self.AttributeProxy( lambda player: self.shuffle[player] not in ['vanilla', 'simple', 'restricted', 'dungeonssimple']) self.NOTCURSED = self.AttributeProxy(lambda player: not self.CURSED[player]) for player in range(1, players + 1): def set_player_attr(attr, val): self.__dict__.setdefault(attr, {})[player] = val set_player_attr('tech_tree_layout_prerequisites', {}) set_player_attr('_region_cache', {}) set_player_attr('shuffle', "vanilla") set_player_attr('logic', "noglitches") set_player_attr('mode', 'open') set_player_attr('difficulty', 'normal') set_player_attr('item_functionality', 'normal') set_player_attr('timer', False) set_player_attr('goal', 'ganon') set_player_attr('required_medallions', ['Ether', 'Quake']) set_player_attr('swamp_patch_required', False) set_player_attr('powder_patch_required', False) set_player_attr('ganon_at_pyramid', True) set_player_attr('ganonstower_vanilla', True) set_player_attr('can_access_trock_eyebridge', None) set_player_attr('can_access_trock_front', None) set_player_attr('can_access_trock_big_chest', None) set_player_attr('can_access_trock_middle', None) set_player_attr('fix_fake_world', True) set_player_attr('difficulty_requirements', None) set_player_attr('boss_shuffle', 'none') set_player_attr('enemy_health', 'default') set_player_attr('enemy_damage', 'default') set_player_attr('beemizer_total_chance', 0) set_player_attr('beemizer_trap_chance', 0) set_player_attr('escape_assist', []) set_player_attr('open_pyramid', False) set_player_attr('treasure_hunt_icon', 'Triforce Piece') set_player_attr('treasure_hunt_count', 0) set_player_attr('clock_mode', False) set_player_attr('countdown_start_time', 10) set_player_attr('red_clock_time', -2) set_player_attr('blue_clock_time', 2) set_player_attr('green_clock_time', 4) set_player_attr('can_take_damage', True) set_player_attr('triforce_pieces_available', 30) set_player_attr('triforce_pieces_required', 20) set_player_attr('shop_shuffle', 'off') set_player_attr('shuffle_prizes', "g") set_player_attr('sprite_pool', []) set_player_attr('dark_room_logic', "lamp") set_player_attr('plando_items', []) set_player_attr('plando_texts', {}) set_player_attr('plando_connections', []) set_player_attr('game', "A Link to the Past") set_player_attr('completion_condition', lambda state: True) self.custom_data = {} self.worlds = {} self.slot_seeds = {} def set_seed(self, seed: Optional[int] = None, secure: bool = False, name: Optional[str] = None): self.seed = get_seed(seed) if secure: self.secure() else: self.random.seed(self.seed) self.seed_name = name if name else str(self.seed) self.slot_seeds = {player: random.Random(self.random.getrandbits(64)) for player in range(1, self.players + 1)} def set_options(self, args): from worlds import AutoWorld for player in self.player_ids: self.custom_data[player] = {} world_type = AutoWorld.AutoWorldRegister.world_types[self.game[player]] for option_key in world_type.options: setattr(self, option_key, getattr(args, option_key, {})) for option_key in Options.common_options: setattr(self, option_key, getattr(args, option_key, {})) for option_key in Options.per_game_common_options: setattr(self, option_key, getattr(args, option_key, {})) self.worlds[player] = world_type(self, player) # intended for unittests def set_default_common_options(self): for option_key, option in Options.common_options.items(): setattr(self, option_key, {player_id: option(option.default) for player_id in self.player_ids}) for option_key, option in Options.per_game_common_options.items(): setattr(self, option_key, {player_id: option(option.default) for player_id in self.player_ids}) def secure(self): self.random = secrets.SystemRandom() self.is_race = True @functools.cached_property def player_ids(self): return tuple(range(1, self.players + 1)) @functools.lru_cache() def get_game_players(self, game_name: str): return tuple(player for player in self.player_ids if self.game[player] == game_name) @functools.lru_cache() def get_game_worlds(self, game_name: str): return tuple(world for player, world in self.worlds.items() if self.game[player] == game_name) def get_name_string_for_object(self, obj) -> str: return obj.name if self.players == 1 else f'{obj.name} ({self.get_player_name(obj.player)})' def get_player_name(self, player: int) -> str: return self.player_name[player] def initialize_regions(self, regions=None): for region in regions if regions else self.regions: region.world = self self._region_cache[region.player][region.name] = region @functools.cached_property def world_name_lookup(self): return {self.player_name[player_id]: player_id for player_id in self.player_ids} def _recache(self): """Rebuild world cache""" for region in self.regions: player = region.player self._region_cache[player][region.name] = region for exit in region.exits: self._entrance_cache[exit.name, player] = exit for r_location in region.locations: self._location_cache[r_location.name, player] = r_location def get_regions(self, player=None): return self.regions if player is None else self._region_cache[player].values() def get_region(self, regionname: str, player: int) -> Region: try: return self._region_cache[player][regionname] except KeyError: self._recache() return self._region_cache[player][regionname] def get_entrance(self, entrance: str, player: int) -> Entrance: try: return self._entrance_cache[entrance, player] except KeyError: self._recache() return self._entrance_cache[entrance, player] def get_location(self, location: str, player: int) -> Location: try: return self._location_cache[location, player] except KeyError: self._recache() return self._location_cache[location, player] def get_dungeon(self, dungeonname: str, player: int) -> Dungeon: try: return self.dungeons[dungeonname, player] except KeyError as e: raise KeyError('No such dungeon %s for player %d' % (dungeonname, player)) from e def get_all_state(self, use_cache: bool) -> CollectionState: cached = getattr(self, "_all_state", None) if use_cache and cached: return cached.copy() ret = CollectionState(self) for item in self.itempool: self.worlds[item.player].collect(ret, item) from worlds.alttp.Dungeons import get_dungeon_item_pool for item in get_dungeon_item_pool(self): subworld = self.worlds[item.player] if item.name in subworld.dungeon_local_item_names: subworld.collect(ret, item) ret.sweep_for_events() if use_cache: self._all_state = ret return ret def get_items(self) -> list: return [loc.item for loc in self.get_filled_locations()] + self.itempool def find_items(self, item, player: int) -> List[Location]: return [location for location in self.get_locations() if location.item is not None and location.item.name == item and location.item.player == player] def find_item(self, item, player: int) -> Location: return next(location for location in self.get_locations() if location.item and location.item.name == item and location.item.player == player) def create_item(self, item_name: str, player: int) -> Item: return self.worlds[player].create_item(item_name) def push_precollected(self, item: Item): item.world = self self.precollected_items[item.player].append(item) self.state.collect(item, True) def push_item(self, location: Location, item: Item, collect: bool = True): if not isinstance(location, Location): raise RuntimeError( 'Cannot assign item %s to invalid location %s (player %d).' % (item, location, item.player)) if location.can_fill(self.state, item, False): location.item = item item.location = location item.world = self # try to not have this here anymore if collect: self.state.collect(item, location.event, location) logging.debug('Placed %s at %s', item, location) else: raise RuntimeError('Cannot assign item %s to location %s.' % (item, location)) def get_entrances(self) -> List[Entrance]: if self._cached_entrances is None: self._cached_entrances = [entrance for region in self.regions for entrance in region.entrances] return self._cached_entrances def clear_entrance_cache(self): self._cached_entrances = None def get_locations(self) -> List[Location]: if self._cached_locations is None: self._cached_locations = [location for region in self.regions for location in region.locations] return self._cached_locations def clear_location_cache(self): self._cached_locations = None def get_unfilled_locations(self, player=None) -> List[Location]: if player is not None: return [location for location in self.get_locations() if location.player == player and not location.item] return [location for location in self.get_locations() if not location.item] def get_unfilled_dungeon_locations(self): return [location for location in self.get_locations() if not location.item and location.parent_region.dungeon] def get_filled_locations(self, player=None) -> List[Location]: if player is not None: return [location for location in self.get_locations() if location.player == player and location.item is not None] return [location for location in self.get_locations() if location.item is not None] def get_reachable_locations(self, state=None, player=None) -> List[Location]: if state is None: state = self.state return [location for location in self.get_locations() if (player is None or location.player == player) and location.can_reach(state)] def get_placeable_locations(self, state=None, player=None) -> List[Location]: if state is None: state = self.state return [location for location in self.get_locations() if (player is None or location.player == player) and location.item is None and location.can_reach(state)] def get_unfilled_locations_for_players(self, location_name: str, players: Iterable[int]): for player in players: location = self.get_location(location_name, player) if location.item is None: yield location def unlocks_new_location(self, item) -> bool: temp_state = self.state.copy() temp_state.collect(item, True) for location in self.get_unfilled_locations(): if temp_state.can_reach(location) and not self.state.can_reach(location): return True return False def has_beaten_game(self, state, player: Optional[int] = None): if player: return self.completion_condition[player](state) else: return all((self.has_beaten_game(state, p) for p in range(1, self.players + 1))) def can_beat_game(self, starting_state: Optional[CollectionState] = None): if starting_state: if self.has_beaten_game(starting_state): return True state = starting_state.copy() else: if self.has_beaten_game(self.state): return True state = CollectionState(self) prog_locations = {location for location in self.get_locations() if location.item and location.item.advancement and location not in state.locations_checked} while prog_locations: sphere = set() # build up spheres of collection radius. # Everything in each sphere is independent from each other in dependencies and only depends on lower spheres for location in prog_locations: if location.can_reach(state): sphere.add(location) if not sphere: # ran out of places and did not finish yet, quit return False for location in sphere: state.collect(location.item, True, location) prog_locations -= sphere if self.has_beaten_game(state): return True return False def get_spheres(self): state = CollectionState(self) locations = set(self.get_filled_locations()) while locations: sphere = set() for location in locations: if location.can_reach(state): sphere.add(location) yield sphere if not sphere: if locations: yield locations # unreachable locations break for location in sphere: state.collect(location.item, True, location) locations -= sphere def fulfills_accessibility(self, state: Optional[CollectionState] = None): """Check if accessibility rules are fulfilled with current or supplied state.""" if not state: state = CollectionState(self) players = {"minimal": set(), "items": set(), "locations": set()} for player, access in self.accessibility.items(): players[access.current_key].add(player) beatable_fulfilled = False def location_conditition(location: Location): """Determine if this location has to be accessible, location is already filtered by location_relevant""" if location.player in players["minimal"]: return False return True def location_relevant(location: Location): """Determine if this location is relevant to sweep.""" if location.player in players["locations"] or location.event or \ (location.item and location.item.advancement): return True return False def all_done(): """Check if all access rules are fulfilled""" if beatable_fulfilled: if any(location_conditition(location) for location in locations): return False # still locations required to be collected return True locations = {location for location in self.get_locations() if location_relevant(location)} while locations: sphere = set() for location in locations: if location.can_reach(state): sphere.add(location) if not sphere: # ran out of places and did not finish yet, quit logging.warning(f"Could not access required locations for accessibility check." f" Missing: {locations}") return False for location in sphere: locations.remove(location) state.collect(location.item, True, location) if self.has_beaten_game(state): beatable_fulfilled = True if all_done(): return True return False class CollectionState(object): def __init__(self, parent: MultiWorld): self.prog_items = Counter() self.world = parent self.reachable_regions = {player: set() for player in range(1, parent.players + 1)} self.blocked_connections = {player: set() for player in range(1, parent.players + 1)} self.events = set() self.path = {} self.locations_checked = set() self.stale = {player: True for player in range(1, parent.players + 1)} for items in parent.precollected_items.values(): for item in items: self.collect(item, True) def update_reachable_regions(self, player: int): from worlds.alttp.EntranceShuffle import indirect_connections self.stale[player] = False rrp = self.reachable_regions[player] bc = self.blocked_connections[player] queue = deque(self.blocked_connections[player]) start = self.world.get_region('Menu', player) # init on first call - this can't be done on construction since the regions don't exist yet if not start in rrp: rrp.add(start) bc.update(start.exits) queue.extend(start.exits) # run BFS on all connections, and keep track of those blocked by missing items while queue: connection = queue.popleft() new_region = connection.connected_region if new_region in rrp: bc.remove(connection) elif connection.can_reach(self): rrp.add(new_region) bc.remove(connection) bc.update(new_region.exits) queue.extend(new_region.exits) self.path[new_region] = (new_region.name, self.path.get(connection, None)) # Retry connections if the new region can unblock them if new_region.name in indirect_connections: new_entrance = self.world.get_entrance(indirect_connections[new_region.name], player) if new_entrance in bc and new_entrance not in queue: queue.append(new_entrance) def copy(self) -> CollectionState: ret = CollectionState(self.world) ret.prog_items = self.prog_items.copy() ret.reachable_regions = {player: copy.copy(self.reachable_regions[player]) for player in range(1, self.world.players + 1)} ret.blocked_connections = {player: copy.copy(self.blocked_connections[player]) for player in range(1, self.world.players + 1)} ret.events = copy.copy(self.events) ret.path = copy.copy(self.path) ret.locations_checked = copy.copy(self.locations_checked) return ret def can_reach(self, spot, resolution_hint=None, player=None) -> bool: if not hasattr(spot, "spot_type"): # try to resolve a name if resolution_hint == 'Location': spot = self.world.get_location(spot, player) elif resolution_hint == 'Entrance': spot = self.world.get_entrance(spot, player) else: # default to Region spot = self.world.get_region(spot, player) return spot.can_reach(self) def sweep_for_events(self, key_only: bool = False, locations=None): if locations is None: locations = self.world.get_filled_locations() new_locations = True # since the loop has a good chance to run more than once, only filter the events once locations = {location for location in locations if location.event} while new_locations: reachable_events = {location for location in locations if (not key_only or getattr(location.item, "locked_dungeon_item", False)) and location.can_reach(self)} new_locations = reachable_events - self.events for event in new_locations: self.events.add(event) self.collect(event.item, True, event) def has(self, item, player: int, count: int = 1): return self.prog_items[item, player] >= count def has_all(self, items: Set[str], player: int): return all(self.prog_items[item, player] for item in items) def has_any(self, items: Set[str], player: int): return any(self.prog_items[item, player] for item in items) def has_group(self, item_name_group: str, player: int, count: int = 1): found: int = 0 for item_name in self.world.worlds[player].item_name_groups[item_name_group]: found += self.prog_items[item_name, player] if found >= count: return True return False def count_group(self, item_name_group: str, player: int): found: int = 0 for item_name in self.world.worlds[player].item_name_groups[item_name_group]: found += self.prog_items[item_name, player] return found def can_buy_unlimited(self, item: str, player: int) -> bool: return any(shop.region.player == player and shop.has_unlimited(item) and shop.region.can_reach(self) for shop in self.world.shops) def can_buy(self, item: str, player: int) -> bool: return any(shop.region.player == player and shop.has(item) and shop.region.can_reach(self) for shop in self.world.shops) def item_count(self, item, player: int) -> int: return self.prog_items[item, player] def has_triforce_pieces(self, count: int, player: int) -> bool: return self.item_count('Triforce Piece', player) + self.item_count('Power Star', player) >= count def has_crystals(self, count: int, player: int) -> bool: found: int = 0 for crystalnumber in range(1, 8): found += self.prog_items[f"Crystal {crystalnumber}", player] if found >= count: return True return False def can_lift_rocks(self, player: int): return self.has('Power Glove', player) or self.has('Titans Mitts', player) def bottle_count(self, player: int) -> int: return min(self.world.difficulty_requirements[player].progressive_bottle_limit, self.count_group("Bottles", player)) def has_hearts(self, player: int, count: int) -> int: # Warning: This only considers items that are marked as advancement items return self.heart_count(player) >= count def heart_count(self, player: int) -> int: # Warning: This only considers items that are marked as advancement items diff = self.world.difficulty_requirements[player] return min(self.item_count('Boss Heart Container', player), diff.boss_heart_container_limit) \ + self.item_count('Sanctuary Heart Container', player) \ + min(self.item_count('Piece of Heart', player), diff.heart_piece_limit) // 4 \ + 3 # starting hearts def can_lift_heavy_rocks(self, player: int) -> bool: return self.has('Titans Mitts', player) def can_extend_magic(self, player: int, smallmagic: int = 16, fullrefill: bool = False): # This reflects the total magic Link has, not the total extra he has. basemagic = 8 if self.has('Magic Upgrade (1/4)', player): basemagic = 32 elif self.has('Magic Upgrade (1/2)', player): basemagic = 16 if self.can_buy_unlimited('Green Potion', player) or self.can_buy_unlimited('Blue Potion', player): if self.world.item_functionality[player] == 'hard' and not fullrefill: basemagic = basemagic + int(basemagic * 0.5 * self.bottle_count(player)) elif self.world.item_functionality[player] == 'expert' and not fullrefill: basemagic = basemagic + int(basemagic * 0.25 * self.bottle_count(player)) else: basemagic = basemagic + basemagic * self.bottle_count(player) return basemagic >= smallmagic def can_kill_most_things(self, player: int, enemies=5) -> bool: return (self.has_melee_weapon(player) or self.has('Cane of Somaria', player) or (self.has('Cane of Byrna', player) and (enemies < 6 or self.can_extend_magic(player))) or self.can_shoot_arrows(player) or self.has('Fire Rod', player) or (self.has('Bombs (10)', player) and enemies < 6)) def can_shoot_arrows(self, player: int) -> bool: if self.world.retro[player]: return (self.has('Bow', player) or self.has('Silver Bow', player)) and self.can_buy('Single Arrow', player) return self.has('Bow', player) or self.has('Silver Bow', player) def can_get_good_bee(self, player: int) -> bool: cave = self.world.get_region('Good Bee Cave', player) return ( self.has_group("Bottles", player) and self.has('Bug Catching Net', player) and (self.has('Pegasus Boots', player) or (self.has_sword(player) and self.has('Quake', player))) and cave.can_reach(self) and self.is_not_bunny(cave, player) ) def can_retrieve_tablet(self, player: int) -> bool: return self.has('Book of Mudora', player) and (self.has_beam_sword(player) or (self.world.swordless[player] and self.has("Hammer", player))) def has_sword(self, player: int) -> bool: return self.has('Fighter Sword', player) \ or self.has('Master Sword', player) \ or self.has('Tempered Sword', player) \ or self.has('Golden Sword', player) def has_beam_sword(self, player: int) -> bool: return self.has('Master Sword', player) or self.has('Tempered Sword', player) or self.has('Golden Sword', player) def has_melee_weapon(self, player: int) -> bool: return self.has_sword(player) or self.has('Hammer', player) def has_fire_source(self, player: int) -> bool: return self.has('Fire Rod', player) or self.has('Lamp', player) def can_melt_things(self, player: int) -> bool: return self.has('Fire Rod', player) or \ (self.has('Bombos', player) and (self.world.swordless[player] or self.has_sword(player))) def can_avoid_lasers(self, player: int) -> bool: return self.has('Mirror Shield', player) or self.has('Cane of Byrna', player) or self.has('Cape', player) def is_not_bunny(self, region: Region, player: int) -> bool: if self.has('Moon Pearl', player): return True return region.is_light_world if self.world.mode[player] != 'inverted' else region.is_dark_world def can_reach_light_world(self, player: int) -> bool: if True in [i.is_light_world for i in self.reachable_regions[player]]: return True return False def can_reach_dark_world(self, player: int) -> bool: if True in [i.is_dark_world for i in self.reachable_regions[player]]: return True return False def has_misery_mire_medallion(self, player: int) -> bool: return self.has(self.world.required_medallions[player][0], player) def has_turtle_rock_medallion(self, player: int) -> bool: return self.has(self.world.required_medallions[player][1], player) def can_boots_clip_lw(self, player): if self.world.mode[player] == 'inverted': return self.has('Pegasus Boots', player) and self.has('Moon Pearl', player) return self.has('Pegasus Boots', player) def can_boots_clip_dw(self, player): if self.world.mode[player] != 'inverted': return self.has('Pegasus Boots', player) and self.has('Moon Pearl', player) return self.has('Pegasus Boots', player) def can_get_glitched_speed_lw(self, player): rules = [self.has('Pegasus Boots', player), any([self.has('Hookshot', player), self.has_sword(player)])] if self.world.mode[player] == 'inverted': rules.append(self.has('Moon Pearl', player)) return all(rules) def can_superbunny_mirror_with_sword(self, player): return self.has('Magic Mirror', player) and self.has_sword(player) def can_get_glitched_speed_dw(self, player: int): rules = [self.has('Pegasus Boots', player), any([self.has('Hookshot', player), self.has_sword(player)])] if self.world.mode[player] != 'inverted': rules.append(self.has('Moon Pearl', player)) return all(rules) def can_bomb_clip(self, region: Region, player: int) -> bool: return self.is_not_bunny(region, player) and self.has('Pegasus Boots', player) def collect(self, item: Item, event: bool = False, location: Location = None) -> bool: if location: self.locations_checked.add(location) changed = self.world.worlds[item.player].collect(self, item) if not changed and event: self.prog_items[item.name, item.player] += 1 changed = True self.stale[item.player] = True if changed and not event: self.sweep_for_events() return changed def remove(self, item): changed = self.world.worlds[item.player].remove(self, item) if changed: # invalidate caches, nothing can be trusted anymore now self.reachable_regions[item.player] = set() self.blocked_connections[item.player] = set() self.stale[item.player] = True @unique class RegionType(int, Enum): Generic = 0 LightWorld = 1 DarkWorld = 2 Cave = 3 # Also includes Houses Dungeon = 4 @property def is_indoors(self): """Shorthand for checking if Cave or Dungeon""" return self in (RegionType.Cave, RegionType.Dungeon) class Region(object): def __init__(self, name: str, type, hint, player: int, world: Optional[MultiWorld] = None): self.name = name self.type = type self.entrances = [] self.exits = [] self.locations = [] self.dungeon = None self.shop = None self.world = world self.is_light_world = False # will be set after making connections. self.is_dark_world = False self.spot_type = 'Region' self.hint_text = hint self.player = player def can_reach(self, state: CollectionState): if state.stale[self.player]: state.update_reachable_regions(self.player) return self in state.reachable_regions[self.player] def can_reach_private(self, state: CollectionState): for entrance in self.entrances: if entrance.can_reach(state): if not self in state.path: state.path[self] = (self.name, state.path.get(entrance, None)) return True return False def __repr__(self): return self.__str__() def __str__(self): return self.world.get_name_string_for_object(self) if self.world else f'{self.name} (Player {self.player})' class Entrance(object): spot_type = 'Entrance' def __init__(self, player: int, name: str = '', parent=None): self.name = name self.parent_region = parent self.connected_region = None self.target = None self.addresses = None self.access_rule = lambda state: True self.player = player self.hide_path = False def can_reach(self, state): if self.parent_region.can_reach(state) and self.access_rule(state): if not self.hide_path and not self in state.path: state.path[self] = (self.name, state.path.get(self.parent_region, (self.parent_region.name, None))) return True return False def connect(self, region, addresses=None, target=None): self.connected_region = region self.target = target self.addresses = addresses region.entrances.append(self) def __repr__(self): return self.__str__() def __str__(self): world = self.parent_region.world if self.parent_region else None return world.get_name_string_for_object(self) if world else f'{self.name} (Player {self.player})' class Dungeon(object): def __init__(self, name: str, regions, big_key, small_keys, dungeon_items, player: int): self.name = name self.regions = regions self.big_key = big_key self.small_keys = small_keys self.dungeon_items = dungeon_items self.bosses = dict() self.player = player self.world = None @property def boss(self): return self.bosses.get(None, None) @boss.setter def boss(self, value): self.bosses[None] = value @property def keys(self): return self.small_keys + ([self.big_key] if self.big_key else []) @property def all_items(self): return self.dungeon_items + self.keys def is_dungeon_item(self, item: Item) -> bool: return item.player == self.player and item.name in (dungeon_item.name for dungeon_item in self.all_items) def __eq__(self, other: Dungeon) -> bool: if not other: return False return self.name == other.name and self.player == other.player def __repr__(self): return self.__str__() def __str__(self): return self.world.get_name_string_for_object(self) if self.world else f'{self.name} (Player {self.player})' class Boss(): def __init__(self, name, enemizer_name, defeat_rule, player: int): self.name = name self.enemizer_name = enemizer_name self.defeat_rule = defeat_rule self.player = player def can_defeat(self, state) -> bool: return self.defeat_rule(state, self.player) def __repr__(self): return f"Boss({self.name})" class Location(): # If given as integer, then this is the shop's inventory index shop_slot: Optional[int] = None shop_slot_disabled: bool = False event: bool = False locked: bool = False spot_type = 'Location' game: str = "Generic" show_in_spoiler: bool = True excluded: bool = False crystal: bool = False always_allow = staticmethod(lambda item, state: False) access_rule = staticmethod(lambda state: True) item_rule = staticmethod(lambda item: True) def __init__(self, player: int, name: str = '', address: int = None, parent=None): self.name: str = name self.address: Optional[int] = address self.parent_region: Region = parent self.player: int = player self.item: Optional[Item] = None def can_fill(self, state: CollectionState, item: Item, check_access=True) -> bool: return self.always_allow(state, item) or (self.item_rule(item) and (not check_access or self.can_reach(state))) def can_reach(self, state: CollectionState) -> bool: # self.access_rule computes faster on average, so placing it first for faster abort if self.access_rule(state) and self.parent_region.can_reach(state): return True return False def place_locked_item(self, item: Item): if self.item: raise Exception(f"Location {self} already filled.") self.item = item self.event = item.advancement self.item.world = self.parent_region.world self.locked = True def __repr__(self): return self.__str__() def __str__(self): world = self.parent_region.world if self.parent_region and self.parent_region.world else None return world.get_name_string_for_object(self) if world else f'{self.name} (Player {self.player})' def __hash__(self): return hash((self.name, self.player)) def __lt__(self, other): return (self.player, self.name) < (other.player, other.name) @property def native_item(self) -> bool: """Returns True if the item in this location matches game.""" return self.item and self.item.game == self.game @property def hint_text(self): hint_text = getattr(self, "_hint_text", None) if hint_text: return hint_text return "at " + self.name.replace("_", " ").replace("-", " ") class Item(): location: Optional[Location] = None world: Optional[MultiWorld] = None code: Optional[int] = None # an item with ID None is called an Event, and does not get written to multidata name: str game: str = "Generic" type: str = None # indicates if this is a negative impact item. Causes these to be handled differently by various games. trap: bool = False # change manually to ensure that a specific non-progression item never goes on an excluded location never_exclude = False # need to find a decent place for these to live and to allow other games to register texts if they want. pedestal_credit_text: str = "and the Unknown Item" sickkid_credit_text: Optional[str] = None magicshop_credit_text: Optional[str] = None zora_credit_text: Optional[str] = None fluteboy_credit_text: Optional[str] = None # hopefully temporary attributes to satisfy legacy LttP code, proper implementation in subclass ALttPItem smallkey: bool = False bigkey: bool = False map: bool = False compass: bool = False def __init__(self, name: str, advancement: bool, code: Optional[int], player: int): self.name = name self.advancement = advancement self.player = player self.code = code @property def hint_text(self): return getattr(self, "_hint_text", self.name.replace("_", " ").replace("-", " ")) @property def pedestal_hint_text(self): return getattr(self, "_pedestal_hint_text", self.name.replace("_", " ").replace("-", " ")) def __eq__(self, other): return self.name == other.name and self.player == other.player def __lt__(self, other): if other.player != self.player: return other.player < self.player return self.name < other.name def __hash__(self): return hash((self.name, self.player)) def __repr__(self): return self.__str__() def __str__(self): return self.world.get_name_string_for_object(self) if self.world else f'{self.name} (Player {self.player})' class Spoiler(): world: MultiWorld def __init__(self, world): self.world = world self.hashes = {} self.entrances = OrderedDict() self.medallions = {} self.playthrough = {} self.unreachables = [] self.locations = {} self.paths = {} self.shops = [] self.bosses = OrderedDict() def set_entrance(self, entrance, exit, direction, player): if self.world.players == 1: self.entrances[(entrance, direction, player)] = OrderedDict( [('entrance', entrance), ('exit', exit), ('direction', direction)]) else: self.entrances[(entrance, direction, player)] = OrderedDict( [('player', player), ('entrance', entrance), ('exit', exit), ('direction', direction)]) def parse_data(self): self.medallions = OrderedDict() for player in self.world.get_game_players("A Link to the Past"): self.medallions[f'Misery Mire ({self.world.get_player_name(player)})'] = \ self.world.required_medallions[player][0] self.medallions[f'Turtle Rock ({self.world.get_player_name(player)})'] = \ self.world.required_medallions[player][1] self.locations = OrderedDict() listed_locations = set() lw_locations = [loc for loc in self.world.get_locations() if loc not in listed_locations and loc.parent_region and loc.parent_region.type == RegionType.LightWorld and loc.show_in_spoiler] self.locations['Light World'] = OrderedDict( [(str(location), str(location.item) if location.item is not None else 'Nothing') for location in lw_locations]) listed_locations.update(lw_locations) dw_locations = [loc for loc in self.world.get_locations() if loc not in listed_locations and loc.parent_region and loc.parent_region.type == RegionType.DarkWorld and loc.show_in_spoiler] self.locations['Dark World'] = OrderedDict( [(str(location), str(location.item) if location.item is not None else 'Nothing') for location in dw_locations]) listed_locations.update(dw_locations) cave_locations = [loc for loc in self.world.get_locations() if loc not in listed_locations and loc.parent_region and loc.parent_region.type == RegionType.Cave and loc.show_in_spoiler] self.locations['Caves'] = OrderedDict( [(str(location), str(location.item) if location.item is not None else 'Nothing') for location in cave_locations]) listed_locations.update(cave_locations) for dungeon in self.world.dungeons.values(): dungeon_locations = [loc for loc in self.world.get_locations() if loc not in listed_locations and loc.parent_region and loc.parent_region.dungeon == dungeon and loc.show_in_spoiler] self.locations[str(dungeon)] = OrderedDict( [(str(location), str(location.item) if location.item is not None else 'Nothing') for location in dungeon_locations]) listed_locations.update(dungeon_locations) other_locations = [loc for loc in self.world.get_locations() if loc not in listed_locations and loc.show_in_spoiler] if other_locations: self.locations['Other Locations'] = OrderedDict( [(str(location), str(location.item) if location.item is not None else 'Nothing') for location in other_locations]) listed_locations.update(other_locations) self.shops = [] from worlds.alttp.Shops import ShopType, price_type_display_name, price_rate_display for shop in self.world.shops: if not shop.custom: continue shopdata = { 'location': str(shop.region), 'type': 'Take Any' if shop.type == ShopType.TakeAny else 'Shop' } for index, item in enumerate(shop.inventory): if item is None: continue my_price = item['price'] // price_rate_display.get(item['price_type'], 1) shopdata['item_{}'.format( index)] = f"{item['item']} — {my_price} {price_type_display_name[item['price_type']]}" if item['player'] > 0: shopdata['item_{}'.format(index)] = shopdata['item_{}'.format(index)].replace('—', '(Player {}) — '.format( item['player'])) if item['max'] == 0: continue shopdata['item_{}'.format(index)] += " x {}".format(item['max']) if item['replacement'] is None: continue shopdata['item_{}'.format( index)] += f", {item['replacement']} - {item['replacement_price']} {price_type_display_name[item['replacement_price_type']]}" self.shops.append(shopdata) for player in self.world.get_game_players("A Link to the Past"): self.bosses[str(player)] = OrderedDict() self.bosses[str(player)]["Eastern Palace"] = self.world.get_dungeon("Eastern Palace", player).boss.name self.bosses[str(player)]["Desert Palace"] = self.world.get_dungeon("Desert Palace", player).boss.name self.bosses[str(player)]["Tower Of Hera"] = self.world.get_dungeon("Tower of Hera", player).boss.name self.bosses[str(player)]["Hyrule Castle"] = "Agahnim" self.bosses[str(player)]["Palace Of Darkness"] = self.world.get_dungeon("Palace of Darkness", player).boss.name self.bosses[str(player)]["Swamp Palace"] = self.world.get_dungeon("Swamp Palace", player).boss.name self.bosses[str(player)]["Skull Woods"] = self.world.get_dungeon("Skull Woods", player).boss.name self.bosses[str(player)]["Thieves Town"] = self.world.get_dungeon("Thieves Town", player).boss.name self.bosses[str(player)]["Ice Palace"] = self.world.get_dungeon("Ice Palace", player).boss.name self.bosses[str(player)]["Misery Mire"] = self.world.get_dungeon("Misery Mire", player).boss.name self.bosses[str(player)]["Turtle Rock"] = self.world.get_dungeon("Turtle Rock", player).boss.name if self.world.mode[player] != 'inverted': self.bosses[str(player)]["Ganons Tower Basement"] = \ self.world.get_dungeon('Ganons Tower', player).bosses['bottom'].name self.bosses[str(player)]["Ganons Tower Middle"] = self.world.get_dungeon('Ganons Tower', player).bosses[ 'middle'].name self.bosses[str(player)]["Ganons Tower Top"] = self.world.get_dungeon('Ganons Tower', player).bosses[ 'top'].name else: self.bosses[str(player)]["Ganons Tower Basement"] = \ self.world.get_dungeon('Inverted Ganons Tower', player).bosses['bottom'].name self.bosses[str(player)]["Ganons Tower Middle"] = \ self.world.get_dungeon('Inverted Ganons Tower', player).bosses['middle'].name self.bosses[str(player)]["Ganons Tower Top"] = \ self.world.get_dungeon('Inverted Ganons Tower', player).bosses['top'].name self.bosses[str(player)]["Ganons Tower"] = "Agahnim 2" self.bosses[str(player)]["Ganon"] = "Ganon" def to_json(self): self.parse_data() out = OrderedDict() out['Entrances'] = list(self.entrances.values()) out.update(self.locations) out['Special'] = self.medallions if self.hashes: out['Hashes'] = self.hashes if self.shops: out['Shops'] = self.shops out['playthrough'] = self.playthrough out['paths'] = self.paths out['Bosses'] = self.bosses return json.dumps(out) def to_file(self, filename): from worlds.AutoWorld import call_all, call_single, call_stage self.parse_data() def bool_to_text(variable: Union[bool, str]) -> str: if type(variable) == str: return variable return 'Yes' if variable else 'No' def write_option(option_key: str, option_obj: type(Options.Option)): res = getattr(self.world, option_key)[player] displayname = getattr(option_obj, "displayname", option_key) try: outfile.write(f'{displayname + ":":33}{res.get_current_option_name()}\n') except: raise Exception with open(filename, 'w', encoding="utf-8-sig") as outfile: outfile.write( 'Archipelago Version %s - Seed: %s\n\n' % ( Utils.__version__, self.world.seed)) outfile.write('Filling Algorithm: %s\n' % self.world.algorithm) outfile.write('Players: %d\n' % self.world.players) call_stage(self.world, "write_spoiler_header", outfile) for player in range(1, self.world.players + 1): if self.world.players > 1: outfile.write('\nPlayer %d: %s\n' % (player, self.world.get_player_name(player))) outfile.write('Game: %s\n' % self.world.game[player]) for f_option, option in Options.common_options.items(): write_option(f_option, option) for f_option, option in Options.per_game_common_options.items(): write_option(f_option, option) options = self.world.worlds[player].options if options: for f_option, option in options.items(): write_option(f_option, option) call_single(self.world, "write_spoiler_header", player, outfile) if player in self.world.get_game_players("A Link to the Past"): outfile.write('%s%s\n' % ('Hash: ', self.hashes[player])) outfile.write('Logic: %s\n' % self.world.logic[player]) outfile.write('Dark Room Logic: %s\n' % self.world.dark_room_logic[player]) outfile.write('Mode: %s\n' % self.world.mode[player]) outfile.write('Goal: %s\n' % self.world.goal[player]) if "triforce" in self.world.goal[player]: # triforce hunt outfile.write("Pieces available for Triforce: %s\n" % self.world.triforce_pieces_available[player]) outfile.write("Pieces required for Triforce: %s\n" % self.world.triforce_pieces_required[player]) outfile.write('Difficulty: %s\n' % self.world.difficulty[player]) outfile.write('Item Functionality: %s\n' % self.world.item_functionality[player]) outfile.write('Entrance Shuffle: %s\n' % self.world.shuffle[player]) if self.world.shuffle[player] != "vanilla": outfile.write('Entrance Shuffle Seed %s\n' % self.world.worlds[player].er_seed) outfile.write('Pyramid hole pre-opened: %s\n' % ( 'Yes' if self.world.open_pyramid[player] else 'No')) outfile.write('Shop inventory shuffle: %s\n' % bool_to_text("i" in self.world.shop_shuffle[player])) outfile.write('Shop price shuffle: %s\n' % bool_to_text("p" in self.world.shop_shuffle[player])) outfile.write('Shop upgrade shuffle: %s\n' % bool_to_text("u" in self.world.shop_shuffle[player])) outfile.write('New Shop inventory: %s\n' % bool_to_text("g" in self.world.shop_shuffle[player] or "f" in self.world.shop_shuffle[player])) outfile.write('Custom Potion Shop: %s\n' % bool_to_text("w" in self.world.shop_shuffle[player])) outfile.write('Boss shuffle: %s\n' % self.world.boss_shuffle[player]) outfile.write('Enemy health: %s\n' % self.world.enemy_health[player]) outfile.write('Enemy damage: %s\n' % self.world.enemy_damage[player]) outfile.write('Prize shuffle %s\n' % self.world.shuffle_prizes[player]) if self.entrances: outfile.write('\n\nEntrances:\n\n') outfile.write('\n'.join(['%s%s %s %s' % (f'{self.world.get_player_name(entry["player"])}: ' if self.world.players > 1 else '', entry['entrance'], '<=>' if entry['direction'] == 'both' else '<=' if entry['direction'] == 'exit' else '=>', entry['exit']) for entry in self.entrances.values()])) if self.medallions: outfile.write('\n\nMedallions:\n') for dungeon, medallion in self.medallions.items(): outfile.write(f'\n{dungeon}: {medallion}') call_all(self.world, "write_spoiler", outfile) outfile.write('\n\nLocations:\n\n') outfile.write('\n'.join( ['%s: %s' % (location, item) for grouping in self.locations.values() for (location, item) in grouping.items()])) if self.shops: outfile.write('\n\nShops:\n\n') outfile.write('\n'.join("{} [{}]\n {}".format(shop['location'], shop['type'], "\n ".join( item for item in [shop.get('item_0', None), shop.get('item_1', None), shop.get('item_2', None)] if item)) for shop in self.shops)) for player in self.world.get_game_players("A Link to the Past"): if self.world.boss_shuffle[player] != 'none': bossmap = self.bosses[str(player)] if self.world.players > 1 else self.bosses outfile.write( f'\n\nBosses{(f" ({self.world.get_player_name(player)})" if self.world.players > 1 else "")}:\n') outfile.write(' ' + '\n '.join([f'{x}: {y}' for x, y in bossmap.items()])) outfile.write('\n\nPlaythrough:\n\n') outfile.write('\n'.join(['%s: {\n%s\n}' % (sphere_nr, '\n'.join( [' %s: %s' % (location, item) for (location, item) in sphere.items()] if sphere_nr != '0' else [ f' {item}' for item in sphere])) for (sphere_nr, sphere) in self.playthrough.items()])) if self.unreachables: outfile.write('\n\nUnreachable Items:\n\n') outfile.write( '\n'.join(['%s: %s' % (unreachable.item, unreachable) for unreachable in self.unreachables])) if self.paths: outfile.write('\n\nPaths:\n\n') path_listings = [] for location, path in sorted(self.paths.items()): path_lines = [] for region, exit in path: if exit is not None: path_lines.append("{} -> {}".format(region, exit)) else: path_lines.append(region) path_listings.append("{}\n {}".format(location, "\n => ".join(path_lines))) outfile.write('\n'.join(path_listings)) call_all(self.world, "write_spoiler_end", outfile) seeddigits = 20 def get_seed(seed=None): if seed is None: random.seed(None) return random.randint(0, pow(10, seeddigits) - 1) return seed <file_sep>import unittest from BaseClasses import MultiWorld from worlds.AutoWorld import AutoWorldRegister class TestBase(unittest.TestCase): world: MultiWorld _state_cache = {} def testUniqueItems(self): known_item_ids = set() for gamename, world_type in AutoWorldRegister.world_types.items(): current = len(known_item_ids) known_item_ids |= set(world_type.item_id_to_name) self.assertEqual(len(known_item_ids) - len(world_type.item_id_to_name), current) def testUniqueLocations(self): known_location_ids = set() for gamename, world_type in AutoWorldRegister.world_types.items(): current = len(known_location_ids) known_location_ids |= set(world_type.location_id_to_name) self.assertEqual(len(known_location_ids) - len(world_type.location_id_to_name), current) <file_sep>import logging import typing logger = logging.getLogger("Subnautica") from .Locations import lookup_name_to_id as locations_lookup_name_to_id from .Items import item_table, lookup_name_to_item, advancement_item_names from .Items import lookup_name_to_id as items_lookup_name_to_id from .Regions import create_regions from .Rules import set_rules from .Options import options from BaseClasses import Region, Entrance, Location, MultiWorld, Item from ..AutoWorld import World class SubnauticaWorld(World): """ Subnautica is an undersea exploration game. Stranded on an alien world, you become infected by an unknown bacteria. The planet's automatic quarantine will shoot you down if you try to leave. You must find a cure for yourself, build an escape rocket, and leave the planet. """ game: str = "Subnautica" item_name_to_id = items_lookup_name_to_id location_name_to_id = locations_lookup_name_to_id options = options data_version = 2 def generate_basic(self): # Link regions self.world.get_entrance('Lifepod 5', self.player).connect(self.world.get_region('Planet 4546B', self.player)) # Generate item pool pool = [] neptune_launch_platform = None extras = 0 valuable = self.world.item_pool[self.player] == "valuable" for item in item_table: for i in range(item["count"]): subnautica_item = self.create_item(item["name"]) if item["name"] == "Neptune Launch Platform": neptune_launch_platform = subnautica_item elif valuable and not item["progression"]: self.world.push_precollected(subnautica_item) extras += 1 else: pool.append(subnautica_item) for item_name in self.world.random.choices(sorted(advancement_item_names - {"Neptune Launch Platform"}), k=extras): item = self.create_item(item_name) item.advancement = False # as it's an extra, just fast-fill it somewhere pool.append(item) self.world.itempool += pool # Victory item self.world.get_location("Aurora - Captain Data Terminal", self.player).place_locked_item( neptune_launch_platform) self.world.get_location("Neptune Launch", self.player).place_locked_item( SubnauticaItem("Victory", True, None, player=self.player)) def set_rules(self): set_rules(self.world, self.player) def create_regions(self): create_regions(self.world, self.player) def fill_slot_data(self): slot_data = {} return slot_data def create_item(self, name: str) -> Item: item = lookup_name_to_item[name] return SubnauticaItem(name, item["progression"], item["id"], player=self.player) def get_required_client_version(self) -> typing.Tuple[int, int, int]: return max((0, 1, 9), super(SubnauticaWorld, self).get_required_client_version()) def create_region(world: MultiWorld, player: int, name: str, locations=None, exits=None): ret = Region(name, None, name, player) ret.world = world if locations: for location in locations: loc_id = locations_lookup_name_to_id.get(location, 0) location = SubnauticaLocation(player, location, loc_id, ret) ret.locations.append(location) if exits: for exit in exits: ret.exits.append(Entrance(player, exit, ret)) return ret class SubnauticaLocation(Location): game: str = "Subnautica" class SubnauticaItem(Item): game = "Subnautica" <file_sep># Minecraft ## Where is the settings page? The player settings page for this game is located <a href="../player-settings">here</a>. It contains all the options you need to configure and export a config file. ## What does randomization do to this game? Recipes are removed from the crafting book and shuffled into the item pool. It can also optionally change which structures appear in each dimension. Crafting recipes are re-learned when they are received from other players as item checks, and occasionally when completing your own achievements. ## What is considered a location check in minecraft? Location checks in are completed when the player completes various Minecraft achievements. Opening the advancements menu in-game by pressing "L" will display outstanding achievements. ## When the player receives an item, what happens? When the player receives an item in Minecraft, it either unlocks crafting recipes or puts items into the player's inventory directly. ## What is the victory condition? Victory is achieved when the player kills the Ender Dragon, enters the portal in The End, and completes the credits sequence either by skipping it or watching hit play out. <file_sep># Archipelago Plando Guide ## What is Plando? The purposes of randomizers is to randomize the items in a game to give a new experience. Plando takes this concept and changes it up by allowing you to plan out certain aspects of the game by placing certain items in certain locations, certain bosses in certain rooms, edit text for certain NPCs/signs, or even force certain region connections. Each of these options are going to be detailed separately as `item plando`, `boss plando`, `text plando`, and `connection plando`. Every game in archipelago supports item plando but the other plando options are only supported by certain games. Currently, Minecraft and LTTP both support connection plando, but only LTTP supports text and boss plando. ### Enabling Plando On the website plando will already be enabled. If you will be generating the game locally plando features must be enabled (opt-in). * To opt-in go to the archipelago installation (default: `C:\ProgramData\Archipelago`), open the host.yaml with a text editor and find the `plando_options` key. The available plando modules can be enabled by adding them after this such as `plando_options: bosses, items, texts, connections`. ## Item Plando Item plando allows a player to place an item in a specific location or specific locations, place multiple items into a list of specific locations both in their own game or in another player's game. **Note that there's a very good chance that cross-game plando could very well be broken i.e. placing on of your items in someone else's world playing a different game.** * The options for item plando are `from_pool`, `world`, `percentage`, `force`, and either item and location, or items and locations. * `from_pool` determines if the item should be taken *from* the item pool or *added* to it. This can be true or false and defaults to true if omitted. * `world` is the target world to place the item in. * It gets ignored if only one world is generated. * Can be a number, name, true, false, or null. False is the default. * If a number is used it targets that slot or player number in the multiworld. * If a name is used it will target the world with that player name. * If set to true it will be any player's world besides your own. * If set to false it will target your own world. * If set to null it will target a random world in the multiworld. * `force` determines whether the generator will fail if the item can't be placed in the location can be true, false, or silent. Silent is the default. * If set to true the item must be placed and the generator will throw an error if it is unable to do so. * If set to false the generator will log a warning if the placement can't be done but will still generate. * If set to silent and the placement fails it will be ignored entirely. * `percentage` is the percentage chance for the relevant block to trigger. This can be any value from 0 to 100 and if omitted will default to 100. * Single Placement is when you use a plando block to place a single item at a single location. * `item` is the item you would like to place and `location` is the location to place it. * Multi Placement uses a plando block to place multiple items in multiple locations until either list is exhausted. * `items` defines the items to use and a number letting you place multiple of it. * `locations` is a list of possible locations those items can be placed in. * Using the multi placement method, placements are picked randomly. ### Available Items * [A Link to the Past](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/alttp/Items.py#L52) * [Factorio Non-Progressive](https://wiki.factorio.com/Technologies) Note that these use the *internal names*. For example, `advanced-electronics` * [Factorio Progressive](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/factorio/Technologies.py#L374) * [Minecraft](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/minecraft/Items.py#L14) * [Ocarina of Time](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/oot/Items.py#L61) * [Risk of Rain 2](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/ror2/Items.py#L8) * [Slay the Spire](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/spire/Items.py#L13) * [Subnautica](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/subnautica/items.json) * [Timespinner](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/timespinner/Items.py#L11) ### Available Locations * [A Link to the Past](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/alttp/Regions.py#L429) * [Factorio](https://wiki.factorio.com/Technologies) Same as items * [Minecraft](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/minecraft/Locations.py#L18) * [Ocarina of Time](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/oot/LocationList.py#L38) * [Risk of Rain 2](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/ror2/Locations.py#L17) This is a special case. The locations are "ItemPickup[number]" up to the maximum set in the yaml. * [Slay the Spire](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/spire/Locations.py) * [Subnautica](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/subnautica/locations.json) * [Timespinner](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/timespinner/Locations.py#L13) A list of all available items and locations can also be found in the [server's datapackage](/api/datapackage). ### Examples ```yaml plando_items: # example block 1 - Timespinner - item: Empire Orb: 1 Radiant Orb: 1 location: Starter Chest 1 from_pool: true world: true percentage: 50 # example block 2 - Ocarina of Time - items: Kokiri Sword: 1 Biggoron Sword: 1 Bow: 1 Magic Meter: 1 Progressive Strength Upgrade: 3 Progressive Hookshot: 2 locations: - Deku Tree Slingshot Chest - Dodongos Cavern Bomb Bag Chest - Jabu Jabus Belly Boomerang Chest - Bottom of the Well Lens of Truth Chest - Forest Temple Bow Chest - Fire Temple Megaton Hammer Chest - Water Temple Longshot Chest - Shadow Temple Hover Boots Chest - Spirit Temple Silver Gauntlets Chest world: false # example block 3 - Slay the Spire - items: Boss Relic: 3 locations: Boss Relic 1 Boss Relic 2 Boss Relic 3 # example block 4 - Factorio - items: progressive-electric-energy-distribution: 2 electric-energy-accumulators: 1 progressive-turret: 2 locations: military gun-turret logistic-science-pack steel-processing percentage: 80 force: true ``` 1. This block has a 50% chance to occur, and if it does will place either the Empire Orb or Radiant Orb on another player's Starter Chest 1 and removes the chosen item from the item pool. 2. This block will always trigger and will place the player's swords, bow, magic meter, strength upgrades, and hookshots in their own dungeon major item chests. 3. This block will always trigger and will lock boss relics on the bosses. 4. This block has an 80% chance of occuring and when it does will place all but 1 of the items randomly among the four locations chosen here. ## Boss Plando As this is currently only supported by A Link to the Past instead of explaining here please refer to the [relevant guide](/tutorial/zelda3/plando/en) ## Text Plando As this is currently only supported by A Link to the Past instead of explaining here please refer to the [relevant guide](/tutorial/zelda3/plando/en) ## Connections Plando This is currently only supported by Minecraft and A Link to the Past. As the way that these games interact with their connections is different I will only explain the basics here while more specifics for Link to the Past connection plando can be found in its plando guide. * The options for connections are `percentage`, `entrance`, `exit`, and `direction`. Each of these options support subweights. * `percentage` is the percentage chance for this connection from 0 to 100 and defaults to 100. * Every connection has an `entrance` and an `exit`. These can be unlinked like in A Link to the Past insanity entrance shuffle. * `direction` can be `both`, `entrance`, or `exit` and determines in which direction this connection will operate. [Link to the Past connections](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/alttp/EntranceShuffle.py#L3852) [Minecraft connections](https://github.com/ArchipelagoMW/Archipelago/blob/main/worlds/minecraft/Regions.py#L62) ### Examples ```yaml plando_connections: # example block 1 - Link to the Past - entrance: Cave Shop (Lake Hylia) exit: Cave 45 direction: entrance - entrance: Cave 45 exit: Cave Shop (Lake Hylia) direction: entrance - entrance: Agahnims Tower exit: Old Man Cave Exit (West) direction: exit # example block 2 - Minecraft - entrance: Overworld Structure 1 exit: Nether Fortress direction: both - entrance: Overworld Structure 2 exit: Village direction: both ``` 1. These connections are decoupled so going into the lake hylia cave shop will take you to the inside of cave 45 and when you leave the interior you will exit to the cave 45 ledge. Going into the cave 45 entrance will then take you to the lake hylia cave shop. Walking into the entrance for the old man cave and Agahnim's Tower entrance will both take you to their locations as normal but leaving old man cave will exit at Agahnim's Tower. 2. This will force a nether fortress and a village to be the overworld structures for your game. Note that for the Minecraft connection plando to work structure shuffle must be enabled.<file_sep> def shuffle_random_entrances(ootworld): world = ootworld.world player = ootworld.player # Gather locations to keep reachable for validation # Set entrance data for all entrances # Determine entrance pools based on settings # Mark shuffled entrances # Build target entrance pools # Place priority entrances # Delete priority targets from one-way pools # Shuffle all entrance pools, in order # Verification steps: # All entrances are properly connected to a region # Game is beatable # Validate world <file_sep>from __future__ import annotations import logging import asyncio import urllib.parse import sys import os import typing import time import websockets import Utils from MultiServer import CommandProcessor from NetUtils import Endpoint, decode, NetworkItem, encode, JSONtoTextParser, ClientStatus, Permission from Utils import Version from worlds import network_data_package, AutoWorldRegister logger = logging.getLogger("Client") gui_enabled = Utils.is_frozen() or "--nogui" not in sys.argv log_folder = Utils.local_path("logs") os.makedirs(log_folder, exist_ok=True) class ClientCommandProcessor(CommandProcessor): def __init__(self, ctx: CommonContext): self.ctx = ctx def output(self, text: str): logger.info(text) def _cmd_exit(self) -> bool: """Close connections and client""" self.ctx.exit_event.set() return True def _cmd_connect(self, address: str = "") -> bool: """Connect to a MultiWorld Server""" self.ctx.server_address = None asyncio.create_task(self.ctx.connect(address if address else None)) return True def _cmd_disconnect(self) -> bool: """Disconnect from a MultiWorld Server""" self.ctx.server_address = None asyncio.create_task(self.ctx.disconnect()) return True def _cmd_received(self) -> bool: """List all received items""" logger.info(f'{len(self.ctx.items_received)} received items:') for index, item in enumerate(self.ctx.items_received, 1): self.output(f"{self.ctx.item_name_getter(item.item)} from {self.ctx.player_names[item.player]}") return True def _cmd_missing(self) -> bool: """List all missing location checks, from your local game state""" if not self.ctx.game: self.output("No game set, cannot determine missing checks.") return count = 0 checked_count = 0 for location, location_id in AutoWorldRegister.world_types[self.ctx.game].location_name_to_id.items(): if location_id < 0: continue if location_id not in self.ctx.locations_checked: if location_id in self.ctx.missing_locations: self.output('Missing: ' + location) count += 1 elif location_id in self.ctx.checked_locations: self.output('Checked: ' + location) count += 1 checked_count += 1 if count: self.output( f"Found {count} missing location checks{f'. {checked_count} location checks previously visited.' if checked_count else ''}") else: self.output("No missing location checks found.") return True def _cmd_ready(self): self.ctx.ready = not self.ctx.ready if self.ctx.ready: state = ClientStatus.CLIENT_READY self.output("Readied up.") else: state = ClientStatus.CLIENT_CONNECTED self.output("Unreadied.") asyncio.create_task(self.ctx.send_msgs([{"cmd": "StatusUpdate", "status": state}])) def default(self, raw: str): asyncio.create_task(self.ctx.send_msgs([{"cmd": "Say", "text": raw}])) class CommonContext(): tags: typing.Set[str] = {"AP"} starting_reconnect_delay: int = 5 current_reconnect_delay: int = starting_reconnect_delay command_processor: int = ClientCommandProcessor game = None ui = None keep_alive_task = None def __init__(self, server_address, password): # server state self.server_address = server_address self.password = <PASSWORD> self.server_task = None self.server: typing.Optional[Endpoint] = None self.server_version = Version(0, 0, 0) self.hint_cost: typing.Optional[int] = None self.games: typing.Dict[int, str] = {} self.permissions = { "forfeit": "disabled", "collect": "disabled", "remaining": "disabled", } # own state self.finished_game = False self.ready = False self.team = None self.slot = None self.auth = None self.seed_name = None self.locations_checked: typing.Set[int] = set() # local state self.locations_scouted: typing.Set[int] = set() self.items_received = [] self.missing_locations: typing.Set[int] = set() self.checked_locations: typing.Set[int] = set() # server state self.locations_info = {} self.input_queue = asyncio.Queue() self.input_requests = 0 self.last_death_link: float = time.time() # last send/received death link on AP layer # game state self.player_names: typing.Dict[int: str] = {0: "Archipelago"} self.exit_event = asyncio.Event() self.watcher_event = asyncio.Event() self.slow_mode = False self.jsontotextparser = JSONtoTextParser(self) self.set_getters(network_data_package) # execution self.keep_alive_task = asyncio.create_task(keep_alive(self)) @property def total_locations(self) -> typing.Optional[int]: """Will return None until connected.""" if self.checked_locations or self.missing_locations: return len(self.checked_locations | self.missing_locations) async def connection_closed(self): self.auth = None self.items_received = [] self.locations_info = {} self.server_version = Version(0, 0, 0) if self.server and self.server.socket is not None: await self.server.socket.close() self.server = None self.server_task = None def set_getters(self, data_package: dict, network=False): if not network: # local data; check if newer data was already downloaded local_package = Utils.persistent_load().get("datapackage", {}).get("latest", {}) if local_package and local_package["version"] > network_data_package["version"]: data_package: dict = local_package elif network: # check if data from server is newer if data_package["version"] > network_data_package["version"]: Utils.persistent_store("datapackage", "latest", network_data_package) item_lookup: dict = {} locations_lookup: dict = {} for game, gamedata in data_package["games"].items(): for item_name, item_id in gamedata["item_name_to_id"].items(): item_lookup[item_id] = item_name for location_name, location_id in gamedata["location_name_to_id"].items(): locations_lookup[location_id] = location_name def get_item_name_from_id(code: int): return item_lookup.get(code, f'Unknown item (ID:{code})') self.item_name_getter = get_item_name_from_id def get_location_name_from_address(address: int): return locations_lookup.get(address, f'Unknown location (ID:{address})') self.location_name_getter = get_location_name_from_address @property def endpoints(self): if self.server: return [self.server] else: return [] async def disconnect(self): if self.server and not self.server.socket.closed: await self.server.socket.close() if self.server_task is not None: await self.server_task async def send_msgs(self, msgs): if not self.server or not self.server.socket.open or self.server.socket.closed: return await self.server.socket.send(encode(msgs)) def consume_players_package(self, package: typing.List[tuple]): self.player_names = {slot: name for team, slot, name, orig_name in package if self.team == team} self.player_names[0] = "Archipelago" def event_invalid_slot(self): raise Exception('Invalid Slot; please verify that you have connected to the correct world.') def event_invalid_game(self): raise Exception('Invalid Game; please verify that you connected with the right game to the correct world.') async def server_auth(self, password_requested: bool = False): if password_requested and not self.password: logger.info('Enter the password required to join this game:') self.password = await self.console_input() return self.password async def console_input(self): self.input_requests += 1 return await self.input_queue.get() async def connect(self, address=None): await self.disconnect() self.server_task = asyncio.create_task(server_loop(self, address)) def on_print(self, args: dict): logger.info(args["text"]) def on_print_json(self, args: dict): if self.ui: self.ui.print_json(args["data"]) else: text = self.jsontotextparser(args["data"]) logger.info(text) def on_package(self, cmd: str, args: dict): """For custom package handling in subclasses.""" pass def update_permissions(self, permissions: typing.Dict[str, int]): for permission_name, permission_flag in permissions.items(): try: flag = Permission(permission_flag) logger.info(f"{permission_name.capitalize()} permission: {flag.name}") self.permissions[permission_name] = flag.name except Exception as e: # safeguard against permissions that may be implemented in the future logger.exception(e) def on_deathlink(self, data: dict): """Gets dispatched when a new DeathLink is triggered by another linked player.""" raise NotImplementedError async def send_death(self): self.last_death_link = time.time() await self.send_msgs([{ "cmd": "Bounce", "tags": ["DeathLink"], "data": { "time": self.last_death_link, "source": self.player_names[self.slot] } }]) async def keep_alive(ctx: CommonContext, seconds_between_checks=100): """some ISPs/network configurations drop TCP connections if no payload is sent (ignore TCP-keep-alive) so we send a payload to prevent drop and if we were dropped anyway this will cause an auto-reconnect.""" seconds_elapsed = 0 while not ctx.exit_event.is_set(): await asyncio.sleep(1) # short sleep to not block program shutdown if ctx.server and ctx.slot: seconds_elapsed += 1 if seconds_elapsed > seconds_between_checks: await ctx.send_msgs([{"cmd": "Bounce", "slots": [ctx.slot]}]) seconds_elapsed = 0 async def server_loop(ctx: CommonContext, address=None): cached_address = None if ctx.server and ctx.server.socket: logger.error('Already connected') return if address is None: # set through CLI or APBP address = ctx.server_address # Wait for the user to provide a multiworld server address if not address: logger.info('Please connect to an Archipelago server.') return address = f"ws://{address}" if "://" not in address else address port = urllib.parse.urlparse(address).port or 38281 logger.info(f'Connecting to Archipelago server at {address}') try: socket = await websockets.connect(address, port=port, ping_timeout=None, ping_interval=None) ctx.server = Endpoint(socket) logger.info('Connected') ctx.server_address = address ctx.current_reconnect_delay = ctx.starting_reconnect_delay async for data in ctx.server.socket: for msg in decode(data): await process_server_cmd(ctx, msg) logger.warning('Disconnected from multiworld server, type /connect to reconnect') except ConnectionRefusedError: if cached_address: logger.error('Unable to connect to multiworld server at cached address. ' 'Please use the connect button above.') else: logger.exception('Connection refused by the multiworld server') except websockets.InvalidURI: logger.exception('Failed to connect to the multiworld server (invalid URI)') except (OSError, websockets.InvalidURI): logger.exception('Failed to connect to the multiworld server') except Exception as e: logger.exception('Lost connection to the multiworld server, type /connect to reconnect') finally: await ctx.connection_closed() if ctx.server_address: logger.info(f"... reconnecting in {ctx.current_reconnect_delay}s") asyncio.create_task(server_autoreconnect(ctx)) ctx.current_reconnect_delay *= 2 async def server_autoreconnect(ctx: CommonContext): await asyncio.sleep(ctx.current_reconnect_delay) if ctx.server_address and ctx.server_task is None: ctx.server_task = asyncio.create_task(server_loop(ctx)) async def process_server_cmd(ctx: CommonContext, args: dict): try: cmd = args["cmd"] except: logger.exception(f"Could not get command from {args}") raise if cmd == 'RoomInfo': if ctx.seed_name and ctx.seed_name != args["seed_name"]: logger.info("The server is running a different multiworld than your client is. (invalid seed_name)") else: logger.info('--------------------------------') logger.info('Room Information:') logger.info('--------------------------------') version = args["version"] ctx.server_version = tuple(version) version = ".".join(str(item) for item in version) logger.info(f'Server protocol version: {version}') logger.info("Server protocol tags: " + ", ".join(args["tags"])) if args['password']: logger.info('Password required') ctx.update_permissions(args.get("permissions", {})) if "games" in args: ctx.games = {x: game for x, game in enumerate(args["games"], start=1)} logger.info( f"A !hint costs {args['hint_cost']}% of your total location count as points" f" and you get {args['location_check_points']}" f" for each location checked. Use !hint for more information.") ctx.hint_cost = int(args['hint_cost']) ctx.check_points = int(args['location_check_points']) if len(args['players']) < 1: logger.info('No player connected') else: args['players'].sort() current_team = -1 logger.info('Players:') for network_player in args['players']: if network_player.team != current_team: logger.info(f' Team #{network_player.team + 1}') current_team = network_player.team logger.info(' %s (Player %d)' % (network_player.alias, network_player.slot)) if args["datapackage_version"] > network_data_package["version"] or args["datapackage_version"] == 0: await ctx.send_msgs([{"cmd": "GetDataPackage"}]) await ctx.server_auth(args['password']) elif cmd == 'DataPackage': logger.info("Got new ID/Name Datapackage") ctx.set_getters(args['data'], network=True) elif cmd == 'ConnectionRefused': errors = args["errors"] if 'InvalidSlot' in errors: ctx.event_invalid_slot() elif 'InvalidGame' in errors: ctx.event_invalid_game() elif 'SlotAlreadyTaken' in errors: raise Exception('Player slot already in use for that team') elif 'IncompatibleVersion' in errors: raise Exception('Server reported your client version as incompatible') # last to check, recoverable problem elif 'InvalidPassword' in errors: logger.error('Invalid password') ctx.password = None await ctx.server_auth(True) elif errors: raise Exception("Unknown connection errors: " + str(errors)) else: raise Exception('Connection refused by the multiworld host, no reason provided') elif cmd == 'Connected': ctx.team = args["team"] ctx.slot = args["slot"] ctx.consume_players_package(args["players"]) msgs = [] if ctx.locations_checked: msgs.append({"cmd": "LocationChecks", "locations": list(ctx.locations_checked)}) if ctx.locations_scouted: msgs.append({"cmd": "LocationScouts", "locations": list(ctx.locations_scouted)}) if msgs: await ctx.send_msgs(msgs) if ctx.finished_game: await ctx.send_msgs([{"cmd": "StatusUpdate", "status": ClientStatus.CLIENT_GOAL}]) # Get the server side view of missing as of time of connecting. # This list is used to only send to the server what is reported as ACTUALLY Missing. # This also serves to allow an easy visual of what locations were already checked previously # when /missing is used for the client side view of what is missing. ctx.missing_locations = set(args["missing_locations"]) ctx.checked_locations = set(args["checked_locations"]) elif cmd == 'ReceivedItems': start_index = args["index"] if start_index == 0: ctx.items_received = [] elif start_index != len(ctx.items_received): sync_msg = [{'cmd': 'Sync'}] if ctx.locations_checked: sync_msg.append({"cmd": "LocationChecks", "locations": list(ctx.locations_checked)}) await ctx.send_msgs(sync_msg) if start_index == len(ctx.items_received): for item in args['items']: ctx.items_received.append(NetworkItem(*item)) ctx.watcher_event.set() elif cmd == 'LocationInfo': for item, location, player in args['locations']: if location not in ctx.locations_info: ctx.locations_info[location] = (item, player) ctx.watcher_event.set() elif cmd == "RoomUpdate": if "players" in args: ctx.consume_players_package(args["players"]) if "hint_points" in args: ctx.hint_points = args['hint_points'] if "checked_locations" in args: checked = set(args["checked_locations"]) ctx.checked_locations |= checked ctx.missing_locations -= checked if "permissions" in args: ctx.update_permissions(args["permissions"]) elif cmd == 'Print': ctx.on_print(args) elif cmd == 'PrintJSON': ctx.on_print_json(args) elif cmd == 'InvalidPacket': logger.warning(f"Invalid Packet of {args['type']}: {args['text']}") elif cmd == "Bounced": tags = args.get("tags", []) # we can skip checking "DeathLink" in ctx.tags, as otherwise we wouldn't have been send this if "DeathLink" in tags and ctx.last_death_link != args["data"]["time"]: ctx.on_deathlink(args["data"]) else: logger.debug(f"unknown command {cmd}") ctx.on_package(cmd, args) async def console_loop(ctx: CommonContext): import sys commandprocessor = ctx.command_processor(ctx) while not ctx.exit_event.is_set(): try: input_text = await asyncio.get_event_loop().run_in_executor( None, sys.stdin.readline ) input_text = input_text.strip() if ctx.input_requests > 0: ctx.input_requests -= 1 ctx.input_queue.put_nowait(input_text) continue if input_text: commandprocessor(input_text) except Exception as e: logger.exception(e) def init_logging(name: str): if gui_enabled: logging.basicConfig(format='[%(name)s]: %(message)s', level=logging.INFO, filename=os.path.join(log_folder, f"{name}.txt"), filemode="w", force=True) else: logging.basicConfig(format='[%(name)s]: %(message)s', level=logging.INFO, force=True) logging.getLogger().addHandler(logging.FileHandler(os.path.join(log_folder, f"{name}.txt"), "w")) if __name__ == '__main__': # Text Mode to use !hint and such with games that have no text entry init_logging("TextClient") class TextContext(CommonContext): tags = {"AP", "IgnoreGame"} async def server_auth(self, password_requested: bool = False): if password_requested and not self.password: await super(TextContext, self).server_auth(password_requested) if not self.auth: logger.info('Enter slot name:') self.auth = await self.console_input() await self.send_msgs([{"cmd": 'Connect', 'password': <PASSWORD>, 'name': self.auth, 'version': Utils.version_tuple, 'tags': self.tags, 'uuid': Utils.get_unique_identifier(), 'game': self.game }]) def on_package(self, cmd: str, args: dict): if cmd == "Connected": self.game = self.games.get(self.slot, None) async def main(args): ctx = TextContext(args.connect, args.password) ctx.server_task = asyncio.create_task(server_loop(ctx), name="ServerLoop") if gui_enabled: input_task = None from kvui import TextManager ctx.ui = TextManager(ctx) ui_task = asyncio.create_task(ctx.ui.async_run(), name="UI") else: input_task = asyncio.create_task(console_loop(ctx), name="Input") ui_task = None await ctx.exit_event.wait() ctx.server_address = None if ctx.server and not ctx.server.socket.closed: await ctx.server.socket.close() if ctx.server_task: await ctx.server_task while ctx.input_requests > 0: ctx.input_queue.put_nowait(None) ctx.input_requests -= 1 if ui_task: await ui_task if input_task: input_task.cancel() import argparse import colorama parser = argparse.ArgumentParser(description="Gameless Archipelago Client, for text interfaction.") parser.add_argument('--connect', default=None, help='Address of the multiworld host.') parser.add_argument('--password', default=None, help='Password of the multiworld host.') if not Utils.is_frozen(): # Frozen state has no cmd window in the first place parser.add_argument('--nogui', default=False, action='store_true', help="Turns off Client GUI.") args, rest = parser.parse_known_args() colorama.init() loop = asyncio.get_event_loop() loop.run_until_complete(main(args)) loop.close() colorama.deinit() <file_sep>import argparse import os, sys import re import atexit from subprocess import Popen from shutil import copyfile from base64 import b64decode from time import strftime import requests import Utils atexit.register(input, "Press enter to exit.") # 1 or more digits followed by m or g, then optional b max_heap_re = re.compile(r"^\d+[mMgG][bB]?$") def prompt_yes_no(prompt): yes_inputs = {'yes', 'ye', 'y'} no_inputs = {'no', 'n'} while True: choice = input(prompt + " [y/n] ").lower() if choice in yes_inputs: return True elif choice in no_inputs: return False else: print('Please respond with "y" or "n".') # Find Forge jar file; raise error if not found def find_forge_jar(forge_dir): for entry in os.scandir(forge_dir): if ".jar" in entry.name and "forge" in entry.name: print(f"Found forge .jar: {entry.name}") return entry.name raise FileNotFoundError(f"Could not find forge .jar in {forge_dir}.") # Create mods folder if needed; find AP randomizer jar; return None if not found. def find_ap_randomizer_jar(forge_dir): mods_dir = os.path.join(forge_dir, 'mods') if os.path.isdir(mods_dir): ap_mod_re = re.compile(r"^aprandomizer-[\d\.]+\.jar$") for entry in os.scandir(mods_dir): match = ap_mod_re.match(entry.name) if match: print(f"Found AP randomizer mod: {match.group()}") return match.group() return None else: os.mkdir(mods_dir) print(f"Created mods folder in {forge_dir}") return None # Create APData folder if needed; clean .apmc files from APData; copy given .apmc into directory. def replace_apmc_files(forge_dir, apmc_file): if apmc_file is None: return apdata_dir = os.path.join(forge_dir, 'APData') copy_apmc = True if not os.path.isdir(apdata_dir): os.mkdir(apdata_dir) print(f"Created APData folder in {forge_dir}") for entry in os.scandir(apdata_dir): if entry.name.endswith(".apmc") and entry.is_file(): if not os.path.samefile(apmc_file, entry.path): os.remove(entry.path) print(f"Removed {entry.name} in {apdata_dir}") else: # apmc already in apdata copy_apmc = False if copy_apmc: copyfile(apmc_file, os.path.join(apdata_dir, os.path.basename(apmc_file))) print(f"Copied {os.path.basename(apmc_file)} to {apdata_dir}") # Check mod version, download new mod from GitHub releases page if needed. def update_mod(forge_dir): ap_randomizer = find_ap_randomizer_jar(forge_dir) client_releases_endpoint = "https://api.github.com/repos/KonoTyran/Minecraft_AP_Randomizer/releases" resp = requests.get(client_releases_endpoint) if resp.status_code == 200: # OK latest_release = resp.json()[0] if ap_randomizer != latest_release['assets'][0]['name']: print(f"A new release of the Minecraft AP randomizer mod was found: {latest_release['assets'][0]['name']}") if ap_randomizer is not None: print(f"Your current mod is {ap_randomizer}.") else: print(f"You do not have the AP randomizer mod installed.") if prompt_yes_no("Would you like to update?"): old_ap_mod = os.path.join(forge_dir, 'mods', ap_randomizer) if ap_randomizer is not None else None new_ap_mod = os.path.join(forge_dir, 'mods', latest_release['assets'][0]['name']) print("Downloading AP randomizer mod. This may take a moment...") apmod_resp = requests.get(latest_release['assets'][0]['browser_download_url']) if apmod_resp.status_code == 200: with open(new_ap_mod, 'wb') as f: f.write(apmod_resp.content) print(f"Wrote new mod file to {new_ap_mod}") if old_ap_mod is not None: os.remove(old_ap_mod) print(f"Removed old mod file from {old_ap_mod}") else: print(f"Error retrieving the randomizer mod (status code {apmod_resp.status_code}).") print(f"Please report this issue on the Archipelago Discord server.") sys.exit(1) else: print(f"Error checking for randomizer mod updates (status code {resp.status_code}).") print(f"If this was not expected, please report this issue on the Archipelago Discord server.") if not prompt_yes_no("Continue anyways?"): sys.exit(0) # Check if the EULA is agreed to, and prompt the user to read and agree if necessary. def check_eula(forge_dir): eula_path = os.path.join(forge_dir, "eula.txt") if not os.path.isfile(eula_path): # Create eula.txt with open(eula_path, 'w') as f: f.write("#By changing the setting below to TRUE you are indicating your agreement to our EULA (https://account.mojang.com/documents/minecraft_eula).\n") f.write(f"#{strftime('%a %b %d %X %Z %Y')}\n") f.write("eula=false\n") with open(eula_path, 'r+') as f: text = f.read() if 'false' in text: # Prompt user to agree to the EULA print("You need to agree to the Minecraft EULA in order to run the server.") print("The EULA can be found at https://account.mojang.com/documents/minecraft_eula") if prompt_yes_no("Do you agree to the EULA?"): f.seek(0) f.write(text.replace('false', 'true')) f.truncate() print(f"Set {eula_path} to true") else: sys.exit(0) # Run the Forge server. Return process object def run_forge_server(forge_dir, heap_arg): forge_server = find_forge_jar(forge_dir) java_exe = os.path.abspath(os.path.join('jre8', 'bin', 'java.exe')) if not os.path.isfile(java_exe): java_exe = "java" # try to fall back on java in the PATH heap_arg = max_heap_re.match(max_heap).group() if heap_arg[-1] in ['b', 'B']: heap_arg = heap_arg[:-1] heap_arg = "-Xmx" + heap_arg argstring = ' '.join([java_exe, heap_arg, "-jar", forge_server, "-nogui"]) print(f"Running Forge server: {argstring}") os.chdir(forge_dir) return Popen(argstring) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("apmc_file", default=None, nargs='?', help="Path to an Archipelago Minecraft data file (.apmc)") args = parser.parse_args() apmc_file = os.path.abspath(args.apmc_file) if args.apmc_file else None # Change to executable's working directory os.chdir(os.path.abspath(os.path.dirname(sys.argv[0]))) options = Utils.get_options() forge_dir = options["minecraft_options"]["forge_directory"] max_heap = options["minecraft_options"]["max_heap_size"] if apmc_file is not None and not os.path.isfile(apmc_file): raise FileNotFoundError(f"Path {apmc_file} does not exist or could not be accessed.") if not os.path.isdir(forge_dir): raise NotADirectoryError(f"Path {forge_dir} does not exist or could not be accessed.") if not max_heap_re.match(max_heap): raise Exception(f"Max heap size {max_heap} in incorrect format. Use a number followed by M or G, e.g. 512M or 2G.") update_mod(forge_dir) replace_apmc_files(forge_dir, apmc_file) check_eula(forge_dir) server_process = run_forge_server(forge_dir, max_heap) server_process.wait() <file_sep>from typing import Tuple, Optional, Callable, NamedTuple from BaseClasses import MultiWorld from .Options import is_option_enabled EventId: Optional[int] = None class LocationData(NamedTuple): region: str name: str code: Optional[int] rule: Callable = lambda state: True def get_locations(world: Optional[MultiWorld], player: Optional[int]) -> Tuple[LocationData, ...]: location_table: Tuple[LocationData, ...] = ( # PresentItemLocations LocationData('Tutorial', 'Yo Momma 1', 1337000), LocationData('Tutorial', 'Yo Momma 2', 1337001), LocationData('Lake desolation', 'Starter chest 2', 1337002), LocationData('Lake desolation', 'Starter chest 3', 1337003), LocationData('Lake desolation', 'Starter chest 1', 1337004), LocationData('Lake desolation', 'Timespinner Wheel room', 1337005), LocationData('Upper lake desolation', 'Forget me not chest', 1337006), LocationData('Lower lake desolation', 'Chicken chest', 1337007, lambda state: state._timespinner_has_timestop(world, player)), LocationData('Lower lake desolation', 'Not so secret room', 1337008, lambda state: state._timespinner_can_break_walls(world, player)), LocationData('Lower lake desolation', 'Tank chest', 1337009, lambda state: state._timespinner_has_timestop(world, player)), LocationData('Upper lake desolation', 'Oxygen recovery room', 1337010), LocationData('Upper lake desolation', 'Lake secret', 1337011, lambda state: state._timespinner_can_break_walls(world, player)), LocationData('Upper lake desolation', 'Double jump cave floor', 1337012, lambda state: state._timespinner_has_doublejump(world, player)), LocationData('Upper lake desolation', 'Double jump cave platform', 1337013), LocationData('Upper lake desolation', 'Fire-Locked sparrow chest', 1337014), LocationData('Upper lake desolation', 'Crash site pedestal', 1337015), LocationData('Upper lake desolation', 'Crash site chest 1', 1337016, lambda state: state.has_all(['Killed Maw', 'Gas Mask'], player)), LocationData('Upper lake desolation', 'Crash site chest 2', 1337017, lambda state: state.has_all(['Killed Maw', 'Gas Mask'], player)), LocationData('Upper lake desolation', 'Kitty Boss', 1337018), LocationData('Library', 'Basement', 1337019), LocationData('Library', 'Consolation', 1337020), LocationData('Library', 'Librarian', 1337021), LocationData('Library', 'Reading nook chest', 1337022), LocationData('Library', 'Storage room chest 1', 1337023, lambda state: state._timespinner_has_keycard_D(world, player)), LocationData('Library', 'Storage room chest 2', 1337024, lambda state: state._timespinner_has_keycard_D(world, player)), LocationData('Library', 'Storage room chest 3', 1337025, lambda state: state._timespinner_has_keycard_D(world, player)), LocationData('Library top', 'Backer room chest 5', 1337026), LocationData('Library top', 'Backer room chest 4', 1337027), LocationData('Library top', 'Backer room chest 3', 1337028), LocationData('Library top', 'Backer room chest 2', 1337029), LocationData('Library top', 'Backer room chest 1', 1337030), LocationData('Varndagroth tower left', 'Elevator Key not required', 1337031), LocationData('Varndagroth tower left', 'Ye olde Timespinner', 1337032), LocationData('Varndagroth tower left', 'C Keycard chest', 1337033, lambda state: state._timespinner_has_keycard_C(world, player)), LocationData('Varndagroth tower left', 'Left air vents secret', 1337034, lambda state: state._timespinner_can_break_walls(world, player)), LocationData('Varndagroth tower left', 'Left elevator chest', 1337035, lambda state: state.has('Elevator Keycard', player)), LocationData('Varndagroth tower right (upper)', 'Spider heck room', 1337036), LocationData('Varndagroth tower right (elevator)', 'Right elevator chest', 1337037), LocationData('Varndagroth tower right (upper)', 'Elevator card chest', 1337038, lambda state: state.has('Elevator Keycard', player) or state._timespinner_has_doublejump(world, player)), LocationData('Varndagroth tower right (upper)', 'Air vents left', 1337039, lambda state: state.has('Elevator Keycard', player) or state._timespinner_has_doublejump(world, player)), LocationData('Varndagroth tower right (upper)', 'Air Vents right', 1337040, lambda state: state.has('Elevator Keycard', player) or state._timespinner_has_doublejump(world, player)), LocationData('Varndagroth tower right (lower)', 'Right side bottom floor', 1337041), LocationData('Varndagroth tower right (elevator)', 'Varndagroth', 1337042, lambda state: state._timespinner_has_keycard_C(world, player)), LocationData('Varndagroth tower right (elevator)', 'Varndagroth Spider hell', 1337043, lambda state: state._timespinner_has_keycard_A(world, player)), LocationData('Skeleton Shaft', 'Skeleton', 1337044), LocationData('Sealed Caves (Xarion)', 'Shroom jump room', 1337045, lambda state: state._timespinner_has_timestop(world, player)), LocationData('Sealed Caves (Xarion)', 'Double shroom room', 1337046), LocationData('Sealed Caves (Xarion)', 'Mini jackpot room', 1337047, lambda state: state._timespinner_has_forwarddash_doublejump(world, player)), LocationData('Sealed Caves (Xarion)', 'Below mini jackpot room', 1337048), LocationData('Sealed Caves (Xarion)', 'Sealed cave secret room', 1337049, lambda state: state._timespinner_can_break_walls(world, player)), LocationData('Sealed Caves (Xarion)', 'Below Sealed cave secret', 1337050), LocationData('Sealed Caves (Xarion)', 'Last chance before Xarion', 1337051, lambda state: state._timespinner_has_doublejump(world, player)), LocationData('Sealed Caves (Xarion)', 'Xarion', 1337052), LocationData('Sealed Caves (Sirens)', 'Solo siren chest', 1337053, lambda state: state.has('Water Mask', player)), LocationData('Sealed Caves (Sirens)', 'Big siren room right', 1337054, lambda state: state.has('Water Mask', player)), LocationData('Sealed Caves (Sirens)', 'Big siren Room left', 1337055, lambda state: state.has('Water Mask', player)), LocationData('Sealed Caves (Sirens)', 'Room after sirens chest 2', 1337056), LocationData('Sealed Caves (Sirens)', 'Room after sirens chest 1', 1337057), LocationData('Militairy Fortress', 'Militairy Bomber chest', 1337058, lambda state: state.has('Timespinner Wheel', player) and state._timespinner_has_doublejump_of_npc(world, player)), LocationData('Militairy Fortress', 'Close combat room', 1337059), LocationData('Militairy Fortress', 'Bridge full of soldiers', 1337060), LocationData('Militairy Fortress', 'Giantess Room', 1337061), LocationData('Militairy Fortress', 'Bridge with Giantess', 1337062), LocationData('Militairy Fortress', 'Military B door chest 2', 1337063, lambda state: state._timespinner_has_doublejump(world, player) and state._timespinner_has_keycard_B(world, player)), LocationData('Militairy Fortress', 'Military B door chest 1', 1337064, lambda state: state._timespinner_has_doublejump(world, player) and state._timespinner_has_keycard_B(world, player)), LocationData('Militairy Fortress', 'Military pedestal', 1337065, lambda state: state._timespinner_has_doublejump(world, player) and (state._timespinner_has_doublejump_of_npc(world, player) or state._timespinner_has_forwarddash_doublejump(world, player))), LocationData('The lab', 'Coffee Break chest', 1337066), LocationData('The lab', 'Lower trash right', 1337067, lambda state: state._timespinner_has_doublejump(world, player)), LocationData('The lab', 'Lower trash left', 1337068, lambda state: state._timespinner_has_upwarddash(world, player)), LocationData('The lab', 'Single turret room', 1337069, lambda state: state._timespinner_has_doublejump(world, player)), LocationData('The lab (power off)', 'Trash jump room', 1337070), LocationData('The lab (power off)', 'Dynamo Works', 1337071), LocationData('The lab (upper)', 'Blob mom', 1337072), LocationData('The lab (power off)', 'Experiment #13', 1337073), LocationData('The lab (upper)', 'Download and chest room', 1337074), LocationData('The lab (upper)', 'Lab secret', 1337075, lambda state: state._timespinner_can_break_walls(world, player)), LocationData('The lab (power off)', 'Lab Spider hell', 1337076, lambda state: state._timespinner_has_keycard_A(world, player)), LocationData('Emperors tower', 'Bottom', 1337077), LocationData('Emperors tower', 'After Courtyard Floor Secret', 1337078, lambda state: state._timespinner_has_upwarddash(world, player) and state._timespinner_can_break_walls(world, player)), LocationData('Emperors tower', 'After Courtyard Chest', 1337079, lambda state: state._timespinner_has_upwarddash(world, player)), LocationData('Emperors tower', 'Galactic Sage Room', 1337080), LocationData('Emperors tower', 'Bottom of Right Tower', 1337081), LocationData('Emperors tower', 'Wayyyy up there', 1337082), LocationData('Emperors tower', 'Left tower balcony', 1337083), LocationData('Emperors tower', 'Dad\'s Chambers chest', 1337084), LocationData('Emperors tower', 'Dad\'s Chambers pedestal', 1337085), # PastItemLocations LocationData('Refugee Camp', 'Neliste\'s Bra', 1337086), LocationData('Refugee Camp', 'Refugee camp storage chest 3', 1337087), LocationData('Refugee Camp', 'Refugee camp storage chest 2', 1337088), LocationData('Refugee Camp', 'Refugee camp storage chest 1', 1337089), LocationData('Forest', 'Refugee camp roof', 1337090), LocationData('Forest', 'Bat jump chest', 1337091, lambda state: state._timespinner_has_doublejump_of_npc(world, player) or state._timespinner_has_forwarddash_doublejump(world, player)), LocationData('Forest', 'Green platform secret', 1337092, lambda state: state._timespinner_can_break_walls(world, player)), LocationData('Forest', 'Rats guarded chest', 1337093), LocationData('Forest', 'Waterfall chest 1', 1337094, lambda state: state.has('Water Mask', player)), LocationData('Forest', 'Waterfall chest 2', 1337095, lambda state: state.has('Water Mask', player)), LocationData('Forest', 'Batcave', 1337096), LocationData('Forest', 'Bridge Chest', 1337097), LocationData('Left Side forest Caves', 'Solitary bat room', 1337098), LocationData('Upper Lake Serene', 'Rat nest', 1337099), LocationData('Upper Lake Serene', 'Double jump cave platform (past)', 1337100, lambda state: state._timespinner_has_doublejump(world, player)), LocationData('Upper Lake Serene', 'Double jump cave floor (past)', 1337101), LocationData('Upper Lake Serene', 'West lake serene cave secret', 1337102, lambda state: state._timespinner_can_break_walls(world, player)), LocationData('Upper Lake Serene', 'Chest behind vines', 1337103), LocationData('Upper Lake Serene', 'Pyramid keys room', 1337104), LocationData('Lower Lake Serene', 'Deep dive', 1337105), LocationData('Lower Lake Serene', 'Under the eels', 1337106), LocationData('Lower Lake Serene', 'Water spikes room', 1337107), LocationData('Lower Lake Serene', 'Underwater secret', 1337108, lambda state: state._timespinner_can_break_walls(world, player)), LocationData('Lower Lake Serene', 'T chest', 1337109), LocationData('Lower Lake Serene', 'Past the eels', 1337110), LocationData('Lower Lake Serene', 'Underwater pedestal', 1337111), LocationData('Caves of Banishment (upper)', 'Mushroom double jump', 1337112, lambda state: state._timespinner_has_doublejump(world, player)), LocationData('Caves of Banishment (upper)', 'Caves of banishment secret room', 1337113), LocationData('Caves of Banishment (upper)', 'Below caves of banishment secret', 1337114), LocationData('Caves of Banishment (upper)', 'Single shroom room', 1337115), LocationData('Caves of Banishment (upper)', 'Jackpot room chest 1', 1337116, lambda state: state._timespinner_has_forwarddash_doublejump(world, player)), LocationData('Caves of Banishment (upper)', 'Jackpot room chest 2', 1337117, lambda state: state._timespinner_has_forwarddash_doublejump(world, player)), LocationData('Caves of Banishment (upper)', 'Jackpot room chest 3', 1337118, lambda state: state._timespinner_has_forwarddash_doublejump(world, player)), LocationData('Caves of Banishment (upper)', 'Jackpot room chest 4', 1337119, lambda state: state._timespinner_has_forwarddash_doublejump(world, player)), LocationData('Caves of Banishment (upper)', 'Banishment pedestal', 1337120), LocationData('Caves of Banishment (Maw)', 'Last chance before Maw', 1337121, lambda state: state._timespinner_has_doublejump(world, player)), LocationData('Caves of Banishment (Maw)', 'Killed Maw', EventId, lambda state: state.has('Gas Mask', player)), LocationData('Caves of Banishment (Maw)', 'Mineshaft', 1337122, lambda state: state.has('Gas Mask', player)), LocationData('Caves of Banishment (Sirens)', 'Wyvern room', 1337123), LocationData('Caves of Banishment (Sirens)', 'Above water sirens', 1337124), LocationData('Caves of Banishment (Sirens)', 'Underwater sirens left', 1337125, lambda state: state.has('Water Mask', player)), LocationData('Caves of Banishment (Sirens)', 'Underwater sirens right', 1337126, lambda state: state.has('Water Mask', player)), LocationData('Caves of Banishment (Sirens)', 'Water hook', 1337127), LocationData('Castle Ramparts', 'Castle Bomber chest', 1337128, lambda state: state._timespinner_has_multiple_small_jumps_of_npc(world, player)), LocationData('Castle Ramparts', 'Freeze the engineer', 1337129, lambda state: state.has('Talaria Attachment', player) or state._timespinner_has_timestop(world, player)), LocationData('Castle Ramparts', 'Giantess guarded room', 1337130), LocationData('Castle Ramparts', 'Knight and archer guarded room', 1337131), LocationData('Castle Ramparts', 'Castle pedestal', 1337132), LocationData('Castle Keep', 'Basement secret pedestal', 1337133, lambda state: state._timespinner_can_break_walls(world, player)), LocationData('Castle Keep', 'Break the wall', 1337134), LocationData('Royal towers (lower)', 'Yas queen room', 1337135, lambda state: state._timespinner_has_pink(world, player)), LocationData('Castle Keep', 'Basement hammer', 1337136), LocationData('Castle Keep', 'Omelette chest', 1337137), LocationData('Castle Keep', 'Just an egg', 1337138), LocationData('Castle Keep', 'Out of the way', 1337139), LocationData('Castle Keep', 'Killed Twins', EventId, lambda state: state._timespinner_has_timestop(world, player)), LocationData('Castle Keep', 'Twins', 1337140, lambda state: state._timespinner_has_timestop(world, player)), LocationData('Castle Keep', 'Royal guard tiny room', 1337141, lambda state: state._timespinner_has_doublejump(world, player)), LocationData('Royal towers (lower)', 'Royal tower floor secret', 1337142, lambda state: state._timespinner_has_doublejump(world, player) and state._timespinner_can_break_walls(world, player)), LocationData('Royal towers', 'Above the gap', 1337143), LocationData('Royal towers', 'Under the ice mage', 1337144), LocationData('Royal towers (upper)', 'Next to easy struggle juggle room', 1337145), LocationData('Royal towers (upper)', 'Easy struggle juggle', 1337146, lambda state: state._timespinner_has_doublejump_of_npc(world, player)), LocationData('Royal towers (upper)', 'Hard struggle juggle', 1337147, lambda state: state._timespinner_has_doublejump_of_npc(world, player)), LocationData('Royal towers (upper)', 'No struggle required', 1337148, lambda state: state._timespinner_has_doublejump_of_npc(world, player)), LocationData('Royal towers', 'Right tower freebie', 1337149), LocationData('Royal towers (upper)', 'Above the ice mage', 1337150), LocationData('Royal towers (upper)', 'Royal guard big room', 1337151), LocationData('Royal towers (upper)', 'Before Aelana', 1337152), LocationData('Royal towers (upper)', 'Killed Aelana', EventId), LocationData('Royal towers (upper)', 'Statue room', 1337153, lambda state: state._timespinner_has_upwarddash(world, player)), LocationData('Royal towers (upper)', 'Aelana\'s pedestal', 1337154), LocationData('Royal towers (upper)', 'After Aelana', 1337155), # 1337157 - 1337170 Downloads # 1337171 - 1337238 Reserved # PyramidItemLocations #LocationData('Temporal Gyre', 'Transition chest 1', 1337239), #LocationData('Temporal Gyre', 'Transition chest 2', 1337240), #LocationData('Temporal Gyre', 'Transition chest 3', 1337241), #LocationData('Temporal Gyre', 'Ravenlord pre fight', 1337242), #LocationData('Temporal Gyre', 'Ravenlord post fight', 1337243), #LocationData('Temporal Gyre', 'Ifrid pre fight', 1337244), #LocationData('Temporal Gyre', 'Ifrid post fight', 1337245), LocationData('Ancient Pyramid (left)', 'Why not it\'s right there', 1337246), LocationData('Ancient Pyramid (left)', 'Conviction guarded room', 1337247), LocationData('Ancient Pyramid (right)', 'Pit secret room', 1337248, lambda state: state._timespinner_can_break_walls(world, player)), LocationData('Ancient Pyramid (right)', 'Regret chest', 1337249, lambda state: state._timespinner_can_break_walls(world, player)), LocationData('Ancient Pyramid (right)', 'Killed Nightmare', EventId) ) downloadable_items: Tuple[LocationData, ...] = ( # DownloadTerminals LocationData('Library', 'Library terminal 1', 1337157, lambda state: state.has('Tablet', player)), LocationData('Library', 'Library terminal 2', 1337156, lambda state: state.has('Tablet', player)), # 1337158 Is Lost in time LocationData('Library', 'Library terminal 3', 1337159, lambda state: state.has('Tablet', player)), LocationData('Library', 'V terminal 1', 1337160, lambda state: state.has_all(['Tablet', 'Library Keycard V'], player)), LocationData('Library', 'V terminal 2', 1337161, lambda state: state.has_all(['Tablet', 'Library Keycard V'], player)), LocationData('Library', 'V terminal 3', 1337162, lambda state: state.has_all(['Tablet', 'Library Keycard V'], player)), LocationData('Library top', 'Backer room terminal', 1337163, lambda state: state.has('Tablet', player)), LocationData('Varndagroth tower right (elevator)', 'Medbay', 1337164, lambda state: state.has('Tablet', player) and state._timespinner_has_keycard_B(world, player)), LocationData('The lab (upper)', 'Chest and download terminal', 1337165, lambda state: state.has('Tablet', player)), LocationData('The lab (power off)', 'Lab terminal middle', 1337166, lambda state: state.has('Tablet', player)), LocationData('The lab (power off)', 'Sentry platform terminal', 1337167, lambda state: state.has('Tablet', player)), LocationData('The lab', 'Experiment 13 terminal', 1337168, lambda state: state.has('Tablet', player)), LocationData('The lab', 'Lab terminal left', 1337169, lambda state: state.has('Tablet', player)), LocationData('The lab (power off)', 'Lab terminal right', 1337170, lambda state: state.has('Tablet', player)) ) if not world or is_option_enabled(world, player, "DownloadableItems"): return ( *location_table, *downloadable_items ) else: return location_table starter_progression_locations: Tuple[str, ...] = ( 'Starter chest 2', 'Starter chest 3', 'Starter chest 1', 'Timespinner Wheel room' )<file_sep>from .RulesData import location_rules from Options import Toggle options = { "open" : Toggle, "openworld": Toggle } for logic_set in location_rules: if logic_set != "casual-core": options[logic_set.replace("-", "_")] = Toggle <file_sep>"""Module extending BaseClasses.py for aLttP""" from typing import Optional from BaseClasses import Location, Item class ALttPLocation(Location): game: str = "A Link to the Past" def __init__(self, player: int, name: str = '', address=None, crystal: bool = False, hint_text: Optional[str] = None, parent=None, player_address=None): super(ALttPLocation, self).__init__(player, name, address, parent) self.crystal = crystal self.player_address = player_address self._hint_text: str = hint_text class ALttPItem(Item): game: str = "A Link to the Past" dungeon = None def __init__(self, name, player, advancement=False, type=None, item_code=None, pedestal_hint=None, pedestal_credit=None, sick_kid_credit=None, zora_credit=None, witch_credit=None, flute_boy_credit=None, hint_text=None, trap=False): super(ALttPItem, self).__init__(name, advancement, item_code, player) self.type = type self._pedestal_hint_text = pedestal_hint self.pedestal_credit_text = pedestal_credit self.sickkid_credit_text = sick_kid_credit self.zora_credit_text = zora_credit self.magicshop_credit_text = witch_credit self.fluteboy_credit_text = flute_boy_credit self._hint_text = hint_text if trap: self.trap = trap @property def crystal(self) -> bool: return self.type == 'Crystal' @property def smallkey(self) -> bool: return self.type == 'SmallKey' @property def bigkey(self) -> bool: return self.type == 'BigKey' @property def map(self) -> bool: return self.type == 'Map' @property def compass(self) -> bool: return self.type == 'Compass' @property def dungeon_item(self) -> Optional[str]: if self.type in {"SmallKey", "BigKey", "Map", "Compass"}: return self.type @property def locked_dungeon_item(self): return self.location.locked and self.dungeon_item<file_sep>def create_regions(world, player: int): from . import create_region from .Locations import location_table world.regions += [ create_region(world, player, 'Menu', None, ['Neow\'s Room']), create_region(world, player, 'The Spire', [location for location in location_table]) ] # link up our region with the entrance we just made world.get_entrance('Neow\'s Room', player).connect(world.get_region('The Spire', player)) <file_sep>from typing import Dict, List, Set from worlds.factorio.Options import TechTreeLayout funnel_layers = {TechTreeLayout.option_small_funnels: 3, TechTreeLayout.option_medium_funnels: 4, TechTreeLayout.option_large_funnels: 5} funnel_slice_sizes = {TechTreeLayout.option_small_funnels: 6, TechTreeLayout.option_medium_funnels: 10, TechTreeLayout.option_large_funnels: 15} def get_shapes(factorio_world) -> Dict[str, List[str]]: world = factorio_world.world player = factorio_world.player prerequisites: Dict[str, Set[str]] = {} layout = world.tech_tree_layout[player].value custom_technologies = factorio_world.custom_technologies tech_names: List[str] = list(set(custom_technologies) - world.worlds[player].static_nodes) tech_names.sort() world.random.shuffle(tech_names) if layout == TechTreeLayout.option_small_diamonds: slice_size = 4 while len(tech_names) > slice_size: slice = tech_names[:slice_size] tech_names = tech_names[slice_size:] slice.sort(key=lambda tech_name: len(custom_technologies[tech_name].get_prior_technologies())) diamond_0, diamond_1, diamond_2, diamond_3 = slice # 0 | # 1 2 | # 3 V prerequisites[diamond_3] = {diamond_1, diamond_2} prerequisites[diamond_2] = prerequisites[diamond_1] = {diamond_0} elif layout == TechTreeLayout.option_medium_diamonds: slice_size = 9 while len(tech_names) > slice_size: slice = tech_names[:slice_size] tech_names = tech_names[slice_size:] slice.sort(key=lambda tech_name: len(custom_technologies[tech_name].get_prior_technologies())) # 0 | # 1 2 | # 3 4 5 | # 6 7 | # 8 V prerequisites[slice[1]] = {slice[0]} prerequisites[slice[2]] = {slice[0]} prerequisites[slice[3]] = {slice[1]} prerequisites[slice[4]] = {slice[1], slice[2]} prerequisites[slice[5]] = {slice[2]} prerequisites[slice[6]] = {slice[3], slice[4]} prerequisites[slice[7]] = {slice[4], slice[5]} prerequisites[slice[8]] = {slice[6], slice[7]} elif layout == TechTreeLayout.option_large_diamonds: slice_size = 16 while len(tech_names) > slice_size: slice = tech_names[:slice_size] tech_names = tech_names[slice_size:] slice.sort(key=lambda tech_name: len(custom_technologies[tech_name].get_prior_technologies())) # 0 | # 1 2 | # 3 4 5 | # 6 7 8 9 | # 10 11 12 | # 13 14 | # 15 | prerequisites[slice[1]] = {slice[0]} prerequisites[slice[2]] = {slice[0]} prerequisites[slice[3]] = {slice[1]} prerequisites[slice[4]] = {slice[1], slice[2]} prerequisites[slice[5]] = {slice[2]} prerequisites[slice[6]] = {slice[3]} prerequisites[slice[7]] = {slice[3], slice[4]} prerequisites[slice[8]] = {slice[4], slice[5]} prerequisites[slice[9]] = {slice[5]} prerequisites[slice[10]] = {slice[6], slice[7]} prerequisites[slice[11]] = {slice[7], slice[8]} prerequisites[slice[12]] = {slice[8], slice[9]} prerequisites[slice[13]] = {slice[10], slice[11]} prerequisites[slice[14]] = {slice[11], slice[12]} prerequisites[slice[15]] = {slice[13], slice[14]} elif layout == TechTreeLayout.option_small_pyramids: slice_size = 6 while len(tech_names) > slice_size: slice = tech_names[:slice_size] tech_names = tech_names[slice_size:] slice.sort(key=lambda tech_name: len(custom_technologies[tech_name].get_prior_technologies())) # 0 | # 1 2 | # 3 4 5 | prerequisites[slice[1]] = {slice[0]} prerequisites[slice[2]] = {slice[0]} prerequisites[slice[3]] = {slice[1]} prerequisites[slice[4]] = {slice[1], slice[2]} prerequisites[slice[5]] = {slice[2]} elif layout == TechTreeLayout.option_medium_pyramids: slice_size = 10 while len(tech_names) > slice_size: slice = tech_names[:slice_size] tech_names = tech_names[slice_size:] slice.sort(key=lambda tech_name: len(custom_technologies[tech_name].get_prior_technologies())) # 0 | # 1 2 | # 3 4 5 | # 6 7 8 9 | prerequisites[slice[1]] = {slice[0]} prerequisites[slice[2]] = {slice[0]} prerequisites[slice[3]] = {slice[1]} prerequisites[slice[4]] = {slice[1], slice[2]} prerequisites[slice[5]] = {slice[2]} prerequisites[slice[6]] = {slice[3]} prerequisites[slice[7]] = {slice[3], slice[4]} prerequisites[slice[8]] = {slice[4], slice[5]} prerequisites[slice[9]] = {slice[5]} elif layout == TechTreeLayout.option_large_pyramids: slice_size = 15 while len(tech_names) > slice_size: slice = tech_names[:slice_size] tech_names = tech_names[slice_size:] slice.sort(key=lambda tech_name: len(custom_technologies[tech_name].get_prior_technologies())) # 0 | # 1 2 | # 3 4 5 | # 6 7 8 9 | # 10 11 12 13 14 | prerequisites[slice[1]] = {slice[0]} prerequisites[slice[2]] = {slice[0]} prerequisites[slice[3]] = {slice[1]} prerequisites[slice[4]] = {slice[1], slice[2]} prerequisites[slice[5]] = {slice[2]} prerequisites[slice[6]] = {slice[3]} prerequisites[slice[7]] = {slice[3], slice[4]} prerequisites[slice[8]] = {slice[4], slice[5]} prerequisites[slice[9]] = {slice[5]} prerequisites[slice[10]] = {slice[6]} prerequisites[slice[11]] = {slice[6], slice[7]} prerequisites[slice[12]] = {slice[7], slice[8]} prerequisites[slice[13]] = {slice[8], slice[9]} prerequisites[slice[14]] = {slice[9]} elif layout in funnel_layers: slice_size = funnel_slice_sizes[layout] world.random.shuffle(tech_names) while len(tech_names) > slice_size: tech_names = tech_names[slice_size:] current_tech_names = tech_names[:slice_size] layer_size = funnel_layers[layout] previous_slice = [] current_tech_names.sort(key=lambda tech_name: len(custom_technologies[tech_name].get_prior_technologies())) for layer in range(funnel_layers[layout]): slice = current_tech_names[:layer_size] current_tech_names = current_tech_names[layer_size:] if previous_slice: for i, tech_name in enumerate(slice): prerequisites.setdefault(tech_name, set()).update(previous_slice[i:i+2]) previous_slice = slice layer_size -= 1 world.tech_tree_layout_prerequisites[player] = prerequisites return prerequisites <file_sep># Subnautica ## Where is the settings page? The player settings page for this game is located <a href="../player-settings">here</a>. It contains all the options you need to configure and export a config file. ## What does randomization do to this game? The most noticeable change is the complete removal of freestanding technologies. The technology blueprints normally awarded from scanning those items have been shuffled into location checks throughout the AP item pool. ## What is the goal of Subnautica when randomized? The goal remains unchanged. Cure the plague, build the Neptune Escape Rocket, and escape into space. ## What items and locations get shuffled? Most of the technologies the player will need throughout the game will be shuffled. Location checks in Subnautica are data pads and technology lockers. ## Which items can be in another player's world? Most technologies may be shuffled into another player's world. ## What does another world's item look like in Subnautica? Location checks in Subnautica are data pads and technology lockers. Opening one of these will send an item to another player's world. ## When the player receives a technology, what happens? When the player receives a technology, the chat log displays a notification the technology has been received. <file_sep>import typing from Options import Choice, Option, Toggle, Range class AdvancementGoal(Range): """Number of advancements required to spawn the Ender Dragon.""" displayname = "Advancement Goal" range_start = 0 range_end = 87 default = 50 class EggShardsRequired(Range): """Number of dragon egg shards to collect before the Ender Dragon will spawn.""" displayname = "Egg Shards Required" range_start = 0 range_end = 30 class EggShardsAvailable(Range): """Number of dragon egg shards available to collect.""" displayname = "Egg Shards Available" range_start = 0 range_end = 30 class ShuffleStructures(Toggle): """Enables shuffling of villages, outposts, fortresses, bastions, and end cities.""" displayname = "Shuffle Structures" class StructureCompasses(Toggle): """Adds structure compasses to the item pool, which point to the nearest indicated structure.""" displayname = "Structure Compasses" class BeeTraps(Range): """Replaces a percentage of junk items with bee traps, which spawn multiple angered bees around every player when received.""" displayname = "Bee Trap Percentage" range_start = 0 range_end = 100 class CombatDifficulty(Choice): """Modifies the level of items logically required for exploring dangerous areas and fighting bosses.""" displayname = "Combat Difficulty" option_easy = 0 option_normal = 1 option_hard = 2 default = 1 class HardAdvancements(Toggle): """Enables certain RNG-reliant or tedious advancements.""" displayname = "Include Hard Advancements" class InsaneAdvancements(Toggle): """Enables the extremely difficult advancements "How Did We Get Here?" and "Adventuring Time.\"""" displayname = "Include Insane Advancements" class PostgameAdvancements(Toggle): """Enables advancements that require spawning and defeating the Ender Dragon.""" displayname = "Include Postgame Advancements" class SendDefeatedMobs(Toggle): """Send killed mobs to other Minecraft worlds which have this option enabled.""" displayname = "Send Defeated Mobs" minecraft_options: typing.Dict[str, type(Option)] = { "advancement_goal": AdvancementGoal, "egg_shards_required": EggShardsRequired, "egg_shards_available": EggShardsAvailable, "shuffle_structures": ShuffleStructures, "structure_compasses": StructureCompasses, "bee_traps": BeeTraps, "combat_difficulty": CombatDifficulty, "include_hard_advancements": HardAdvancements, "include_insane_advancements": InsaneAdvancements, "include_postgame_advancements": PostgameAdvancements, "send_defeated_mobs": SendDefeatedMobs, } <file_sep>from .LocationList import location_table from BaseClasses import Location location_id_offset = 67000 location_name_to_id = {name: (location_id_offset + index) for (index, name) in enumerate(location_table) if location_table[name][0] not in ['Boss', 'Event', 'Drop', 'HintStone', 'Hint']} class OOTLocation(Location): game: str = 'Ocarina of Time' def __init__(self, player, name='', code=None, address1=None, address2=None, default=None, type='Chest', scene=None, parent=None, filter_tags=None, internal=False): super(OOTLocation, self).__init__(player, name, code, parent) self.address1 = address1 self.address2 = address2 self.default = default self.type = type self.scene = scene self.internal = internal if filter_tags is None: self.filter_tags = None else: self.filter_tags = list(filter_tags) self.never = False # no idea what this does if type == 'Event': self.event = True def LocationFactory(locations, player: int): ret = [] singleton = False if isinstance(locations, str): locations = [locations] singleton = True for location in locations: if location in location_table: match_location = location else: match_location = next(filter(lambda k: k.lower() == location.lower(), location_table), None) if match_location: type, scene, default, addresses, vanilla_item, filter_tags = location_table[match_location] if addresses is None: addresses = (None, None) address1, address2 = addresses ret.append(OOTLocation(player, match_location, location_name_to_id.get(match_location, None), address1, address2, default, type, scene, filter_tags=filter_tags)) else: raise KeyError('Unknown Location: %s', location) if singleton: return ret[0] return ret <file_sep>from BaseClasses import Item import typing class RiskOfRainItem(Item): game: str = "Risk of Rain 2" # 37000 - 38000 item_table = { "Dio's Best Friend": 37001, "Common Item": 37002, "Uncommon Item": 37003, "Legendary Item": 37004, "Boss Item": 37005, "Lunar Item": 37006, "Equipment": 37007, "Item Scrap, White": 37008, "Item Scrap, Green": 37009, "Item Scrap, Red": 37010, "Item Scrap, Yellow": 37011, "Victory": None, "Beat Level One": None, "Beat Level Two": None, "Beat Level Three": None, "Beat Level Four": None, "Beat Level Five": None, } default_weights = { "Item Scrap, Green": 16, "Item Scrap, Red": 4, "Item Scrap, Yellow": 1, "Item Scrap, White": 32, "Common Item": 64, "Uncommon Item": 32, "Legendary Item": 8, "Boss Item": 4, "Lunar Item": 16, "Equipment": 32 } new_weights = { "Item Scrap, Green": 15, "Item Scrap, Red": 5, "Item Scrap, Yellow": 1, "Item Scrap, White": 30, "Common Item": 75, "Uncommon Item": 40, "Legendary Item": 10, "Boss Item": 5, "Lunar Item": 10, "Equipment": 20 } uncommon_weights = { "Item Scrap, Green": 45, "Item Scrap, Red": 5, "Item Scrap, Yellow": 1, "Item Scrap, White": 30, "Common Item": 45, "Uncommon Item": 100, "Legendary Item": 10, "Boss Item": 5, "Lunar Item": 15, "Equipment": 20 } legendary_weights = { "Item Scrap, Green": 15, "Item Scrap, Red": 5, "Item Scrap, Yellow": 1, "Item Scrap, White": 30, "Common Item": 50, "Uncommon Item": 25, "Legendary Item": 100, "Boss Item": 5, "Lunar Item": 15, "Equipment": 20 } lunartic_weights = { "Item Scrap, Green": 0, "Item Scrap, Red": 0, "Item Scrap, Yellow": 0, "Item Scrap, White": 0, "Common Item": 0, "Uncommon Item": 0, "Legendary Item": 0, "Boss Item": 0, "Lunar Item": 100, "Equipment": 0 } no_scraps_weights = { "Item Scrap, Green": 0, "Item Scrap, Red": 0, "Item Scrap, Yellow": 0, "Item Scrap, White": 0, "Common Item": 100, "Uncommon Item": 40, "Legendary Item": 15, "Boss Item": 5, "Lunar Item": 10, "Equipment": 25 } even_weights = { "Item Scrap, Green": 1, "Item Scrap, Red": 1, "Item Scrap, Yellow": 1, "Item Scrap, White": 1, "Common Item": 1, "Uncommon Item": 1, "Legendary Item": 1, "Boss Item": 1, "Lunar Item": 1, "Equipment": 1 } scraps_only = { "Item Scrap, Green": 70, "Item Scrap, White": 100, "Item Scrap, Red": 30, "Item Scrap, Yellow": 5, "Common Item": 0, "Uncommon Item": 0, "Legendary Item": 0, "Boss Item": 0, "Lunar Item": 0, "Equipment": 0 } item_pool_weights: typing.Dict[int, typing.Dict[str, int]] = { 0: default_weights, 1: new_weights, 2: uncommon_weights, 3: legendary_weights, 4: lunartic_weights, 6: no_scraps_weights, 7: even_weights, 8: scraps_only } lookup_id_to_name: typing.Dict[int, str] = {id: name for name, id in item_table.items() if id} <file_sep>from __future__ import annotations # Factorio technologies are imported from a .json document in /data from typing import Dict, Set, FrozenSet, Tuple, Union, List from collections import Counter import os import json import string import Utils import logging from . import Options factorio_id = factorio_base_id = 2 ** 17 source_folder = os.path.join(os.path.dirname(__file__), "data") with open(os.path.join(source_folder, "techs.json")) as f: raw = json.load(f) with open(os.path.join(source_folder, "recipes.json")) as f: raw_recipes = json.load(f) with open(os.path.join(source_folder, "machines.json")) as f: raw_machines = json.load(f) tech_table: Dict[str, int] = {} technology_table: Dict[str, Technology] = {} always = lambda state: True class FactorioElement(): name: str def __repr__(self): return f"{self.__class__.__name__}({self.name})" def __hash__(self): return hash(self.name) class Technology(FactorioElement): # maybe make subclass of Location? has_modifier: bool factorio_id: int name: str ingredients: Set[str] progressive: Tuple[str] unlocks: Union[Set[str], bool] # bool case is for progressive technologies def __init__(self, name: str, ingredients: Set[str], factorio_id: int, progressive: Tuple[str] = (), has_modifier: bool = False, unlocks: Union[Set[str], bool] = None): self.name = name self.factorio_id = factorio_id self.ingredients = ingredients self.progressive = progressive self.has_modifier = has_modifier if unlocks: self.unlocks = unlocks else: self.unlocks = set() def build_rule(self, player: int): logging.debug(f"Building rules for {self.name}") return lambda state, technologies=technologies: all(state.has(f"Automated {ingredient}", player) for ingredient in self.ingredients) def get_prior_technologies(self) -> Set[Technology]: """Get Technologies that have to precede this one to resolve tree connections.""" technologies = set() for ingredient in self.ingredients: technologies |= required_technologies[ingredient] # technologies that unlock the recipes return technologies def __hash__(self): return self.factorio_id def get_custom(self, world, allowed_packs: Set[str], player: int) -> CustomTechnology: return CustomTechnology(self, world, allowed_packs, player) def useful(self) -> bool: return self.has_modifier or self.unlocks class CustomTechnology(Technology): """A particularly configured Technology for a world.""" def __init__(self, origin: Technology, world, allowed_packs: Set[str], player: int): ingredients = origin.ingredients & allowed_packs military_allowed = "military-science-pack" in allowed_packs \ and (ingredients & {"chemical-science-pack", "production-science-pack", "utility-science-pack"}) self.player = player if origin.name not in world.worlds[player].static_nodes: if military_allowed: ingredients.add("military-science-pack") ingredients = list(ingredients) ingredients.sort() # deterministic sample ingredients = world.random.sample(ingredients, world.random.randint(1, len(ingredients))) elif origin.name == "rocket-silo" and military_allowed: ingredients.add("military-science-pack") super(CustomTechnology, self).__init__(origin.name, ingredients, origin.factorio_id) class Recipe(FactorioElement): name: str category: str ingredients: Dict[str, int] products: Dict[str, int] energy: float def __init__(self, name: str, category: str, ingredients: Dict[str, int], products: Dict[str, int], energy: float): self.name = name self.category = category self.ingredients = ingredients self.products = products self.energy = energy def __repr__(self): return f"{self.__class__.__name__}({self.name})" @property def crafting_machine(self) -> str: """cheapest crafting machine name able to run this recipe""" return machine_per_category[self.category] @property def unlocking_technologies(self) -> Set[Technology]: """Unlocked by any of the returned technologies. Empty set indicates a starting recipe.""" return {technology_table[tech_name] for tech_name in recipe_sources.get(self.name, ())} @property def recursive_unlocking_technologies(self) -> Set[Technology]: base = {technology_table[tech_name] for tech_name in recipe_sources.get(self.name, ())} for ingredient in self.ingredients: base |= required_technologies[ingredient] return base @property def rel_cost(self) -> float: ingredients = sum(self.ingredients.values()) return min(ingredients / amount for product, amount in self.products.items()) @property def base_cost(self) -> Dict[str, int]: ingredients = Counter() for ingredient, cost in self.ingredients.items(): if ingredient in all_product_sources: for recipe in all_product_sources[ingredient]: ingredients.update({name: amount * cost / recipe.products[ingredient] for name, amount in recipe.base_cost.items()}) else: ingredients[ingredient] += cost return ingredients @property def total_energy(self) -> float: """Total required energy (crafting time) for single craft""" # TODO: multiply mining energy by 2 since drill has 0.5 speed total_energy = self.energy for ingredient, cost in self.ingredients.items(): if ingredient in all_product_sources: for ingredient_recipe in all_product_sources[ingredient]: # FIXME: this may select the wrong recipe craft_count = max((n for name, n in ingredient_recipe.products.items() if name == ingredient)) total_energy += ingredient_recipe.total_energy / craft_count * cost break return total_energy class Machine(FactorioElement): def __init__(self, name, categories): self.name: str = name self.categories: set = categories recipe_sources: Dict[str, Set[str]] = {} # recipe_name -> technology source # recipes and technologies can share names in Factorio for technology_name in sorted(raw): data = raw[technology_name] current_ingredients = set(data["ingredients"]) technology = Technology(technology_name, current_ingredients, factorio_id, has_modifier=data["has_modifier"], unlocks=set(data["unlocks"])) factorio_id += 1 tech_table[technology_name] = technology.factorio_id technology_table[technology_name] = technology for recipe_name in technology.unlocks: recipe_sources.setdefault(recipe_name, set()).add(technology_name) del (raw) recipes = {} all_product_sources: Dict[str, Set[Recipe]] = {"character": set()} # add uranium mining to logic graph. TODO: add to automatic extractor for mod support raw_recipes["uranium-ore"] = {"ingredients": {"sulfuric-acid": 1}, "products": {"uranium-ore": 1}, "category": "mining", "energy": 2} # raw_recipes["iron-ore"] = {"ingredients": {}, "products": {"iron-ore": 1}, "category": "mining", "energy": 2} # raw_recipes["copper-ore"] = {"ingredients": {}, "products": {"copper-ore": 1}, "category": "mining", "energy": 2} # raw_recipes["coal-ore"] = {"ingredients": {}, "products": {"coal": 1}, "category": "mining", "energy": 2} # raw_recipes["stone"] = {"ingredients": {}, "products": {"coal": 1}, "category": "mining", "energy": 2} for recipe_name, recipe_data in raw_recipes.items(): # example: # "accumulator":{"ingredients":{"iron-plate":2,"battery":5},"products":{"accumulator":1},"category":"crafting"} # FIXME: add mining? recipe = Recipe(recipe_name, recipe_data["category"], recipe_data["ingredients"], recipe_data["products"], recipe_data["energy"] if "energy" in recipe_data else 0) recipes[recipe_name] = recipe if set(recipe.products).isdisjoint( # prevents loop recipes like uranium centrifuging set(recipe.ingredients)) and ("empty-barrel" not in recipe.products or recipe.name == "empty-barrel") and \ not recipe_name.endswith("-reprocessing"): for product_name in recipe.products: all_product_sources.setdefault(product_name, set()).add(recipe) del (raw_recipes) machines: Dict[str, Machine] = {} for name, categories in raw_machines.items(): machine = Machine(name, set(categories)) machines[name] = machine # add electric mining drill as a crafting machine to resolve uranium-ore machines["electric-mining-drill"] = Machine("electric-mining-drill", {"mining"}) machines["assembling-machine-1"].categories.add("crafting-with-fluid") # mod enables this machines["character"].categories.add("basic-crafting") # somehow this is implied and not exported del (raw_machines) # build requirements graph for all technology ingredients all_ingredient_names: Set[str] = set() for technology in technology_table.values(): all_ingredient_names |= technology.ingredients def unlock_just_tech(recipe: Recipe, _done) -> Set[Technology]: current_technologies = recipe.unlocking_technologies for ingredient_name in recipe.ingredients: current_technologies |= recursively_get_unlocking_technologies(ingredient_name, _done, unlock_func=unlock_just_tech) return current_technologies def unlock(recipe: Recipe, _done) -> Set[Technology]: current_technologies = recipe.unlocking_technologies for ingredient_name in recipe.ingredients: current_technologies |= recursively_get_unlocking_technologies(ingredient_name, _done, unlock_func=unlock) current_technologies |= required_category_technologies[recipe.category] return current_technologies def recursively_get_unlocking_technologies(ingredient_name, _done=None, unlock_func=unlock_just_tech) -> Set[ Technology]: if _done: if ingredient_name in _done: return set() else: _done.add(ingredient_name) else: _done = {ingredient_name} recipes = all_product_sources.get(ingredient_name) if not recipes: return set() current_technologies = set() for recipe in recipes: current_technologies |= unlock_func(recipe, _done) return current_technologies required_machine_technologies: Dict[str, FrozenSet[Technology]] = {} for ingredient_name in machines: required_machine_technologies[ingredient_name] = frozenset(recursively_get_unlocking_technologies(ingredient_name)) logical_machines = {} machine_tech_cost = {} for machine in machines.values(): for category in machine.categories: current_cost, current_machine = machine_tech_cost.get(category, (10000, "character")) machine_cost = len(required_machine_technologies[machine.name]) if machine_cost < current_cost: machine_tech_cost[category] = machine_cost, machine.name machine_per_category: Dict[str: str] = {} for category, (cost, machine_name) in machine_tech_cost.items(): machine_per_category[category] = machine_name del (machine_tech_cost) # required technologies to be able to craft recipes from a certain category required_category_technologies: Dict[str, FrozenSet[FrozenSet[Technology]]] = {} for category_name, machine_name in machine_per_category.items(): techs = set() techs |= recursively_get_unlocking_technologies(machine_name) required_category_technologies[category_name] = frozenset(techs) required_technologies: Dict[str, FrozenSet[Technology]] = Utils.KeyedDefaultDict(lambda ingredient_name: frozenset( recursively_get_unlocking_technologies(ingredient_name, unlock_func=unlock))) advancement_technologies: Set[str] = set() for ingredient_name in all_ingredient_names: technologies = required_technologies[ingredient_name] advancement_technologies |= {technology.name for technology in technologies} def get_rocket_requirements(silo_recipe: Recipe, part_recipe: Recipe) -> Set[str]: techs = set() if silo_recipe: for ingredient in silo_recipe.ingredients: techs |= recursively_get_unlocking_technologies(ingredient) for ingredient in part_recipe.ingredients: techs |= recursively_get_unlocking_technologies(ingredient) return {tech.name for tech in techs} free_sample_blacklist: Set[str] = all_ingredient_names | {"rocket-part"} rocket_recipes = { Options.MaxSciencePack.option_space_science_pack: {"rocket-control-unit": 10, "low-density-structure": 10, "rocket-fuel": 10}, Options.MaxSciencePack.option_utility_science_pack: {"speed-module": 10, "steel-plate": 10, "solid-fuel": 10}, Options.MaxSciencePack.option_production_science_pack: {"speed-module": 10, "steel-plate": 10, "solid-fuel": 10}, Options.MaxSciencePack.option_chemical_science_pack: {"advanced-circuit": 10, "steel-plate": 10, "solid-fuel": 10}, Options.MaxSciencePack.option_military_science_pack: {"defender-capsule": 10, "stone-wall": 10, "coal": 10}, Options.MaxSciencePack.option_logistic_science_pack: {"electronic-circuit": 10, "stone-brick": 10, "coal": 10}, Options.MaxSciencePack.option_automation_science_pack: {"copper-cable": 10, "iron-plate": 10, "wood": 10} } advancement_technologies |= {tech.name for tech in required_technologies["rocket-silo"]} # progressive technologies # auto-progressive progressive_rows: Dict[str, Union[List[str], Tuple[str, ...]]] = {} progressive_incs = set() for tech_name in tech_table: if tech_name.endswith("-1"): progressive_rows[tech_name] = [] elif tech_name[-2] == "-" and tech_name[-1] in string.digits: progressive_incs.add(tech_name) for root, progressive in progressive_rows.items(): seeking = root[:-1] + str(int(root[-1]) + 1) while seeking in progressive_incs: progressive.append(seeking) progressive_incs.remove(seeking) seeking = seeking[:-1] + str(int(seeking[-1]) + 1) # make root entry the progressive name for old_name in set(progressive_rows): prog_name = "progressive-" + old_name.rsplit("-", 1)[0] progressive_rows[prog_name] = tuple([old_name] + progressive_rows[old_name]) del (progressive_rows[old_name]) # no -1 start base_starts = set() for remnant in progressive_incs: if remnant[-1] == "2": base_starts.add(remnant[:-2]) for root in base_starts: seeking = root + "-2" progressive = [root] while seeking in progressive_incs: progressive.append(seeking) seeking = seeking[:-1] + str(int(seeking[-1]) + 1) progressive_rows["progressive-" + root] = tuple(progressive) # science packs progressive_rows["progressive-science-pack"] = tuple(Options.MaxSciencePack.get_ordered_science_packs())[1:] # manual progressive progressive_rows["progressive-processing"] = ( "steel-processing", "oil-processing", "sulfur-processing", "advanced-oil-processing", "coal-liquefaction", "uranium-processing", "kovarex-enrichment-process", "nuclear-fuel-reprocessing") progressive_rows["progressive-rocketry"] = ("rocketry", "explosive-rocketry", "atomic-bomb") progressive_rows["progressive-vehicle"] = ("automobilism", "tank", "spidertron") progressive_rows["progressive-train-network"] = ("railway", "fluid-wagon", "automated-rail-transportation", "rail-signals") progressive_rows["progressive-engine"] = ("engine", "electric-engine") progressive_rows["progressive-armor"] = ("heavy-armor", "modular-armor", "power-armor", "power-armor-mk2") progressive_rows["progressive-personal-battery"] = ("battery-equipment", "battery-mk2-equipment") progressive_rows["progressive-energy-shield"] = ("energy-shield-equipment", "energy-shield-mk2-equipment") progressive_rows["progressive-wall"] = ("stone-wall", "gate") progressive_rows["progressive-follower"] = ("defender", "distractor", "destroyer") progressive_rows["progressive-inserter"] = ("fast-inserter", "stack-inserter") sorted_rows = sorted(progressive_rows) # to keep ID mappings the same. # If there's a breaking change at some point, then this should be moved in with the sorted ordering progressive_rows["progressive-turret"] = ("gun-turret", "laser-turret") sorted_rows.append("progressive-turret") progressive_rows["progressive-flamethrower"] = ("flamethrower",) # leaving out flammables, as they do nothing sorted_rows.append("progressive-flamethrower") progressive_rows["progressive-personal-roboport-equipment"] = ("personal-roboport-equipment", "personal-roboport-mk2-equipment") sorted_rows.append("progressive-personal-roboport-equipment") # integrate into source_target_mapping: Dict[str, str] = { "progressive-braking-force": "progressive-train-network", "progressive-inserter-capacity-bonus": "progressive-inserter", "progressive-refined-flammables": "progressive-flamethrower" } for source, target in source_target_mapping.items(): progressive_rows[target] += progressive_rows[source] base_tech_table = tech_table.copy() # without progressive techs base_technology_table = technology_table.copy() progressive_tech_table: Dict[str, int] = {} progressive_technology_table: Dict[str, Technology] = {} for root in sorted_rows: progressive = progressive_rows[root] assert all(tech in tech_table for tech in progressive) factorio_id += 1 progressive_technology = Technology(root, technology_table[progressive_rows[root][0]].ingredients, factorio_id, progressive, has_modifier=any(technology_table[tech].has_modifier for tech in progressive), unlocks=any(technology_table[tech].unlocks for tech in progressive)) progressive_tech_table[root] = progressive_technology.factorio_id progressive_technology_table[root] = progressive_technology if any(tech in advancement_technologies for tech in progressive): advancement_technologies.add(root) tech_to_progressive_lookup: Dict[str, str] = {} for technology in progressive_technology_table.values(): if technology.name not in source_target_mapping: for progressive in technology.progressive: tech_to_progressive_lookup[progressive] = technology.name tech_table.update(progressive_tech_table) technology_table.update(progressive_technology_table) # techs that are never progressive common_tech_table: Dict[str, int] = {tech_name: tech_id for tech_name, tech_id in base_tech_table.items() if tech_name not in progressive_tech_table} useless_technologies: Set[str] = {tech_name for tech_name in common_tech_table if not technology_table[tech_name].useful()} lookup_id_to_name: Dict[int, str] = {item_id: item_name for item_name, item_id in tech_table.items()} rel_cost = { "wood": 10000, "iron-ore": 1, "copper-ore": 1, "stone": 1, "crude-oil": 0.5, "water": 0.001, "coal": 1, "raw-fish": 1000, "steam": 0.01, "used-up-uranium-fuel-cell": 1000 } # forbid liquids for now, TODO: allow a single liquid per assembler blacklist: Set[str] = all_ingredient_names | {"rocket-part", "crude-oil", "water", "sulfuric-acid", "petroleum-gas", "light-oil", "heavy-oil", "lubricant", "steam"} @Utils.cache_argsless def get_science_pack_pools() -> Dict[str, Set[str]]: def get_estimated_difficulty(recipe: Recipe): base_ingredients = recipe.base_cost cost = 0 for ingredient_name, amount in base_ingredients.items(): cost += rel_cost.get(ingredient_name, 1) * amount return cost science_pack_pools = {} already_taken = blacklist.copy() current_difficulty = 5 for science_pack in Options.MaxSciencePack.get_ordered_science_packs(): current = science_pack_pools[science_pack] = set() for name, recipe in recipes.items(): if (science_pack != "automation-science-pack" or not recipe.recursive_unlocking_technologies) \ and get_estimated_difficulty(recipe) < current_difficulty: current |= set(recipe.products) if science_pack == "automation-science-pack": current |= {"iron-ore", "copper-ore", "coal", "stone"} current -= already_taken already_taken |= current current_difficulty *= 2 return science_pack_pools <file_sep># generated by https://github.com/Berserker66/HollowKnight.RandomizerMod/blob/master/extract_data.py # do not edit manually from .Types import HKItemData from typing import Dict, Set item_table = \ { '150_Geo-Resting_Grounds_Chest': HKItemData(advancement=False, id=16777336, type='Geo'), '160_Geo-Weavers_Den_Chest': HKItemData(advancement=False, id=16777338, type='Geo'), '1_Geo': HKItemData(advancement=False, id=16777339, type='Fake'), '200_Geo-False_Knight_Chest': HKItemData(advancement=False, id=16777331, type='Geo'), '380_Geo-Soul_Master_Chest': HKItemData(advancement=False, id=16777332, type='Geo'), '620_Geo-Mantis_Lords_Chest': HKItemData(advancement=False, id=16777335, type='Geo'), '655_Geo-Watcher_Knights_Chest': HKItemData(advancement=False, id=16777333, type='Geo'), '80_Geo-Crystal_Peak_Chest': HKItemData(advancement=False, id=16777337, type='Geo'), '85_Geo-Greenpath_Chest': HKItemData(advancement=False, id=16777334, type='Geo'), 'Abyss': HKItemData(advancement=True, id=0, type='Event'), 'Abyss_Shriek': HKItemData(advancement=True, id=16777236, type='Skill'), 'Ancestral_Mound': HKItemData(advancement=True, id=0, type='Event'), 'Ancient_Basin_Map': HKItemData(advancement=False, id=16777482, type='Map'), 'Arcane_Egg-Birthplace': HKItemData(advancement=False, id=16777402, type='Relic'), 'Arcane_Egg-Lifeblood_Core': HKItemData(advancement=False, id=16777400, type='Relic'), 'Arcane_Egg-Seer': HKItemData(advancement=False, id=16777399, type='Relic'), 'Arcane_Egg-Shade_Cloak': HKItemData(advancement=False, id=16777401, type='Relic'), 'Awoken_Dream_Nail': HKItemData(advancement=True, id=16777230, type='Skill'), 'Baldur_Shell': HKItemData(advancement=False, id=16777245, type='Charm'), "Beast's_Den": HKItemData(advancement=True, id=0, type='Event'), 'Blue_Lake': HKItemData(advancement=True, id=0, type='Event'), 'Boss_Essence-Elder_Hu': HKItemData(advancement=True, id=16777418, type='Essence_Boss'), 'Boss_Essence-Failed_Champion': HKItemData(advancement=True, id=16777425, type='Essence_Boss'), 'Boss_Essence-Galien': HKItemData(advancement=True, id=16777423, type='Essence_Boss'), 'Boss_Essence-Gorb': HKItemData(advancement=True, id=16777420, type='Essence_Boss'), 'Boss_Essence-Grey_Prince_Zote': HKItemData(advancement=True, id=16777429, type='Essence_Boss'), 'Boss_Essence-Lost_Kin': HKItemData(advancement=True, id=16777427, type='Essence_Boss'), 'Boss_Essence-Markoth': HKItemData(advancement=True, id=16777424, type='Essence_Boss'), 'Boss_Essence-Marmu': HKItemData(advancement=True, id=16777421, type='Essence_Boss'), 'Boss_Essence-No_Eyes': HKItemData(advancement=True, id=16777422, type='Essence_Boss'), 'Boss_Essence-Soul_Tyrant': HKItemData(advancement=True, id=16777426, type='Essence_Boss'), 'Boss_Essence-White_Defender': HKItemData(advancement=True, id=16777428, type='Essence_Boss'), 'Boss_Essence-Xero': HKItemData(advancement=True, id=16777419, type='Essence_Boss'), 'Bottom_Left_Fungal_Wastes': HKItemData(advancement=True, id=0, type='Event'), "Bottom_Left_Queen's_Gardens": HKItemData(advancement=True, id=0, type='Event'), "Bottom_Right_Queen's_Gardens": HKItemData(advancement=True, id=0, type='Event'), 'Can_Stag': HKItemData(advancement=True, id=0, type='Event'), 'Cast_Off_Shell': HKItemData(advancement=True, id=0, type='Event'), "Center_Right_Kingdom's_Edge": HKItemData(advancement=True, id=0, type='Event'), "Central_Kingdom's_Edge": HKItemData(advancement=True, id=0, type='Event'), 'Central_Left_Waterways': HKItemData(advancement=True, id=0, type='Event'), 'Charm_Notch-Colosseum': HKItemData(advancement=False, id=16777323, type='Notch'), 'Charm_Notch-Fog_Canyon': HKItemData(advancement=False, id=16777322, type='Notch'), 'Charm_Notch-Grimm': HKItemData(advancement=False, id=16777324, type='Notch'), 'Charm_Notch-Shrumal_Ogres': HKItemData(advancement=False, id=16777321, type='Notch'), 'City_Crest': HKItemData(advancement=True, id=16777283, type='Key'), 'City_Storerooms_Stag': HKItemData(advancement=True, id=16777495, type='Stag'), 'City_of_Tears_Map': HKItemData(advancement=False, id=16777484, type='Map'), "Collector's_Map": HKItemData(advancement=False, id=16777295, type='Key'), 'Colosseum': HKItemData(advancement=True, id=0, type='Event'), 'Crossroads': HKItemData(advancement=True, id=0, type='Event'), 'Crossroads_Map': HKItemData(advancement=False, id=16777476, type='Map'), 'Crossroads_Stag': HKItemData(advancement=True, id=16777491, type='Stag'), 'Crystal_Heart': HKItemData(advancement=True, id=16777224, type='Skill'), 'Crystal_Peak': HKItemData(advancement=True, id=0, type='Event'), 'Crystal_Peak_Map': HKItemData(advancement=False, id=16777487, type='Map'), 'Crystallized_Mound': HKItemData(advancement=True, id=0, type='Event'), 'Cyclone_Slash': HKItemData(advancement=True, id=16777237, type='Skill'), 'Dark_Deepnest': HKItemData(advancement=True, id=0, type='Event'), 'Dash_Slash': HKItemData(advancement=True, id=16777238, type='Skill'), 'Dashmaster': HKItemData(advancement=True, id=16777271, type='Charm'), 'Deep_Focus': HKItemData(advancement=False, id=16777274, type='Charm'), 'Deepnest': HKItemData(advancement=True, id=0, type='Event'), 'Deepnest_Map-Right_[Gives_Quill]': HKItemData(advancement=False, id=16777481, type='Map'), 'Deepnest_Map-Upper': HKItemData(advancement=False, id=16777480, type='Map'), "Defender's_Crest": HKItemData(advancement=False, id=16777250, type='Charm'), 'Descending_Dark': HKItemData(advancement=True, id=16777234, type='Skill'), 'Desolate_Dive': HKItemData(advancement=True, id=16777233, type='Skill'), 'Dirtmouth': HKItemData(advancement=True, id=0, type='Event'), 'Dirtmouth_Stag': HKItemData(advancement=True, id=16777490, type='Stag'), 'Distant_Village': HKItemData(advancement=True, id=0, type='Event'), 'Distant_Village_Stag': HKItemData(advancement=True, id=16777498, type='Stag'), 'Dream_Gate': HKItemData(advancement=True, id=16777229, type='Skill'), 'Dream_Nail': HKItemData(advancement=True, id=16777228, type='Skill'), 'Dream_Wielder': HKItemData(advancement=False, id=16777270, type='Charm'), 'Dreamer': HKItemData(advancement=True, id=16777221, type='Fake'), 'Dreamshield': HKItemData(advancement=False, id=16777280, type='Charm'), 'Elegant_Key': HKItemData(advancement=True, id=16777291, type='Key'), 'Emilitia': HKItemData(advancement=True, id=0, type='Event'), 'Equipped': HKItemData(advancement=False, id=16777521, type='Fake'), 'Failed_Tramway': HKItemData(advancement=True, id=0, type='Event'), 'Far_Left_Basin': HKItemData(advancement=True, id=0, type='Event'), 'Far_Left_Waterways': HKItemData(advancement=True, id=0, type='Event'), "Far_Queen's_Gardens": HKItemData(advancement=True, id=0, type='Event'), 'Far_Right_Deepnest': HKItemData(advancement=True, id=0, type='Event'), 'Flukenest': HKItemData(advancement=False, id=16777251, type='Charm'), 'Focus': HKItemData(advancement=True, id=16777240, type='Cursed'), 'Fog_Canyon_Map': HKItemData(advancement=False, id=16777478, type='Map'), 'Fragile_Greed': HKItemData(advancement=False, id=16777264, type='Charm'), 'Fragile_Heart': HKItemData(advancement=False, id=16777263, type='Charm'), 'Fragile_Strength': HKItemData(advancement=False, id=16777265, type='Charm'), 'Fungal_Core': HKItemData(advancement=True, id=0, type='Event'), 'Fungal_Wastes': HKItemData(advancement=True, id=0, type='Event'), 'Fungal_Wastes_Map': HKItemData(advancement=False, id=16777479, type='Map'), 'Fury_of_the_Fallen': HKItemData(advancement=False, id=16777246, type='Charm'), 'Gathering_Swarm': HKItemData(advancement=False, id=16777241, type='Charm'), 'Glowing_Womb': HKItemData(advancement=True, id=16777262, type='Charm'), 'Godtuner': HKItemData(advancement=False, id=16777294, type='Key'), 'Great_Slash': HKItemData(advancement=True, id=16777239, type='Skill'), 'Greenpath': HKItemData(advancement=True, id=0, type='Event'), 'Greenpath-QG': HKItemData(advancement=True, id=0, type='Event'), 'Greenpath_Map': HKItemData(advancement=False, id=16777477, type='Map'), 'Greenpath_Stag': HKItemData(advancement=True, id=16777492, type='Stag'), 'Grimmchild': HKItemData(advancement=True, id=16777282, type='Charm'), 'Grimmkin_Flame-Ancient_Basin': HKItemData(advancement=True, id=16777516, type='Flame'), 'Grimmkin_Flame-Brumm': HKItemData(advancement=True, id=16777518, type='Flame'), 'Grimmkin_Flame-City_Storerooms': HKItemData(advancement=True, id=16777509, type='Flame'), 'Grimmkin_Flame-Crystal_Peak': HKItemData(advancement=True, id=16777511, type='Flame'), 'Grimmkin_Flame-Fungal_Core': HKItemData(advancement=True, id=16777515, type='Flame'), 'Grimmkin_Flame-Greenpath': HKItemData(advancement=True, id=16777510, type='Flame'), 'Grimmkin_Flame-Hive': HKItemData(advancement=True, id=16777517, type='Flame'), "Grimmkin_Flame-King's_Pass": HKItemData(advancement=True, id=16777512, type='Flame'), "Grimmkin_Flame-Kingdom's_Edge": HKItemData(advancement=True, id=16777514, type='Flame'), 'Grimmkin_Flame-Resting_Grounds': HKItemData(advancement=True, id=16777513, type='Flame'), 'Grub-Basin_Requires_Dive': HKItemData(advancement=True, id=16777452, type='Grub'), 'Grub-Basin_Requires_Wings': HKItemData(advancement=True, id=16777451, type='Grub'), "Grub-Beast's_Den": HKItemData(advancement=True, id=16777446, type='Grub'), 'Grub-City_of_Tears_Guarded': HKItemData(advancement=True, id=16777459, type='Grub'), 'Grub-City_of_Tears_Left': HKItemData(advancement=True, id=16777456, type='Grub'), 'Grub-Collector_1': HKItemData(advancement=True, id=16777473, type='Grub'), 'Grub-Collector_2': HKItemData(advancement=True, id=16777474, type='Grub'), 'Grub-Collector_3': HKItemData(advancement=True, id=16777475, type='Grub'), 'Grub-Crossroads_Acid': HKItemData(advancement=True, id=16777430, type='Grub'), 'Grub-Crossroads_Center': HKItemData(advancement=True, id=16777431, type='Grub'), 'Grub-Crossroads_Guarded': HKItemData(advancement=True, id=16777434, type='Grub'), 'Grub-Crossroads_Spike': HKItemData(advancement=True, id=16777433, type='Grub'), 'Grub-Crossroads_Stag': HKItemData(advancement=True, id=16777432, type='Grub'), 'Grub-Crystal_Heart': HKItemData(advancement=True, id=16777467, type='Grub'), 'Grub-Crystal_Peak_Below_Chest': HKItemData(advancement=True, id=16777462, type='Grub'), 'Grub-Crystal_Peak_Crushers': HKItemData(advancement=True, id=16777466, type='Grub'), 'Grub-Crystal_Peak_Mimic': HKItemData(advancement=True, id=16777465, type='Grub'), 'Grub-Crystal_Peak_Spike': HKItemData(advancement=True, id=16777464, type='Grub'), 'Grub-Crystallized_Mound': HKItemData(advancement=True, id=16777463, type='Grub'), 'Grub-Dark_Deepnest': HKItemData(advancement=True, id=16777445, type='Grub'), 'Grub-Deepnest_Mimic': HKItemData(advancement=True, id=16777442, type='Grub'), 'Grub-Deepnest_Nosk': HKItemData(advancement=True, id=16777443, type='Grub'), 'Grub-Deepnest_Spike': HKItemData(advancement=True, id=16777444, type='Grub'), 'Grub-Fog_Canyon': HKItemData(advancement=True, id=16777439, type='Grub'), 'Grub-Fungal_Bouncy': HKItemData(advancement=True, id=16777440, type='Grub'), 'Grub-Fungal_Spore_Shroom': HKItemData(advancement=True, id=16777441, type='Grub'), 'Grub-Greenpath_Cornifer': HKItemData(advancement=True, id=16777435, type='Grub'), 'Grub-Greenpath_Journal': HKItemData(advancement=True, id=16777436, type='Grub'), 'Grub-Greenpath_MMC': HKItemData(advancement=True, id=16777437, type='Grub'), 'Grub-Greenpath_Stag': HKItemData(advancement=True, id=16777438, type='Grub'), 'Grub-Hallownest_Crown': HKItemData(advancement=True, id=16777468, type='Grub'), 'Grub-Hive_External': HKItemData(advancement=True, id=16777449, type='Grub'), 'Grub-Hive_Internal': HKItemData(advancement=True, id=16777450, type='Grub'), 'Grub-Howling_Cliffs': HKItemData(advancement=True, id=16777469, type='Grub'), "Grub-King's_Station": HKItemData(advancement=True, id=16777460, type='Grub'), "Grub-Kingdom's_Edge_Camp": HKItemData(advancement=True, id=16777448, type='Grub'), "Grub-Kingdom's_Edge_Oro": HKItemData(advancement=True, id=16777447, type='Grub'), "Grub-Queen's_Gardens_Marmu": HKItemData(advancement=True, id=16777471, type='Grub'), "Grub-Queen's_Gardens_Stag": HKItemData(advancement=True, id=16777470, type='Grub'), "Grub-Queen's_Gardens_Top": HKItemData(advancement=True, id=16777472, type='Grub'), 'Grub-Resting_Grounds': HKItemData(advancement=True, id=16777461, type='Grub'), 'Grub-Soul_Sanctum': HKItemData(advancement=True, id=16777457, type='Grub'), "Grub-Watcher's_Spire": HKItemData(advancement=True, id=16777458, type='Grub'), 'Grub-Waterways_East': HKItemData(advancement=True, id=16777454, type='Grub'), 'Grub-Waterways_Main': HKItemData(advancement=True, id=16777453, type='Grub'), 'Grub-Waterways_Requires_Tram': HKItemData(advancement=True, id=16777455, type='Grub'), "Grubberfly's_Elegy": HKItemData(advancement=True, id=16777275, type='Charm'), 'Grubfather': HKItemData(advancement=False, id=16777519, type='Fake'), 'Grubsong': HKItemData(advancement=False, id=16777243, type='Charm'), "Hallownest's_Crown": HKItemData(advancement=True, id=0, type='Event'), "Hallownest_Seal-Beast's_Den": HKItemData(advancement=False, id=16777389, type='Relic'), 'Hallownest_Seal-City_Rafters': HKItemData(advancement=False, id=16777385, type='Relic'), 'Hallownest_Seal-Crossroads_Well': HKItemData(advancement=False, id=16777374, type='Relic'), 'Hallownest_Seal-Deepnest_By_Mantis_Lords': HKItemData(advancement=False, id=16777388, type='Relic'), 'Hallownest_Seal-Fog_Canyon_East': HKItemData(advancement=False, id=16777378, type='Relic'), 'Hallownest_Seal-Fog_Canyon_West': HKItemData(advancement=False, id=16777377, type='Relic'), 'Hallownest_Seal-Fungal_Wastes_Sporgs': HKItemData(advancement=False, id=16777380, type='Relic'), 'Hallownest_Seal-Greenpath': HKItemData(advancement=False, id=16777376, type='Relic'), 'Hallownest_Seal-Grubs': HKItemData(advancement=False, id=16777375, type='Relic'), "Hallownest_Seal-King's_Station": HKItemData(advancement=False, id=16777384, type='Relic'), 'Hallownest_Seal-Mantis_Lords': HKItemData(advancement=False, id=16777381, type='Relic'), "Hallownest_Seal-Queen's_Gardens": HKItemData(advancement=False, id=16777390, type='Relic'), "Hallownest_Seal-Queen's_Station": HKItemData(advancement=False, id=16777379, type='Relic'), 'Hallownest_Seal-Resting_Grounds_Catacombs': HKItemData(advancement=False, id=16777383, type='Relic'), 'Hallownest_Seal-Seer': HKItemData(advancement=False, id=16777382, type='Relic'), 'Hallownest_Seal-Soul_Sanctum': HKItemData(advancement=False, id=16777386, type='Relic'), 'Hallownest_Seal-Watcher_Knight': HKItemData(advancement=False, id=16777387, type='Relic'), 'Heavy_Blow': HKItemData(advancement=False, id=16777255, type='Charm'), 'Herrah': HKItemData(advancement=True, id=16777219, type='Dreamer'), 'Hidden_Station_Stag': HKItemData(advancement=True, id=16777499, type='Stag'), 'Hive': HKItemData(advancement=True, id=0, type='Event'), 'Hiveblood': HKItemData(advancement=False, id=16777269, type='Charm'), 'Hollow Knight': HKItemData(advancement=True, id=0, type='Event'), 'Howling_Cliffs': HKItemData(advancement=True, id=0, type='Event'), 'Howling_Cliffs_Map': HKItemData(advancement=False, id=16777486, type='Map'), 'Howling_Wraiths': HKItemData(advancement=True, id=16777235, type='Skill'), "Isma's_Grove": HKItemData(advancement=True, id=0, type='Event'), "Isma's_Tear": HKItemData(advancement=True, id=16777227, type='Skill'), "Joni's_Blessing": HKItemData(advancement=True, id=16777267, type='Charm'), 'Junk_Pit': HKItemData(advancement=True, id=0, type='Event'), "King's_Brand": HKItemData(advancement=True, id=16777293, type='Key'), "King's_Idol-Cliffs": HKItemData(advancement=False, id=16777392, type='Relic'), "King's_Idol-Crystal_Peak": HKItemData(advancement=False, id=16777393, type='Relic'), "King's_Idol-Deepnest": HKItemData(advancement=False, id=16777398, type='Relic'), "King's_Idol-Dung_Defender": HKItemData(advancement=False, id=16777395, type='Relic'), "King's_Idol-Glade_of_Hope": HKItemData(advancement=False, id=16777394, type='Relic'), "King's_Idol-Great_Hopper": HKItemData(advancement=False, id=16777396, type='Relic'), "King's_Idol-Grubs": HKItemData(advancement=False, id=16777391, type='Relic'), "King's_Idol-Pale_Lurker": HKItemData(advancement=False, id=16777397, type='Relic'), "King's_Pass": HKItemData(advancement=True, id=0, type='Event'), "King's_Station_Stag": HKItemData(advancement=True, id=16777496, type='Stag'), 'King_Fragment': HKItemData(advancement=True, id=16777277, type='Charm'), "Kingdom's_Edge_Map": HKItemData(advancement=False, id=16777483, type='Map'), 'Lake_of_Unn': HKItemData(advancement=True, id=0, type='Event'), 'Left_City': HKItemData(advancement=True, id=0, type='Event'), 'Left_Elevator': HKItemData(advancement=True, id=0, type='Event'), 'Left_Fog_Canyon': HKItemData(advancement=True, id=0, type='Event'), 'Lifeblood_Cocoon-Ancestral_Mound': HKItemData(advancement=False, id=16777502, type='Cocoon'), 'Lifeblood_Cocoon-Failed_Tramway': HKItemData(advancement=False, id=16777506, type='Cocoon'), 'Lifeblood_Cocoon-Fog_Canyon_West': HKItemData(advancement=False, id=16777504, type='Cocoon'), 'Lifeblood_Cocoon-Galien': HKItemData(advancement=False, id=16777507, type='Cocoon'), 'Lifeblood_Cocoon-Greenpath': HKItemData(advancement=False, id=16777503, type='Cocoon'), "Lifeblood_Cocoon-King's_Pass": HKItemData(advancement=False, id=16777501, type='Cocoon'), "Lifeblood_Cocoon-Kingdom's_Edge": HKItemData(advancement=False, id=16777508, type='Cocoon'), 'Lifeblood_Cocoon-Mantis_Village': HKItemData(advancement=False, id=16777505, type='Cocoon'), 'Lifeblood_Core': HKItemData(advancement=True, id=16777249, type='Charm'), 'Lifeblood_Heart': HKItemData(advancement=True, id=16777248, type='Charm'), 'Longnail': HKItemData(advancement=False, id=16777258, type='Charm'), 'Love_Key': HKItemData(advancement=True, id=16777292, type='Key'), 'Lower_Basin': HKItemData(advancement=True, id=0, type='Event'), "Lower_King's_Station": HKItemData(advancement=True, id=0, type='Event'), "Lower_Kingdom's_Edge": HKItemData(advancement=True, id=0, type='Event'), 'Lower_Left_Waterways': HKItemData(advancement=True, id=0, type='Event'), 'Lower_Resting_Grounds': HKItemData(advancement=True, id=0, type='Event'), 'Lower_Tram': HKItemData(advancement=True, id=0, type='Event'), 'Lumafly_Lantern': HKItemData(advancement=True, id=16777284, type='Key'), 'Lurien': HKItemData(advancement=True, id=16777217, type='Dreamer'), 'Mantis_Claw': HKItemData(advancement=True, id=16777223, type='Skill'), 'Mantis_Outskirts': HKItemData(advancement=True, id=0, type='Event'), 'Mantis_Village': HKItemData(advancement=True, id=0, type='Event'), 'Mark_of_Pride': HKItemData(advancement=True, id=16777253, type='Charm'), 'Mask_Shard-5_Grubs': HKItemData(advancement=False, id=16777301, type='Mask'), 'Mask_Shard-Bretta': HKItemData(advancement=False, id=16777311, type='Mask'), 'Mask_Shard-Brooding_Mawlek': HKItemData(advancement=False, id=16777302, type='Mask'), 'Mask_Shard-Crossroads_Goam': HKItemData(advancement=False, id=16777303, type='Mask'), 'Mask_Shard-Deepnest': HKItemData(advancement=False, id=16777306, type='Mask'), 'Mask_Shard-Enraged_Guardian': HKItemData(advancement=False, id=16777308, type='Mask'), 'Mask_Shard-Grey_Mourner': HKItemData(advancement=False, id=16777310, type='Mask'), 'Mask_Shard-Hive': HKItemData(advancement=False, id=16777309, type='Mask'), "Mask_Shard-Queen's_Station": HKItemData(advancement=False, id=16777305, type='Mask'), 'Mask_Shard-Seer': HKItemData(advancement=False, id=16777300, type='Mask'), 'Mask_Shard-Sly1': HKItemData(advancement=False, id=16777296, type='Mask'), 'Mask_Shard-Sly2': HKItemData(advancement=False, id=16777297, type='Mask'), 'Mask_Shard-Sly3': HKItemData(advancement=False, id=16777298, type='Mask'), 'Mask_Shard-Sly4': HKItemData(advancement=False, id=16777299, type='Mask'), 'Mask_Shard-Stone_Sanctuary': HKItemData(advancement=False, id=16777304, type='Mask'), 'Mask_Shard-Waterways': HKItemData(advancement=False, id=16777307, type='Mask'), 'Mid_Basin': HKItemData(advancement=True, id=0, type='Event'), 'Monarch_Wings': HKItemData(advancement=True, id=16777225, type='Skill'), 'Monomon': HKItemData(advancement=True, id=16777218, type='Dreamer'), 'Mothwing_Cloak': HKItemData(advancement=True, id=16777222, type='Skill'), "Nailmaster's_Glory": HKItemData(advancement=False, id=16777266, type='Charm'), 'Oro_Bench': HKItemData(advancement=True, id=0, type='Event'), 'Overgrown_Mound': HKItemData(advancement=True, id=0, type='Event'), 'Palace_Grounds': HKItemData(advancement=True, id=0, type='Event'), 'Pale_Lurker_Area': HKItemData(advancement=True, id=0, type='Event'), 'Pale_Ore-Basin': HKItemData(advancement=False, id=16777325, type='Ore'), 'Pale_Ore-Colosseum': HKItemData(advancement=False, id=16777330, type='Ore'), 'Pale_Ore-Crystal_Peak': HKItemData(advancement=False, id=16777326, type='Ore'), 'Pale_Ore-Grubs': HKItemData(advancement=False, id=16777329, type='Ore'), 'Pale_Ore-Nosk': HKItemData(advancement=False, id=16777327, type='Ore'), 'Pale_Ore-Seer': HKItemData(advancement=False, id=16777328, type='Ore'), 'Placeholder': HKItemData(advancement=False, id=16777522, type='Fake'), 'Pleasure_House': HKItemData(advancement=True, id=0, type='Event'), "Queen's_Gardens_Map": HKItemData(advancement=False, id=16777488, type='Map'), "Queen's_Gardens_Stag": HKItemData(advancement=True, id=16777494, type='Stag'), "Queen's_Station": HKItemData(advancement=True, id=0, type='Event'), "Queen's_Station_Stag": HKItemData(advancement=True, id=16777493, type='Stag'), 'Queen_Fragment': HKItemData(advancement=True, id=16777276, type='Charm'), 'Quick_Focus': HKItemData(advancement=False, id=16777247, type='Charm'), 'Quick_Slash': HKItemData(advancement=False, id=16777272, type='Charm'), "Rancid_Egg-Beast's_Den": HKItemData(advancement=False, id=16777351, type='Egg'), 'Rancid_Egg-Blue_Lake': HKItemData(advancement=False, id=16777345, type='Egg'), 'Rancid_Egg-City_of_Tears_Left': HKItemData(advancement=False, id=16777349, type='Egg'), 'Rancid_Egg-City_of_Tears_Pleasure_House': HKItemData(advancement=False, id=16777350, type='Egg'), 'Rancid_Egg-Crystal_Peak_Dark_Room': HKItemData(advancement=False, id=16777347, type='Egg'), 'Rancid_Egg-Crystal_Peak_Dive_Entrance': HKItemData(advancement=False, id=16777346, type='Egg'), 'Rancid_Egg-Crystal_Peak_Tall_Room': HKItemData(advancement=False, id=16777348, type='Egg'), 'Rancid_Egg-Dark_Deepnest': HKItemData(advancement=False, id=16777352, type='Egg'), 'Rancid_Egg-Fungal_Core': HKItemData(advancement=False, id=16777343, type='Egg'), 'Rancid_Egg-Grubs': HKItemData(advancement=False, id=16777341, type='Egg'), 'Rancid_Egg-Near_Quick_Slash': HKItemData(advancement=False, id=16777354, type='Egg'), "Rancid_Egg-Queen's_Gardens": HKItemData(advancement=False, id=16777344, type='Egg'), 'Rancid_Egg-Sheo': HKItemData(advancement=False, id=16777342, type='Egg'), 'Rancid_Egg-Sly': HKItemData(advancement=False, id=16777340, type='Egg'), "Rancid_Egg-Upper_Kingdom's_Edge": HKItemData(advancement=False, id=16777355, type='Egg'), 'Rancid_Egg-Waterways_East': HKItemData(advancement=False, id=16777356, type='Egg'), 'Rancid_Egg-Waterways_Main': HKItemData(advancement=False, id=16777357, type='Egg'), 'Rancid_Egg-Waterways_West_Bluggsac': HKItemData(advancement=False, id=16777358, type='Egg'), 'Rancid_Egg-Waterways_West_Pickup': HKItemData(advancement=False, id=16777359, type='Egg'), "Rancid_Egg-Weaver's_Den": HKItemData(advancement=False, id=16777353, type='Egg'), 'Resting_Grounds_Map': HKItemData(advancement=False, id=16777489, type='Map'), 'Resting_Grounds_Stag': HKItemData(advancement=True, id=16777497, type='Stag'), 'Right_City': HKItemData(advancement=True, id=0, type='Event'), 'Right_Elevator': HKItemData(advancement=True, id=0, type='Event'), 'Right_Fog_Canyon': HKItemData(advancement=True, id=0, type='Event'), 'Right_Waterways': HKItemData(advancement=True, id=0, type='Event'), 'Royal_Waterways_Map': HKItemData(advancement=False, id=16777485, type='Map'), 'Seer': HKItemData(advancement=False, id=16777520, type='Fake'), 'Shade_Cloak': HKItemData(advancement=True, id=16777226, type='Skill'), 'Shade_Soul': HKItemData(advancement=True, id=16777232, type='Skill'), 'Shaman_Stone': HKItemData(advancement=False, id=16777259, type='Charm'), 'Shape_of_Unn': HKItemData(advancement=False, id=16777268, type='Charm'), 'Sharp_Shadow': HKItemData(advancement=True, id=16777256, type='Charm'), "Shopkeeper's_Key": HKItemData(advancement=True, id=16777290, type='Key'), 'Simple_Key-Basin': HKItemData(advancement=True, id=16777287, type='Key'), 'Simple_Key-City': HKItemData(advancement=True, id=16777288, type='Key'), 'Simple_Key-Lurker': HKItemData(advancement=True, id=16777289, type='Key'), 'Simple_Key-Sly': HKItemData(advancement=True, id=16777286, type='Key'), 'Soul_Catcher': HKItemData(advancement=False, id=16777260, type='Charm'), 'Soul_Eater': HKItemData(advancement=False, id=16777261, type='Charm'), 'Soul_Sanctum': HKItemData(advancement=True, id=0, type='Event'), 'Spell_Twister': HKItemData(advancement=False, id=16777273, type='Charm'), 'Spirits_Glade': HKItemData(advancement=True, id=0, type='Event'), 'Spore_Shroom': HKItemData(advancement=True, id=16777257, type='Charm'), 'Sprintmaster': HKItemData(advancement=True, id=16777279, type='Charm'), 'Stag_Nest': HKItemData(advancement=True, id=0, type='Event'), 'Stag_Nest_Stag': HKItemData(advancement=True, id=16777500, type='Stag'), 'Stalwart_Shell': HKItemData(advancement=False, id=16777244, type='Charm'), 'Steady_Body': HKItemData(advancement=False, id=16777254, type='Charm'), 'Stone_Sanctuary': HKItemData(advancement=True, id=0, type='Event'), "Teacher's_Archives": HKItemData(advancement=True, id=0, type='Event'), 'Thorns_of_Agony': HKItemData(advancement=False, id=16777252, type='Charm'), "Top_Kingdom's_Edge": HKItemData(advancement=True, id=0, type='Event'), "Top_Left_Queen's_Gardens": HKItemData(advancement=True, id=0, type='Event'), "Top_Right_Queen's_Gardens": HKItemData(advancement=True, id=0, type='Event'), 'Tower_of_Love': HKItemData(advancement=True, id=0, type='Event'), 'Tram_Pass': HKItemData(advancement=True, id=16777285, type='Key'), 'Upper_Basin': HKItemData(advancement=True, id=0, type='Event'), 'Upper_Crystal_Peak': HKItemData(advancement=True, id=0, type='Event'), 'Upper_Deepnest': HKItemData(advancement=True, id=0, type='Event'), "Upper_King's_Station": HKItemData(advancement=True, id=0, type='Event'), "Upper_Kingdom's_Edge": HKItemData(advancement=True, id=0, type='Event'), 'Upper_Left_Waterways': HKItemData(advancement=True, id=0, type='Event'), 'Upper_Resting_Grounds': HKItemData(advancement=True, id=0, type='Event'), 'Upper_Tram': HKItemData(advancement=True, id=0, type='Event'), 'Vengeful_Spirit': HKItemData(advancement=True, id=16777231, type='Skill'), 'Vessel_Fragment-Basin': HKItemData(advancement=False, id=16777318, type='Vessel'), 'Vessel_Fragment-City': HKItemData(advancement=False, id=16777316, type='Vessel'), 'Vessel_Fragment-Crossroads': HKItemData(advancement=False, id=16777317, type='Vessel'), 'Vessel_Fragment-Deepnest': HKItemData(advancement=False, id=16777319, type='Vessel'), 'Vessel_Fragment-Greenpath': HKItemData(advancement=False, id=16777315, type='Vessel'), 'Vessel_Fragment-Seer': HKItemData(advancement=False, id=16777314, type='Vessel'), 'Vessel_Fragment-Sly1': HKItemData(advancement=False, id=16777312, type='Vessel'), 'Vessel_Fragment-Sly2': HKItemData(advancement=False, id=16777313, type='Vessel'), 'Vessel_Fragment-Stag_Nest': HKItemData(advancement=False, id=16777320, type='Vessel'), 'Void_Heart': HKItemData(advancement=True, id=16777278, type='Charm'), "Wanderer's_Journal-Above_Mantis_Village": HKItemData(advancement=False, id=16777364, type='Relic'), "Wanderer's_Journal-Ancient_Basin": HKItemData(advancement=False, id=16777370, type='Relic'), "Wanderer's_Journal-City_Storerooms": HKItemData(advancement=False, id=16777369, type='Relic'), "Wanderer's_Journal-Cliffs": HKItemData(advancement=False, id=16777360, type='Relic'), "Wanderer's_Journal-Crystal_Peak_Crawlers": HKItemData(advancement=False, id=16777365, type='Relic'), "Wanderer's_Journal-Fungal_Wastes_Thorns_Gauntlet": HKItemData(advancement=False, id=16777363, type='Relic'), "Wanderer's_Journal-Greenpath_Lower": HKItemData(advancement=False, id=16777362, type='Relic'), "Wanderer's_Journal-Greenpath_Stag": HKItemData(advancement=False, id=16777361, type='Relic'), "Wanderer's_Journal-King's_Station": HKItemData(advancement=False, id=16777367, type='Relic'), "Wanderer's_Journal-Kingdom's_Edge_Camp": HKItemData(advancement=False, id=16777372, type='Relic'), "Wanderer's_Journal-Kingdom's_Edge_Entrance": HKItemData(advancement=False, id=16777371, type='Relic'), "Wanderer's_Journal-Kingdom's_Edge_Requires_Dive": HKItemData(advancement=False, id=16777373, type='Relic'), "Wanderer's_Journal-Pleasure_House": HKItemData(advancement=False, id=16777368, type='Relic'), "Wanderer's_Journal-Resting_Grounds_Catacombs": HKItemData(advancement=False, id=16777366, type='Relic'), 'Waterways_Shaft': HKItemData(advancement=True, id=0, type='Event'), 'Wayward_Compass': HKItemData(advancement=False, id=16777242, type='Charm'), "Weaver's_Den": HKItemData(advancement=True, id=0, type='Event'), 'Weaversong': HKItemData(advancement=True, id=16777281, type='Charm'), 'Whispering_Root-Ancestral_Mound': HKItemData(advancement=True, id=16777416, type='Root'), 'Whispering_Root-City': HKItemData(advancement=True, id=16777411, type='Root'), 'Whispering_Root-Crossroads': HKItemData(advancement=True, id=16777403, type='Root'), 'Whispering_Root-Crystal_Peak': HKItemData(advancement=True, id=16777414, type='Root'), 'Whispering_Root-Deepnest': HKItemData(advancement=True, id=16777407, type='Root'), 'Whispering_Root-Greenpath': HKItemData(advancement=True, id=16777404, type='Root'), 'Whispering_Root-Hive': HKItemData(advancement=True, id=16777417, type='Root'), 'Whispering_Root-Howling_Cliffs': HKItemData(advancement=True, id=16777415, type='Root'), 'Whispering_Root-Kingdoms_Edge': HKItemData(advancement=True, id=16777409, type='Root'), 'Whispering_Root-Leg_Eater': HKItemData(advancement=True, id=16777405, type='Root'), 'Whispering_Root-Mantis_Village': HKItemData(advancement=True, id=16777406, type='Root'), 'Whispering_Root-Queens_Gardens': HKItemData(advancement=True, id=16777408, type='Root'), 'Whispering_Root-Resting_Grounds': HKItemData(advancement=True, id=16777412, type='Root'), 'Whispering_Root-Spirits_Glade': HKItemData(advancement=True, id=16777413, type='Root'), 'Whispering_Root-Waterways': HKItemData(advancement=True, id=16777410, type='Root'), 'World_Sense': HKItemData(advancement=False, id=16777220, type='Dreamer')} lookup_id_to_name:Dict[int, str] = {data.id: item_name for item_name, data in item_table.items() if data.type != 'Event'} lookup_type_to_names:Dict[str, Set[str]] = {} for item, item_data in item_table.items(): lookup_type_to_names.setdefault(item_data.type, set()).add(item)<file_sep># Risk of Rain 2 Setup Guide ## Install using r2modman ### Install r2modman Head on over to the r2modman page on Thunderstore and follow the installation instructions. [https://thunderstore.io/package/ebkr/r2modman/](https://thunderstore.io/package/ebkr/r2modman/) ### Install Archipelago Mod using r2modman You can install the Archipelago mod using r2modman in one of two ways. [https://thunderstore.io/package/ArchipelagoMW/Archipelago/](https://thunderstore.io/package/ArchipelagoMW/Archipelago/) One, you can use the Thunderstore website and click on the "Install with Mod Manager" link. You can also search for the "Archipelago" mod in the r2modman interface. The mod manager should automatically install all necessary dependencies as well. ### Running the Modded Game Click on the "Start modded" button in the top left in r2modman to start the game with the Archipelago mod installed. ## Joining an Archipelago Session There will be a menu button on the right side of the screen in the character select menu. Click it in order to bring up the in lobby mod config. From here you can expand the Archipelago sections and fill in the relevant info. Keep password blank if there is no password on the server. Simply check `Enable Archipelago?` and when you start the run it will automatically connect. ## Gameplay The Risk of Rain 2 players send checks by causing items to spawn in-game. That means opening chests or killing bosses, generally. An item check is only sent out after a certain number of items are picked up. This count is configurable in the player's YAML. ## YAML Settings An example YAML would look like this: ```yaml description: Ijwu-ror2 name: Ijwu game: Risk of Rain 2: 1 Risk of Rain 2: total_locations: 15 total_revivals: 4 start_with_revive: true item_pickup_step: 1 enable_lunar: true item_weights: default: 50 new: 0 uncommon: 0 legendary: 0 lunartic: 0 chaos: 0 no_scraps: 0 even: 0 scraps_only: 0 item_pool_presets: true # custom item weights green_scrap: 16 red_scrap: 4 yellow_scrap: 1 white_scrap: 32 common_item: 64 uncommon_item: 32 legendary_item: 8 boss_item: 4 lunar_item: 16 equipment: 32 ``` | Name | Description | Allowed values | | ---- | ----------- | -------------- | | total_locations | The total number of location checks that will be attributed to the Risk of Rain player. This option is ALSO the total number of items in the item pool for the Risk of Rain player. | 10 - 100 | | total_revivals | The total number of items in the Risk of Rain player's item pool (items other players pick up for them) replaced with `Dio's Best Friend`. | 0 - 5 | | start_with_revive | Starts the player off with a `Dio's Best Friend`. Functionally equivalent to putting a `Dio's Best Friend` in your `starting_inventory`. | true/false | | item_pickup_step | The number of item pickups which you are allowed to claim before they become an Archipelago location check. | 0 - 5 | | enable_lunar | Allows for lunar items to be shuffled into the item pool on behalf of the Risk of Rain player. | true/false | | item_weights | Each option here is a preset item weight that can be used to customize your generate item pool with certain settings. | default, new, uncommon, legendary, lunartic, chaos, no_scraps, even, scraps_only | | item_pool_presets | A simple toggle to determine whether the item_weight presets are used or the custom item pool as defined below | true/false | | custom item weights | Each defined item here is a single item in the pool that will have a weight against the other items when the item pool gets generated. These values can be modified to adjust how frequently certain items appear | 0-100| Using the example YAML above: the Risk of Rain 2 player will have 15 total items which they can pick up for other players. (total_locations = 15) They will have 15 items waiting for them in the item pool which will be distributed out to the multiworld. (total_locations = 15) They will complete a location check every second item. (item_pickup_step = 1) They will have 4 of the items which other players can grant them replaced with `Dio's Best Friend`. (total_revivals = 4) The player will also start with a `Dio's Best Friend`. (start_with_revive = true) The player will have lunar items shuffled into the item pool on their behalf. (enable_lunar = true) The player will have the default preset generated item pool with the custom item weights being ignored. (item_weights: default and item_pool_presets: true) <file_sep>import typing from Options import Option, DefaultOnToggle, Toggle, Choice, Range, OptionList from .ColorSFXOptions import * class Logic(Choice): """Set the logic used for the generator.""" displayname = "Logic Rules" option_glitchless = 0 option_glitched = 1 option_no_logic = 2 class NightTokens(Toggle): """Nighttime skulltulas will logically require Sun's Song.""" displayname = "Nighttime Skulltulas Expect Sun's Song" class Forest(Choice): """Set the state of Kokiri Forest and the path to Deku Tree.""" displayname = "Forest" option_open = 0 option_closed_deku = 1 option_closed = 2 alias_open_forest = 0 alias_closed_forest = 2 class Gate(Choice): """Set the state of the Kakariko Village gate.""" displayname = "Kakariko Gate" option_open = 0 option_zelda = 1 option_closed = 2 class DoorOfTime(DefaultOnToggle): """Open the Door of Time by default, without the Song of Time.""" displayname = "Open Door of Time" class Fountain(Choice): """Set the state of King Zora, blocking the way to Zora's Fountain.""" displayname = "Zora's Fountain" option_open = 0 option_adult = 1 option_closed = 2 default = 2 class Fortress(Choice): """Set the requirements for access to Gerudo Fortress.""" displayname = "Gerudo Fortress" option_normal = 0 option_fast = 1 option_open = 2 default = 1 class Bridge(Choice): """Set the requirements for the Rainbow Bridge.""" displayname = "Rainbow Bridge Requirement" option_open = 0 option_vanilla = 1 option_stones = 2 option_medallions = 3 option_dungeons = 4 option_tokens = 5 default = 3 class Trials(Range): """Set the number of required trials in Ganon's Castle.""" displayname = "Ganon's Trials Count" range_start = 0 range_end = 6 open_options: typing.Dict[str, type(Option)] = { "open_forest": Forest, "open_kakariko": Gate, "open_door_of_time": DoorOfTime, "zora_fountain": Fountain, "gerudo_fortress": Fortress, "bridge": Bridge, "trials": Trials, } class StartingAge(Choice): """Choose which age Link will start as.""" displayname = "Starting Age" option_child = 0 option_adult = 1 # TODO: document and name ER options class InteriorEntrances(Choice): option_off = 0 option_simple = 1 option_all = 2 alias_false = 0 class TriforceHunt(Toggle): """Gather pieces of the Triforce scattered around the world to complete the game.""" displayname = "Triforce Hunt" class TriforceGoal(Range): """Number of Triforce pieces required to complete the game.""" displayname = "Required Triforce Pieces" range_start = 1 range_end = 100 default = 20 class ExtraTriforces(Range): """Percentage of additional Triforce pieces in the pool, separate from the item pool setting.""" displayname = "Percentage of Extra Triforce Pieces" range_start = 0 range_end = 100 default = 50 class LogicalChus(Toggle): """Bombchus are properly considered in logic. The first found pack will have 20 chus; Kokiri Shop and Bazaar sell refills; bombchus open Bombchu Bowling.""" displayname = "Bombchus Considered in Logic" class MQDungeons(Range): """Number of MQ dungeons. The dungeons to replace are randomly selected.""" displayname = "Number of MQ Dungeons" range_start = 0 range_end = 12 default = 0 world_options: typing.Dict[str, type(Option)] = { "starting_age": StartingAge, # "shuffle_interior_entrances": InteriorEntrances, # "shuffle_grotto_entrances": Toggle, # "shuffle_dungeon_entrances": Toggle, # "shuffle_overworld_entrances": Toggle, # "owl_drops": Toggle, # "warp_songs": Toggle, # "spawn_positions": Toggle, "triforce_hunt": TriforceHunt, "triforce_goal": TriforceGoal, "extra_triforce_percentage": ExtraTriforces, "bombchus_in_logic": LogicalChus, "mq_dungeons": MQDungeons, } class LacsCondition(Choice): """Set the requirements for the Light Arrow Cutscene in the Temple of Time.""" displayname = "Light Arrow Cutscene Requirement" option_vanilla = 0 option_stones = 1 option_medallions = 2 option_dungeons = 3 option_tokens = 4 class LacsStones(Range): """Set the number of Spiritual Stones required for LACS.""" displayname = "Spiritual Stones Required for LACS" range_start = 0 range_end = 3 default = 3 class LacsMedallions(Range): """Set the number of medallions required for LACS.""" displayname = "Medallions Required for LACS" range_start = 0 range_end = 6 default = 6 class LacsRewards(Range): """Set the number of dungeon rewards required for LACS.""" displayname = "Dungeon Rewards Required for LACS" range_start = 0 range_end = 9 default = 9 class LacsTokens(Range): """Set the number of Gold Skulltula Tokens required for LACS.""" displayname = "Tokens Required for LACS" range_start = 0 range_end = 100 default = 40 lacs_options: typing.Dict[str, type(Option)] = { "lacs_condition": LacsCondition, "lacs_stones": LacsStones, "lacs_medallions": LacsMedallions, "lacs_rewards": LacsRewards, "lacs_tokens": LacsTokens, } class BridgeStones(Range): """Set the number of Spiritual Stones required for the rainbow bridge.""" displayname = "Spiritual Stones Required for Bridge" range_start = 0 range_end = 3 default = 3 class BridgeMedallions(Range): """Set the number of medallions required for the rainbow bridge.""" displayname = "Medallions Required for Bridge" range_start = 0 range_end = 6 default = 6 class BridgeRewards(Range): """Set the number of dungeon rewards required for the rainbow bridge.""" displayname = "Dungeon Rewards Required for Bridge" range_start = 0 range_end = 9 default = 9 class BridgeTokens(Range): """Set the number of Gold Skulltula Tokens required for the rainbow bridge.""" displayname = "Tokens Required for Bridge" range_start = 0 range_end = 100 default = 40 bridge_options: typing.Dict[str, type(Option)] = { "bridge_stones": BridgeStones, "bridge_medallions": BridgeMedallions, "bridge_rewards": BridgeRewards, "bridge_tokens": BridgeTokens, } class SongShuffle(Choice): """Set where songs can appear.""" displayname = "Shuffle Songs" option_song = 0 option_dungeon = 1 option_any = 2 class ShopShuffle(Choice): """Randomizes shop contents. "fixed_number" randomizes a specific number of items per shop; "random_number" randomizes the value for each shop. """ displayname = "Shopsanity" option_off = 0 option_fixed_number = 1 option_random_number = 2 alias_false = 0 class ShopSlots(Range): """Number of items per shop to be randomized into the main itempool. Only active if Shopsanity is set to "fixed_number." """ displayname = "Shuffled Shop Slots" range_start = 0 range_end = 4 class TokenShuffle(Choice): """Token rewards from Gold Skulltulas are shuffled into the pool.""" displayname = "Tokensanity" option_off = 0 option_dungeons = 1 option_overworld = 2 option_all = 3 alias_false = 0 class ScrubShuffle(Choice): """Shuffle the items sold by Business Scrubs, and set the prices.""" displayname = "Scrub Shuffle" option_off = 0 option_low = 1 option_regular = 2 option_random_prices = 3 alias_false = 0 alias_affordable = 1 alias_expensive = 2 class ShuffleCows(Toggle): """Cows give items when Epona's Song is played.""" displayname = "Shuffle Cows" class ShuffleSword(Toggle): """Shuffle Kokiri Sword into the item pool.""" displayname = "Shuffle Kokiri Sword" class ShuffleOcarinas(Toggle): """Shuffle the Fairy Ocarina and Ocarina of Time into the item pool.""" displayname = "Shuffle Ocarinas" class ShuffleEgg(Toggle): """Shuffle the Weird Egg from Malon at Hyrule Castle.""" displayname = "Shuffle Weird Egg" class ShuffleCard(Toggle): """Shuffle the Gerudo Membership Card into the item pool.""" displayname = "Shuffle Gerudo Card" class ShuffleBeans(Toggle): """Adds a pack of 10 beans to the item pool and changes the bean salesman to sell one item for 60 rupees.""" displayname = "Shuffle Magic Beans" class ShuffleMedigoronCarpet(Toggle): """Shuffle the items sold by Medigoron and the Haunted Wasteland Carpet Salesman.""" displayname = "Shuffle Medigoron & Carpet Salesman" shuffle_options: typing.Dict[str, type(Option)] = { "shuffle_song_items": SongShuffle, "shopsanity": ShopShuffle, "shop_slots": ShopSlots, "tokensanity": TokenShuffle, "shuffle_scrubs": ScrubShuffle, "shuffle_cows": ShuffleCows, "shuffle_kokiri_sword": ShuffleSword, "shuffle_ocarinas": ShuffleOcarinas, "shuffle_weird_egg": ShuffleEgg, "shuffle_gerudo_card": ShuffleCard, "shuffle_beans": ShuffleBeans, "shuffle_medigoron_carpet_salesman": ShuffleMedigoronCarpet, } class ShuffleMapCompass(Choice): """Control where to shuffle dungeon maps and compasses.""" displayname = "Maps & Compasses" option_remove = 0 option_startwith = 1 option_vanilla = 2 option_dungeon = 3 option_overworld = 4 option_any_dungeon = 5 option_keysanity = 6 default = 1 alias_anywhere = 6 class ShuffleKeys(Choice): """Control where to shuffle dungeon small keys.""" displayname = "Small Keys" option_remove = 0 option_vanilla = 2 option_dungeon = 3 option_overworld = 4 option_any_dungeon = 5 option_keysanity = 6 default = 3 alias_keysy = 0 alias_anywhere = 6 class ShuffleGerudoKeys(Choice): """Control where to shuffle the Gerudo Fortress small keys.""" displayname = "Gerudo Fortress Keys" option_vanilla = 0 option_overworld = 1 option_any_dungeon = 2 option_keysanity = 3 alias_anywhere = 3 class ShuffleBossKeys(Choice): """Control where to shuffle boss keys, except the Ganon's Castle Boss Key.""" displayname = "Boss Keys" option_remove = 0 option_vanilla = 2 option_dungeon = 3 option_overworld = 4 option_any_dungeon = 5 option_keysanity = 6 default = 3 alias_keysy = 0 alias_anywhere = 6 class ShuffleGanonBK(Choice): """Control where to shuffle the Ganon's Castle Boss Key.""" displayname = "Ganon's Boss Key" option_remove = 0 option_vanilla = 2 option_dungeon = 3 option_overworld = 4 option_any_dungeon = 5 option_keysanity = 6 option_on_lacs = 7 default = 0 alias_keysy = 0 alias_anywhere = 6 class EnhanceMC(Toggle): """Map tells if a dungeon is vanilla or MQ. Compass tells what the dungeon reward is.""" displayname = "Maps and Compasses Give Information" dungeon_items_options: typing.Dict[str, type(Option)] = { "shuffle_mapcompass": ShuffleMapCompass, "shuffle_smallkeys": ShuffleKeys, "shuffle_fortresskeys": ShuffleGerudoKeys, "shuffle_bosskeys": ShuffleBossKeys, "shuffle_ganon_bosskey": ShuffleGanonBK, "enhance_map_compass": EnhanceMC, } class SkipChildZelda(Toggle): """Game starts with Zelda's Letter, the item at Zelda's Lullaby, and the relevant events already completed.""" displayname = "Skip Child Zelda" class SkipEscape(DefaultOnToggle): """Skips the tower collapse sequence between the Ganondorf and Ganon fights.""" displayname = "Skip Tower Escape Sequence" class SkipStealth(DefaultOnToggle): """The crawlspace into Hyrule Castle skips straight to Zelda.""" displayname = "Skip Child Stealth" class SkipEponaRace(DefaultOnToggle): """Epona can always be summoned with Epona's Song.""" displayname = "Skip Epona Race" class SkipMinigamePhases(DefaultOnToggle): """Dampe Race and Horseback Archery give both rewards if the second condition is met on the first attempt.""" displayname = "Skip Some Minigame Phases" class CompleteMaskQuest(Toggle): """All masks are immediately available to borrow from the Happy Mask Shop.""" displayname = "Complete Mask Quest" class UsefulCutscenes(Toggle): """Reenables the Poe cutscene in Forest Temple, Darunia in Fire Temple, and Twinrova introduction. Mostly useful for glitched.""" displayname = "Enable Useful Cutscenes" class FastChests(DefaultOnToggle): """All chest animations are fast. If disabled, major items have a slow animation.""" displayname = "Fast Chest Cutscenes" class FreeScarecrow(Toggle): """Pulling out the ocarina near a scarecrow spot spawns Pierre without needing the song.""" displayname = "Free Scarecrow's Song" class FastBunny(Toggle): """Bunny Hood lets you move 1.5x faster like in Majora's Mask.""" displayname = "Fast Bunny Hood" class ChickenCount(Range): """Controls the number of Cuccos for Anju to give an item as child.""" displayname = "Cucco Count" range_start = 0 range_end = 7 default = 7 timesavers_options: typing.Dict[str, type(Option)] = { "skip_child_zelda": SkipChildZelda, "no_escape_sequence": SkipEscape, "no_guard_stealth": SkipStealth, "no_epona_race": SkipEponaRace, "skip_some_minigame_phases": SkipMinigamePhases, "complete_mask_quest": CompleteMaskQuest, "useful_cutscenes": UsefulCutscenes, "fast_chests": FastChests, "free_scarecrow": FreeScarecrow, "fast_bunny_hood": FastBunny, "chicken_count": ChickenCount, # "big_poe_count": make_range(1, 10, 1), } class CSMC(Toggle): """Changes chests containing progression into large chests, and nonprogression into small chests.""" displayname = "Chest Size Matches Contents" class Hints(Choice): """Gossip Stones can give hints about item locations.""" displayname = "<NAME>" option_none = 0 option_mask = 1 option_agony = 2 option_always = 3 default = 3 alias_false = 0 class HintDistribution(Choice): """Choose the hint distribution to use. Affects the frequency of strong hints, which items are always hinted, etc.""" displayname = "Hint Distribution" option_balanced = 0 option_ddr = 1 option_league = 2 option_mw2 = 3 option_scrubs = 4 option_strong = 5 option_tournament = 6 option_useless = 7 option_very_strong = 8 option_async = 9 class TextShuffle(Choice): """Randomizes text in the game for comedic effect.""" displayname = "Text Shuffle" option_none = 0 option_except_hints = 1 option_complete = 2 alias_false = 0 class DamageMultiplier(Choice): """Controls the amount of damage Link takes.""" displayname = "Damage Multiplier" option_half = 0 option_normal = 1 option_double = 2 option_quadruple = 3 option_ohko = 4 default = 1 class HeroMode(Toggle): """Hearts will not drop from enemies or objects.""" displayname = "Hero Mode" class StartingToD(Choice): """Change the starting time of day.""" displayname = "Starting Time of Day" option_default = 0 option_sunrise = 1 option_morning = 2 option_noon = 3 option_afternoon = 4 option_sunset = 5 option_evening = 6 option_midnight = 7 option_witching_hour = 8 class ConsumableStart(Toggle): """Start the game with full Deku Sticks and Deku Nuts.""" displayname = "Start with Consumables" class RupeeStart(Toggle): """Start with a full wallet. Wallet upgrades will also fill your wallet.""" displayname = "Start with Rupees" misc_options: typing.Dict[str, type(Option)] = { "correct_chest_sizes": CSMC, "hints": Hints, "hint_dist": HintDistribution, "text_shuffle": TextShuffle, "damage_multiplier": DamageMultiplier, "no_collectible_hearts": HeroMode, "starting_tod": StartingToD, "start_with_consumables": ConsumableStart, "start_with_rupees": RupeeStart, } class ItemPoolValue(Choice): """Changes the number of items available in the game.""" displayname = "Item Pool" option_plentiful = 0 option_balanced = 1 option_scarce = 2 option_minimal = 3 default = 1 class IceTraps(Choice): """Adds ice traps to the item pool.""" displayname = "Ice Traps" option_off = 0 option_normal = 1 option_on = 2 option_mayhem = 3 option_onslaught = 4 default = 1 alias_false = 0 alias_true = 2 alias_extra = 2 class IceTrapVisual(Choice): """Changes the appearance of ice traps as freestanding items.""" displayname = "Ice Trap Appearance" option_major_only = 0 option_junk_only = 1 option_anything = 2 class AdultTradeItem(Choice): option_pocket_egg = 0 option_pocket_cucco = 1 option_cojiro = 2 option_odd_mushroom = 3 option_poachers_saw = 4 option_broken_sword = 5 option_prescription = 6 option_eyeball_frog = 7 option_eyedrops = 8 option_claim_check = 9 class EarlyTradeItem(AdultTradeItem): """Earliest item that can appear in the adult trade sequence.""" displayname = "Adult Trade Sequence Earliest Item" default = 6 class LateTradeItem(AdultTradeItem): """Latest item that can appear in the adult trade sequence.""" displayname = "Adult Trade Sequence Latest Item" default = 9 itempool_options: typing.Dict[str, type(Option)] = { "item_pool_value": ItemPoolValue, "junk_ice_traps": IceTraps, "ice_trap_appearance": IceTrapVisual, "logic_earliest_adult_trade": EarlyTradeItem, "logic_latest_adult_trade": LateTradeItem, } # Start of cosmetic options class Targeting(Choice): """Default targeting option.""" displayname = "Default Targeting Option" option_hold = 0 option_switch = 1 class DisplayDpad(DefaultOnToggle): """Show dpad icon on HUD for quick actions (ocarina, hover boots, iron boots).""" displayname = "Display D-Pad HUD" class CorrectColors(DefaultOnToggle): """Makes in-game models match their HUD element colors.""" displayname = "Item Model Colors Match Cosmetics" class Music(Choice): option_normal = 0 option_off = 1 option_randomized = 2 alias_false = 1 class BackgroundMusic(Music): """Randomize or disable background music.""" displayname = "Background Music" class Fanfares(Music): """Randomize or disable item fanfares.""" displayname = "Fanfares" class OcarinaFanfares(Toggle): """Enable ocarina songs as fanfares. These are longer than usual fanfares. Does nothing without fanfares randomized.""" displayname = "Ocarina Songs as Fanfares" class SwordTrailDuration(Range): """Set the duration for sword trails.""" displayname = "Sword Trail Duration" range_start = 4 range_end = 20 default = 4 cosmetic_options: typing.Dict[str, type(Option)] = { "default_targeting": Targeting, "display_dpad": DisplayDpad, "correct_model_colors": CorrectColors, "background_music": BackgroundMusic, "fanfares": Fanfares, "ocarina_fanfares": OcarinaFanfares, "kokiri_color": kokiri_color, "goron_color": goron_color, "zora_color": zora_color, "silver_gauntlets_color": silver_gauntlets_color, "golden_gauntlets_color": golden_gauntlets_color, "mirror_shield_frame_color": mirror_shield_frame_color, "navi_color_default_inner": navi_color_default_inner, "navi_color_default_outer": navi_color_default_outer, "navi_color_enemy_inner": navi_color_enemy_inner, "navi_color_enemy_outer": navi_color_enemy_outer, "navi_color_npc_inner": navi_color_npc_inner, "navi_color_npc_outer": navi_color_npc_outer, "navi_color_prop_inner": navi_color_prop_inner, "navi_color_prop_outer": navi_color_prop_outer, "sword_trail_duration": SwordTrailDuration, "sword_trail_color_inner": sword_trail_color_inner, "sword_trail_color_outer": sword_trail_color_outer, "bombchu_trail_color_inner": bombchu_trail_color_inner, "bombchu_trail_color_outer": bombchu_trail_color_outer, "boomerang_trail_color_inner": boomerang_trail_color_inner, "boomerang_trail_color_outer": boomerang_trail_color_outer, "heart_color": heart_color, "magic_color": magic_color, "a_button_color": a_button_color, "b_button_color": b_button_color, "c_button_color": c_button_color, "start_button_color": start_button_color, } class SfxOcarina(Choice): """Change the sound of the ocarina.""" displayname = "Ocarina Instrument" option_ocarina = 1 option_malon = 2 option_whistle = 3 option_harp = 4 option_grind_organ = 5 option_flute = 6 default = 1 sfx_options: typing.Dict[str, type(Option)] = { "sfx_navi_overworld": sfx_navi_overworld, "sfx_navi_enemy": sfx_navi_enemy, "sfx_low_hp": sfx_low_hp, "sfx_menu_cursor": sfx_menu_cursor, "sfx_menu_select": sfx_menu_select, "sfx_nightfall": sfx_nightfall, "sfx_horse_neigh": sfx_horse_neigh, "sfx_hover_boots": sfx_hover_boots, "sfx_ocarina": SfxOcarina, } # All options assembled into a single dict oot_options: typing.Dict[str, type(Option)] = { "logic_rules": Logic, "logic_no_night_tokens_without_suns_song": NightTokens, **open_options, **world_options, **bridge_options, **dungeon_items_options, **lacs_options, **shuffle_options, **timesavers_options, **misc_options, **itempool_options, **cosmetic_options, **sfx_options, "logic_tricks": OptionList, } <file_sep>from worlds.hk import HKWorld from BaseClasses import MultiWorld from worlds import AutoWorld from worlds.hk.Options import hollow_knight_randomize_options, hollow_knight_skip_options from test.TestBase import TestBase class TestVanilla(TestBase): def setUp(self): self.world = MultiWorld(1) self.world.game[1] = "Hollow Knight" self.world.worlds[1] = HKWorld(self.world, 1) for hk_option in hollow_knight_randomize_options: setattr(self.world, hk_option, {1: True}) for hk_option, option in hollow_knight_skip_options.items(): setattr(self.world, hk_option, {1: option.default}) AutoWorld.call_single(self.world, "create_regions", 1) AutoWorld.call_single(self.world, "generate_basic", 1) AutoWorld.call_single(self.world, "set_rules", 1)<file_sep>from __future__ import annotations import typing import random class AssembleOptions(type): def __new__(mcs, name, bases, attrs): options = attrs["options"] = {} name_lookup = attrs["name_lookup"] = {} # merge parent class options for base in bases: if getattr(base, "options", None): options.update(base.options) name_lookup.update(base.name_lookup) new_options = {name[7:].lower(): option_id for name, option_id in attrs.items() if name.startswith("option_")} if "random" in new_options: raise Exception("Choice option 'random' cannot be manually assigned.") attrs["name_lookup"].update({option_id: name for name, option_id in new_options.items()}) options.update(new_options) # apply aliases, without name_lookup options.update({name[6:].lower(): option_id for name, option_id in attrs.items() if name.startswith("alias_")}) # auto-validate schema on __init__ if "schema" in attrs.keys(): def validate_decorator(func): def validate(self, *args, **kwargs): func(self, *args, **kwargs) self.value = self.schema.validate(self.value) return validate attrs["__init__"] = validate_decorator(attrs["__init__"]) return super(AssembleOptions, mcs).__new__(mcs, name, bases, attrs) class Option(metaclass=AssembleOptions): value: int name_lookup: typing.Dict[int, str] default = 0 # convert option_name_long into Name Long as displayname, otherwise name_long is the result. # Handled in get_option_name() autodisplayname = False # can be weighted between selections supports_weighting = True def __repr__(self) -> str: return f"{self.__class__.__name__}({self.get_current_option_name()})" def __hash__(self): return hash(self.value) @property def current_key(self) -> str: return self.name_lookup[self.value] def get_current_option_name(self) -> str: """For display purposes.""" return self.get_option_name(self.value) @classmethod def get_option_name(cls, value: typing.Any) -> str: if cls.autodisplayname: return cls.name_lookup[value].replace("_", " ").title() else: return cls.name_lookup[value] def __int__(self) -> int: return self.value def __bool__(self) -> bool: return bool(self.value) @classmethod def from_any(cls, data: typing.Any): raise NotImplementedError class Toggle(Option): option_false = 0 option_true = 1 default = 0 def __init__(self, value: int): assert value == 0 or value == 1 self.value = value @classmethod def from_text(cls, text: str) -> Toggle: if text.lower() in {"off", "0", "false", "none", "null", "no"}: return cls(0) else: return cls(1) @classmethod def from_any(cls, data: typing.Any): if type(data) == str: return cls.from_text(data) else: return cls(data) def __eq__(self, other): if isinstance(other, Toggle): return self.value == other.value else: return self.value == other def __gt__(self, other): if isinstance(other, Toggle): return self.value > other.value else: return self.value > other def __bool__(self): return bool(self.value) def __int__(self): return int(self.value) @classmethod def get_option_name(cls, value): return ["No", "Yes"][int(value)] class DefaultOnToggle(Toggle): default = 1 class Choice(Option): autodisplayname = True def __init__(self, value: int): self.value: int = value @classmethod def from_text(cls, text: str) -> Choice: text = text.lower() if text == "random": return cls(random.choice(list(cls.name_lookup))) for optionname, value in cls.options.items(): if optionname == text: return cls(value) raise KeyError( f'Could not find option "{text}" for "{cls.__name__}", ' f'known options are {", ".join(f"{option}" for option in cls.name_lookup.values())}') @classmethod def from_any(cls, data: typing.Any) -> Choice: if type(data) == int and data in cls.options.values(): return cls(data) return cls.from_text(str(data)) def __eq__(self, other): if isinstance(other, self.__class__): return other.value == self.value elif isinstance(other, str): assert other in self.options return other == self.current_key elif isinstance(other, int): assert other in self.name_lookup return other == self.value elif isinstance(other, bool): return other == bool(self.value) else: raise TypeError(f"Can't compare {self.__class__.__name__} with {other.__class__.__name__}") def __ne__(self, other): if isinstance(other, self.__class__): return other.value != self.value elif isinstance(other, str): assert other in self.options return other != self.current_key elif isinstance(other, int): assert other in self.name_lookup return other != self.value elif isinstance(other, bool): return other != bool(self.value) elif other is None: return False else: raise TypeError(f"Can't compare {self.__class__.__name__} with {other.__class__.__name__}") class Range(Option, int): range_start = 0 range_end = 1 def __init__(self, value: int): if value < self.range_start: raise Exception(f"{value} is lower than minimum {self.range_start} for option {self.__class__.__name__}") elif value > self.range_end: raise Exception(f"{value} is higher than maximum {self.range_end} for option {self.__class__.__name__}") self.value = value @classmethod def from_text(cls, text: str) -> Range: text = text.lower() if text.startswith("random"): if text == "random-low": return cls(int(round(random.triangular(cls.range_start, cls.range_end, cls.range_start), 0))) elif text == "random-high": return cls(int(round(random.triangular(cls.range_start, cls.range_end, cls.range_end), 0))) elif text == "random-middle": return cls(int(round(random.triangular(cls.range_start, cls.range_end), 0))) else: return cls(random.randint(cls.range_start, cls.range_end)) return cls(int(text)) @classmethod def from_any(cls, data: typing.Any) -> Range: if type(data) == int: return cls(data) return cls.from_text(str(data)) def get_option_name(self, value): return str(value) def __str__(self): return str(self.value) class OptionNameSet(Option): default = frozenset() def __init__(self, value: typing.Set[str]): self.value: typing.Set[str] = value @classmethod def from_text(cls, text: str) -> OptionNameSet: return cls({option.strip() for option in text.split(",")}) @classmethod def from_any(cls, data: typing.Any) -> OptionNameSet: if type(data) == set: return cls(data) return cls.from_text(str(data)) class OptionDict(Option): default = {} supports_weighting = False value: typing.Dict[str, typing.Any] def __init__(self, value: typing.Dict[str, typing.Any]): self.value = value @classmethod def from_any(cls, data: typing.Dict[str, typing.Any]) -> OptionDict: if type(data) == dict: return cls(data) else: raise NotImplementedError(f"Cannot Convert from non-dictionary, got {type(data)}") def get_option_name(self, value): return ", ".join(f"{key}: {v}" for key, v in value.items()) def __contains__(self, item): return item in self.value class ItemDict(OptionDict): # implemented by Generate verify_item_name = True def __init__(self, value: typing.Dict[str, int]): if any(item_count < 1 for item_count in value.values()): raise Exception("Cannot have non-positive item counts.") super(ItemDict, self).__init__(value) class OptionList(Option): default = [] supports_weighting = False value: list def __init__(self, value: typing.List[str, typing.Any]): self.value = value super(OptionList, self).__init__() @classmethod def from_text(cls, text: str): return cls([option.strip() for option in text.split(",")]) @classmethod def from_any(cls, data: typing.Any): if type(data) == list: return cls(data) return cls.from_text(str(data)) def get_option_name(self, value): return ", ".join(value) def __contains__(self, item): return item in self.value class OptionSet(Option): default = frozenset() supports_weighting = False value: set def __init__(self, value: typing.Union[typing.Set[str, typing.Any], typing.List[str, typing.Any]]): self.value = set(value) super(OptionSet, self).__init__() @classmethod def from_text(cls, text: str): return cls([option.strip() for option in text.split(",")]) @classmethod def from_any(cls, data: typing.Any): if type(data) == list: return cls(data) elif type(data) == set: return cls(data) return cls.from_text(str(data)) def get_option_name(self, value): return ", ".join(value) def __contains__(self, item): return item in self.value local_objective = Toggle # local triforce pieces, local dungeon prizes etc. class Accessibility(Choice): """Set rules for reachability of your items/locations. Locations: ensure everything can be reached and acquired. Items: ensure all logically relevant items can be acquired. Minimal: ensure what is needed to reach your goal can be acquired.""" option_locations = 0 option_items = 1 option_minimal = 2 alias_none = 2 default = 1 class ProgressionBalancing(DefaultOnToggle): """A system that moves progression earlier, to try and prevent the player from getting stuck and bored early.""" common_options = { "progression_balancing": ProgressionBalancing, "accessibility": Accessibility } class ItemSet(OptionSet): # implemented by Generate verify_item_name = True class LocalItems(ItemSet): """Forces these items to be in their native world.""" displayname = "Local Items" class NonLocalItems(ItemSet): """Forces these items to be outside their native world.""" displayname = "Not Local Items" class StartInventory(ItemDict): """Start with these items.""" verify_item_name = True displayname = "Start Inventory" class StartHints(ItemSet): """Start with these item's locations prefilled into the !hint command.""" displayname = "Start Hints" class StartLocationHints(OptionSet): displayname = "Start Location Hints" class ExcludeLocations(OptionSet): """Prevent these locations from having an important item""" displayname = "Excluded Locations" verify_location_name = True class DeathLink(Toggle): """When you die, everyone dies. Of course the reverse is true too.""" displayname = "Death Link" per_game_common_options = { "local_items": LocalItems, "non_local_items": NonLocalItems, "start_inventory": StartInventory, "start_hints": StartHints, "start_location_hints": StartLocationHints, "exclude_locations": OptionSet } if __name__ == "__main__": from worlds.alttp.Options import Logic import argparse map_shuffle = Toggle compass_shuffle = Toggle keyshuffle = Toggle bigkey_shuffle = Toggle hints = Toggle test = argparse.Namespace() test.logic = Logic.from_text("no_logic") test.map_shuffle = map_shuffle.from_text("ON") test.hints = hints.from_text('OFF') try: test.logic = Logic.from_text("overworld_glitches_typo") except KeyError as e: print(e) try: test.logic_owg = Logic.from_text("owg") except KeyError as e: print(e) if test.map_shuffle: print("map_shuffle is on") print(f"Hints are {bool(test.hints)}") print(test) <file_sep>import os import multiprocessing import logging import ModuleUpdate ModuleUpdate.requirements_files.add(os.path.join("WebHostLib", "requirements.txt")) ModuleUpdate.update() # in case app gets imported by something like gunicorn import Utils Utils.local_path.cached_path = os.path.dirname(__file__) from WebHostLib import app as raw_app from waitress import serve from WebHostLib.models import db from WebHostLib.autolauncher import autohost from WebHostLib.lttpsprites import update_sprites_lttp from WebHostLib.options import create as create_options_files configpath = os.path.abspath("config.yaml") def get_app(): app = raw_app if os.path.exists(configpath): import yaml app.config.from_file(configpath, yaml.safe_load) logging.info(f"Updated config from {configpath}") db.bind(**app.config["PONY"]) db.generate_mapping(create_tables=True) return app if __name__ == "__main__": multiprocessing.freeze_support() multiprocessing.set_start_method('spawn') logging.basicConfig(format='[%(asctime)s] %(message)s', level=logging.INFO) try: update_sprites_lttp() except Exception as e: logging.exception(e) logging.warning("Could not update LttP sprites.") app = get_app() create_options_files() if app.config["SELFLAUNCH"]: autohost(app.config) if app.config["SELFHOST"]: # using WSGI, you just want to run get_app() if app.config["DEBUG"]: autohost(app.config) app.run(debug=True, port=app.config["PORT"]) else: serve(app, port=app.config["PORT"], threads=app.config["WAITRESS_THREADS"]) <file_sep>from BaseClasses import MultiWorld from ..AutoWorld import LogicMixin from .Options import is_option_enabled class TimespinnerLogic(LogicMixin): def _timespinner_has_timestop(self, world: MultiWorld, player: int) -> bool: return self.has_any(['Timespinner Wheel', 'Succubus Hairpin', 'Lightwall', 'Celestial Sash'], player) def _timespinner_has_doublejump(self, world: MultiWorld, player: int) -> bool: return self.has_any(['Succubus Hairpin', 'Lightwall', 'Celestial Sash'], player) def _timespinner_has_forwarddash_doublejump(self, world: MultiWorld, player: int) -> bool: return self._timespinner_has_upwarddash(world, player) or (self.has('Talaria Attachment', player) and self._timespinner_has_doublejump(world, player)) def _timespinner_has_doublejump_of_npc(self, world: MultiWorld, player: int) -> bool: return self._timespinner_has_upwarddash(world, player) or (self.has('Timespinner Wheel', player) and self._timespinner_has_doublejump(world, player)) def _timespinner_has_multiple_small_jumps_of_npc(self, world: MultiWorld, player: int) -> bool: return self.has('Timespinner Wheel', player) or self._timespinner_has_upwarddash(world, player) def _timespinner_has_upwarddash(self, world: MultiWorld, player: int) -> bool: return self.has_any(['Lightwall', 'Celestial Sash'], player) def _timespinner_has_fire(self, world: MultiWorld, player: int) -> bool: return self.has_any(['Fire Orb', 'Infernal Flames', 'Pyro Ring', 'Djinn Inferno'], player) def _timespinner_has_pink(self, world: MultiWorld, player: int) -> bool: return self.has_any(['Plasma Orb', 'Plasma Geyser', 'Royal Ring'], player) def _timespinner_has_keycard_A(self, world: MultiWorld, player: int) -> bool: return self.has('Security Keycard A', player) def _timespinner_has_keycard_B(self, world: MultiWorld, player: int) -> bool: if is_option_enabled(world, player, "SpecificKeycards"): return self.has('Security Keycard B', player) else: return self.has_any(['Security Keycard A', 'Security Keycard B'], player) def _timespinner_has_keycard_C(self, world: MultiWorld, player: int) -> bool: if is_option_enabled(world, player, "SpecificKeycards"): return self.has('Security Keycard C', player) else: return self.has_any(['Security Keycard A', 'Security Keycard B', 'Security Keycard C'], player) def _timespinner_has_keycard_D(self, world: MultiWorld, player: int) -> bool: if is_option_enabled(world, player, "SpecificKeycards"): return self.has('Security Keycard D', player) else: return self.has_any(['Security Keycard A', 'Security Keycard B', 'Security Keycard C', 'Security Keycard D'], player) def _timespinner_can_break_walls(self, world: MultiWorld, player: int) -> bool: if is_option_enabled(world, player, "FacebookMode"): return self.has('Oculus Ring', player) else: return True def _timespinner_can_kill_all_3_bosses(self, world: MultiWorld, player: int) -> bool: return self.has_all(['Killed Maw', 'Killed Twins', 'Killed Aelana'], player)<file_sep>from typing import List, Dict, Tuple, Optional, Callable from BaseClasses import MultiWorld, Region, Entrance, Location, RegionType from .Options import is_option_enabled from .Locations import LocationData def create_regions(world: MultiWorld, player: int, locations: Tuple[LocationData, ...], location_cache: List[Location], pyramid_keys_unlock: str): locations_per_region = get_locations_per_region(locations) world.regions += [ create_region(world, player, locations_per_region, location_cache, 'Menu'), create_region(world, player, locations_per_region, location_cache, 'Tutorial'), create_region(world, player, locations_per_region, location_cache, 'Lake desolation'), create_region(world, player, locations_per_region, location_cache, 'Upper lake desolation'), create_region(world, player, locations_per_region, location_cache, 'Lower lake desolation'), create_region(world, player, locations_per_region, location_cache, 'Library'), create_region(world, player, locations_per_region, location_cache, 'Library top'), create_region(world, player, locations_per_region, location_cache, 'Varndagroth tower left'), create_region(world, player, locations_per_region, location_cache, 'Varndagroth tower right (upper)'), create_region(world, player, locations_per_region, location_cache, 'Varndagroth tower right (lower)'), create_region(world, player, locations_per_region, location_cache, 'Varndagroth tower right (elevator)'), create_region(world, player, locations_per_region, location_cache, 'Sealed Caves (Sirens)'), create_region(world, player, locations_per_region, location_cache, 'Militairy Fortress'), create_region(world, player, locations_per_region, location_cache, 'The lab'), create_region(world, player, locations_per_region, location_cache, 'The lab (power off)'), create_region(world, player, locations_per_region, location_cache, 'The lab (upper)'), create_region(world, player, locations_per_region, location_cache, 'Emperors tower'), create_region(world, player, locations_per_region, location_cache, 'Skeleton Shaft'), create_region(world, player, locations_per_region, location_cache, 'Sealed Caves (upper)'), create_region(world, player, locations_per_region, location_cache, 'Sealed Caves (Xarion)'), create_region(world, player, locations_per_region, location_cache, 'Refugee Camp'), create_region(world, player, locations_per_region, location_cache, 'Forest'), create_region(world, player, locations_per_region, location_cache, 'Left Side forest Caves'), create_region(world, player, locations_per_region, location_cache, 'Upper Lake Serene'), create_region(world, player, locations_per_region, location_cache, 'Lower Lake Serene'), create_region(world, player, locations_per_region, location_cache, 'Caves of Banishment (upper)'), create_region(world, player, locations_per_region, location_cache, 'Caves of Banishment (Maw)'), create_region(world, player, locations_per_region, location_cache, 'Caves of Banishment (Sirens)'), create_region(world, player, locations_per_region, location_cache, 'Castle Ramparts'), create_region(world, player, locations_per_region, location_cache, 'Castle Keep'), create_region(world, player, locations_per_region, location_cache, 'Royal towers (lower)'), create_region(world, player, locations_per_region, location_cache, 'Royal towers'), create_region(world, player, locations_per_region, location_cache, 'Royal towers (upper)'), create_region(world, player, locations_per_region, location_cache, 'Ancient Pyramid (left)'), create_region(world, player, locations_per_region, location_cache, 'Ancient Pyramid (right)'), create_region(world, player, locations_per_region, location_cache, 'Space time continuum') ] connectStartingRegion(world, player) names: Dict[str, int] = {} connect(world, player, names, 'Lake desolation', 'Lower lake desolation', lambda state: state._timespinner_has_timestop(world, player or state.has('Talaria Attachment', player))) connect(world, player, names, 'Lake desolation', 'Upper lake desolation', lambda state: state._timespinner_has_fire(world, player) and state.can_reach('Upper Lake Serene', 'Region', player)) connect(world, player, names, 'Lake desolation', 'Skeleton Shaft', lambda state: state._timespinner_has_doublejump(world, player)) connect(world, player, names, 'Lake desolation', 'Space time continuum', lambda state: state.has('Twin Pyramid Key', player)) connect(world, player, names, 'Upper lake desolation', 'Lake desolation') connect(world, player, names, 'Upper lake desolation', 'Lower lake desolation') connect(world, player, names, 'Lower lake desolation', 'Lake desolation') connect(world, player, names, 'Lower lake desolation', 'Library') connect(world, player, names, 'Lower lake desolation', 'Space time continuum', lambda state: state.has('Twin Pyramid Key', player)) connect(world, player, names, 'Library', 'Lower lake desolation') connect(world, player, names, 'Library', 'Library top', lambda state: state._timespinner_has_doublejump(world, player) or state.has('Talaria Attachment', player)) connect(world, player, names, 'Library', 'Varndagroth tower left', lambda state: state._timespinner_has_keycard_D(world, player)) connect(world, player, names, 'Library', 'Space time continuum', lambda state: state.has('Twin Pyramid Key', player)) connect(world, player, names, 'Library top', 'Library') connect(world, player, names, 'Varndagroth tower left', 'Library') connect(world, player, names, 'Varndagroth tower left', 'Varndagroth tower right (upper)', lambda state: state._timespinner_has_keycard_C(world, player)) connect(world, player, names, 'Varndagroth tower left', 'Varndagroth tower right (lower)', lambda state: state._timespinner_has_keycard_B(world, player)) connect(world, player, names, 'Varndagroth tower left', 'Sealed Caves (Sirens)', lambda state: state._timespinner_has_keycard_B(world, player) and state.has('Elevator Keycard', player)) connect(world, player, names, 'Varndagroth tower left', 'Refugee Camp', lambda state: state.has('Timespinner Wheel', player) and state.has('Timespinner Spindle', player)) connect(world, player, names, 'Varndagroth tower right (upper)', 'Varndagroth tower left') connect(world, player, names, 'Varndagroth tower right (upper)', 'Varndagroth tower right (elevator)', lambda state: state.has('Elevator Keycard', player)) connect(world, player, names, 'Varndagroth tower right (elevator)', 'Varndagroth tower right (upper)') connect(world, player, names, 'Varndagroth tower right (elevator)', 'Varndagroth tower right (lower)') connect(world, player, names, 'Varndagroth tower right (lower)', 'Varndagroth tower left') connect(world, player, names, 'Varndagroth tower right (lower)', 'Varndagroth tower right (elevator)', lambda state: state.has('Elevator Keycard', player)) connect(world, player, names, 'Varndagroth tower right (lower)', 'Sealed Caves (Sirens)', lambda state: state._timespinner_has_keycard_B(world, player) and state.has('Elevator Keycard', player)) connect(world, player, names, 'Varndagroth tower right (lower)', 'Militairy Fortress', lambda state: state._timespinner_can_kill_all_3_bosses(world, player)) connect(world, player, names, 'Varndagroth tower right (lower)', 'Space time continuum', lambda state: state.has('Twin Pyramid Key', player)) connect(world, player, names, 'Sealed Caves (Sirens)', 'Varndagroth tower left', lambda state: state.has('Elevator Keycard', player)) connect(world, player, names, 'Sealed Caves (Sirens)', 'Varndagroth tower right (lower)', lambda state: state.has('Elevator Keycard', player)) connect(world, player, names, 'Sealed Caves (Sirens)', 'Space time continuum', lambda state: state.has('Twin Pyramid Key', player)) connect(world, player, names, 'Militairy Fortress', 'Varndagroth tower right (lower)', lambda state: state._timespinner_can_kill_all_3_bosses(world, player)) connect(world, player, names, 'Militairy Fortress', 'The lab', lambda state: state._timespinner_has_keycard_B(world, player) and state._timespinner_has_doublejump(world, player)) connect(world, player, names, 'The lab', 'Militairy Fortress') connect(world, player, names, 'The lab', 'The lab (power off)', lambda state: state._timespinner_has_doublejump_of_npc(world, player)) connect(world, player, names, 'The lab (power off)', 'The lab') connect(world, player, names, 'The lab (power off)', 'The lab (upper)', lambda state: state._timespinner_has_forwarddash_doublejump(world, player)) connect(world, player, names, 'The lab (upper)', 'The lab (power off)') connect(world, player, names, 'The lab (upper)', 'Emperors tower', lambda state: state._timespinner_has_forwarddash_doublejump(world, player)) connect(world, player, names, 'The lab (upper)', 'Ancient Pyramid (left)', lambda state: state.has_all(['Timespinner Wheel', 'Timespinner Spindle', 'Timespinner Gear 1', 'Timespinner Gear 2', 'Timespinner Gear 3'], player)) connect(world, player, names, 'Emperors tower', 'The lab (upper)') connect(world, player, names, 'Skeleton Shaft', 'Lake desolation') connect(world, player, names, 'Skeleton Shaft', 'Sealed Caves (upper)', lambda state: state._timespinner_has_keycard_A(world, player)) connect(world, player, names, 'Skeleton Shaft', 'Space time continuum', lambda state: state.has('Twin Pyramid Key', player)) connect(world, player, names, 'Sealed Caves (upper)', 'Skeleton Shaft') connect(world, player, names, 'Sealed Caves (upper)', 'Sealed Caves (Xarion)', lambda state: state.has('Twin Pyramid Key', player) or state._timespinner_has_forwarddash_doublejump(world, player)) connect(world, player, names, 'Sealed Caves (Xarion)', 'Sealed Caves (upper)', lambda state: state._timespinner_has_forwarddash_doublejump(world, player)) connect(world, player, names, 'Sealed Caves (Xarion)', 'Space time continuum', lambda state: state.has('Twin Pyramid Key', player)) connect(world, player, names, 'Refugee Camp', 'Forest') connect(world, player, names, 'Refugee Camp', 'Library', lambda state: not is_option_enabled(world, player, "Inverted")) connect(world, player, names, 'Refugee Camp', 'Space time continuum', lambda state: state.has('Twin Pyramid Key', player)) connect(world, player, names, 'Forest', 'Refugee Camp') connect(world, player, names, 'Forest', 'Left Side forest Caves', lambda state: state.has('Talaria Attachment', player) or state._timespinner_has_timestop(world, player)) connect(world, player, names, 'Forest', 'Caves of Banishment (Sirens)') connect(world, player, names, 'Forest', 'Castle Ramparts') connect(world, player, names, 'Left Side forest Caves', 'Forest') connect(world, player, names, 'Left Side forest Caves', 'Upper Lake Serene', lambda state: state._timespinner_has_timestop(world, player)) connect(world, player, names, 'Left Side forest Caves', 'Lower Lake Serene', lambda state: state.has('Water Mask', player)) connect(world, player, names, 'Left Side forest Caves', 'Space time continuum', lambda state: state.has('Twin Pyramid Key', player)) connect(world, player, names, 'Upper Lake Serene', 'Left Side forest Caves') connect(world, player, names, 'Upper Lake Serene', 'Lower Lake Serene', lambda state: state.has('Water Mask', player)) connect(world, player, names, 'Lower Lake Serene', 'Upper Lake Serene') connect(world, player, names, 'Lower Lake Serene', 'Left Side forest Caves') connect(world, player, names, 'Lower Lake Serene', 'Caves of Banishment (upper)') connect(world, player, names, 'Caves of Banishment (upper)', 'Upper Lake Serene', lambda state: state.has('Water Mask', player)) connect(world, player, names, 'Caves of Banishment (upper)', 'Caves of Banishment (Maw)', lambda state: state.has('Twin Pyramid Key', player) or state._timespinner_has_forwarddash_doublejump(world, player)) connect(world, player, names, 'Caves of Banishment (upper)', 'Space time continuum', lambda state: state.has('Twin Pyramid Key', player)) connect(world, player, names, 'Caves of Banishment (Maw)', 'Caves of Banishment (upper)', lambda state: state._timespinner_has_forwarddash_doublejump(world, player)) connect(world, player, names, 'Caves of Banishment (Maw)', 'Caves of Banishment (Sirens)', lambda state: state.has('Gas Mask', player)) connect(world, player, names, 'Caves of Banishment (Maw)', 'Space time continuum', lambda state: state.has('Twin Pyramid Key', player)) connect(world, player, names, 'Caves of Banishment (Sirens)', 'Forest') connect(world, player, names, 'Castle Ramparts', 'Forest') connect(world, player, names, 'Castle Ramparts', 'Castle Keep') connect(world, player, names, 'Castle Ramparts', 'Space time continuum', lambda state: state.has('Twin Pyramid Key', player)) connect(world, player, names, 'Castle Keep', 'Castle Ramparts') connect(world, player, names, 'Castle Keep', 'Royal towers (lower)', lambda state: state._timespinner_has_doublejump(world, player)) connect(world, player, names, 'Castle Keep', 'Space time continuum', lambda state: state.has('Twin Pyramid Key', player)) connect(world, player, names, 'Royal towers (lower)', 'Castle Keep') connect(world, player, names, 'Royal towers (lower)', 'Royal towers', lambda state: state.has('Timespinner Wheel', player) or state._timespinner_has_forwarddash_doublejump(world, player)) connect(world, player, names, 'Royal towers (lower)', 'Space time continuum', lambda state: state.has('Twin Pyramid Key', player)) connect(world, player, names, 'Royal towers', 'Royal towers (lower)') connect(world, player, names, 'Royal towers', 'Royal towers (upper)', lambda state: state._timespinner_has_doublejump(world, player)) connect(world, player, names, 'Royal towers (upper)', 'Royal towers') connect(world, player, names, 'Ancient Pyramid (left)', 'The lab (upper)') connect(world, player, names, 'Ancient Pyramid (left)', 'Ancient Pyramid (right)', lambda state: state._timespinner_has_upwarddash(world, player)) connect(world, player, names, 'Ancient Pyramid (right)', 'Ancient Pyramid (left)', lambda state: state._timespinner_has_upwarddash(world, player)) connect(world, player, names, 'Space time continuum', 'Lake desolation', lambda state: pyramid_keys_unlock == "GateLakeDesolation") connect(world, player, names, 'Space time continuum', 'Lower lake desolation', lambda state: pyramid_keys_unlock == "GateKittyBoss") connect(world, player, names, 'Space time continuum', 'Library', lambda state: pyramid_keys_unlock == "GateLeftLibrary") connect(world, player, names, 'Space time continuum', 'Varndagroth tower right (lower)', lambda state: pyramid_keys_unlock == "GateMilitairyGate") connect(world, player, names, 'Space time continuum', 'Skeleton Shaft', lambda state: pyramid_keys_unlock == "GateSealedCaves") connect(world, player, names, 'Space time continuum', 'Sealed Caves (Sirens)', lambda state: pyramid_keys_unlock == "GateSealedSirensCave") connect(world, player, names, 'Space time continuum', 'Left Side forest Caves', lambda state: pyramid_keys_unlock == "GateLakeSirineRight") connect(world, player, names, 'Space time continuum', 'Refugee Camp', lambda state: pyramid_keys_unlock == "GateAccessToPast") connect(world, player, names, 'Space time continuum', 'Castle Ramparts', lambda state: pyramid_keys_unlock == "GateCastleRamparts") connect(world, player, names, 'Space time continuum', 'Castle Keep', lambda state: pyramid_keys_unlock == "GateCastleKeep") connect(world, player, names, 'Space time continuum', 'Royal towers (lower)', lambda state: pyramid_keys_unlock == "GateRoyalTowers") connect(world, player, names, 'Space time continuum', 'Caves of Banishment (Maw)', lambda state: pyramid_keys_unlock == "GateMaw") connect(world, player, names, 'Space time continuum', 'Caves of Banishment (upper)', lambda state: pyramid_keys_unlock == "GateCavesOfBanishment") def create_location(player: int, location_data: LocationData, region: Region, location_cache: List[Location]) -> Location: location = Location(player, location_data.name, location_data.code, region) location.access_rule = location_data.rule if id is None: location.event = True location.locked = True location_cache.append(location) return location def create_region(world: MultiWorld, player: int, locations_per_region: Dict[str, List[LocationData]], location_cache: List[Location], name: str) -> Region: region = Region(name, RegionType.Generic, name, player) region.world = world if name in locations_per_region: for location_data in locations_per_region[name]: location = create_location(player, location_data, region, location_cache) region.locations.append(location) return region def connectStartingRegion(world: MultiWorld, player: int): menu = world.get_region('Menu', player) tutorial = world.get_region('Tutorial', player) space_time_continuum = world.get_region('Space time continuum', player) if is_option_enabled(world, player, "Inverted"): starting_region = world.get_region('Refugee Camp', player) else: starting_region = world.get_region('Lake desolation', player) menu_to_tutorial = Entrance(player, 'Tutorial', menu) menu_to_tutorial.connect(tutorial) menu.exits.append(menu_to_tutorial) tutorial_to_start = Entrance(player, 'Start Game', tutorial) tutorial_to_start.connect(starting_region) tutorial.exits.append(tutorial_to_start) teleport_back_to_start = Entrance(player, 'Teleport back to start', space_time_continuum) teleport_back_to_start.connect(starting_region) space_time_continuum.exits.append(teleport_back_to_start) def connect(world: MultiWorld, player: int, used_names: Dict[str, int], source: str, target: str, rule: Optional[Callable] = None): sourceRegion = world.get_region(source, player) targetRegion = world.get_region(target, player) if target not in used_names: used_names[target] = 1 name = target else: used_names[target] += 1 name = target + (' ' * used_names[target]) connection = Entrance(player, name, sourceRegion) if rule: connection.access_rule = rule sourceRegion.exits.append(connection) connection.connect(targetRegion) def get_locations_per_region(locations: Tuple[LocationData, ...]) -> Dict[str, List[LocationData]]: per_region: Dict[str, List[LocationData]] = {} for location in locations: per_region.setdefault(location.region, []).append(location) return per_region <file_sep># Archipelago Setup Guide ## Installing the Archipelago software The most recent public release of Archipelago can be found [here](https://github.com/ArchipelagoMW/Archipelago/releases). Run the exe file, and after accepting the license agreement you will be prompted on which components you would like to install. The generator allows you to generate multiworld games on your computer. The ROM setups are optional but are required if anyone in the game that you generate wants to play any of those games as they are needed to generate the relevant patch files. The server will allow you to host the multiworld on your machine but this also requires you to port forward. The default port for Archipelago is `38281`. If you are unsure how to do this there are plenty of other guides on the internet that will be more suited to your hardware. The `Clients` are what you use to connect your game to the multiworld. If the game/games you plan to play are available here go ahead and install these as well. If the game you choose to play is supported by Archipelago but not listed in the installation check the relevant tutorial. ## Generating a game ### Gather all player YAMLS All players that wish to play in the generated multiworld must have a YAML file which contains the settings that they wish to play with. A YAML is a file which contains human readable markup. In other words, this is a settings file kind of like an INI file or a TOML file. Each player can go to the game's player settings page in order to determine the settings how they want them and then download a YAML file containing these settings. After getting the YAML files of each participant for your multiworld game, these can all either be placed together in the `Archipelago\Players` folder or compressed into a ZIP folder to then be uploaded to the [website generator](/generate). If rolling locally ensure that the folder is clear of any files you do not wish to include in the game such as the included default player settings files. #### Changing local host settings for generation Sometimes there are various settings that you may want to change before rolling a seed such as enabling race mode, auto-forfeit, plando support, or setting a password. All of these settings plus other options are able to be changed by modifying the `host.yaml` file in the base `Archipelago` folder. The settings chosen here are baked into the serverdata file that gets output with the other files after generation so if rolling locally ensure this file is edited to your liking *before* rolling the seed. ### Rolling the seed #### On the Website After gathering the YAML files together in one location, select all of the files and compress them into a .zip folder. Next go to the [Start Playing](/start-playing) page and click on `generate a randomized game` to reach the website generator. Here, you can adjust some server settings such as forfeit rules and the cost for a player to use a hint before generation. After adjusting the host settings to your liking click on the Upload File button and using the explorer window that opens, navigate to the location where you zipped the player files and upload this zip. The page will generate your game and refresh multiple times to check on completion status. After the generation completes you will be on a Seed Info page that provides the seed, the date/time of creation, a link to the spoiler log, if available, and links to any rooms created from this seed. To begin playing, click on `Create New Room`, which will take you to the room page. From here you can navigate back to thse Seed Info page or to the Tracker page. Sharing the link to this page with your friends will provide them with the necessary info and files for them to connect to the multiworld. #### Rolling using the generation program After gathering the YAML files together in the `Archipelago\Players` folder, run the program `ArchipelagoGenerate.exe` in the base `Archipelago` folder. This will then open a console window and either silently close itself or spit out an error. If you receive an error, it is likely due to an error in the YAML file. If the error is unhelpful in figuring out the issue asking in the ***#tech-support*** channel of our Discord for help with finding it is highly recommended. The generator will put a zip folder into your `Archipelago\output` folder with the format `AP_XXXXXXXXX`.zip. This contains the patch files and relevant mods for the players as well as the serverdata for the host. ## Hosting a multiworld ### Uploading the seed to the website The easiest and most recommended method is to generate the game on the website which will allow you to create a private room with all the necessary files you can share, as well as hosting the game and supporting item trackers for various games. If for some reason the seed was rolled on a machine, then either the resulting zip file or the resulting `AP_XXXXX.archipelago` inside the zip file can be uploaded to the [upload page](/uploads). This will give a page with the seed info and have a link to the spoiler if it exists. Click on Create New room and then share the link for the room with the other players so that they can download their patches or mods. The room will also have a link to a Multiworld Tracker and tell you what the players need to connect to from their clients. ### Hosting a seed locally For this we'll assume you have already port forwarding `38281` and have generated a seed that is still in the `outputs` folder. Next, you'll want to run `ArchipelagoServer.exe`. A window will open in order to open the multiworld data for the game. You can either use the generated zip folder or extract the .archipelago file and use it. If everything worked correctly the console window should tell you it's now hosting a game with the IP, port, and password that clients will need in order to connect. Extract the patch and mod files then send those to your friends, and you're done! <file_sep> def link_minecraft_structures(world, player): # Link mandatory connections first for (exit, region) in mandatory_connections: world.get_entrance(exit, player).connect(world.get_region(region, player)) # Get all unpaired exits and all regions without entrances (except the Menu) # This function is destructive on these lists. exits = [exit.name for r in world.regions if r.player == player for exit in r.exits if exit.connected_region == None] structs = [r.name for r in world.regions if r.player == player and r.entrances == [] and r.name != 'Menu'] exits_spoiler = exits[:] # copy the original order for the spoiler log try: assert len(exits) == len(structs) except AssertionError as e: # this should never happen raise Exception(f"Could not obtain equal numbers of Minecraft exits and structures for player {player} ({world.player_name[player]})") pairs = {} def set_pair(exit, struct): if (exit in exits) and (struct in structs) and (exit not in illegal_connections.get(struct, [])): pairs[exit] = struct exits.remove(exit) structs.remove(struct) else: raise Exception(f"Invalid connection: {exit} => {struct} for player {player} ({world.player_name[player]})") # Connect plando structures first if world.plando_connections[player]: for conn in world.plando_connections[player]: set_pair(conn.entrance, conn.exit) # The algorithm tries to place the most restrictive structures first. This algorithm always works on the # relatively small set of restrictions here, but does not work on all possible inputs with valid configurations. if world.shuffle_structures[player]: structs.sort(reverse=True, key=lambda s: len(illegal_connections.get(s, []))) for struct in structs[:]: try: exit = world.random.choice([e for e in exits if e not in illegal_connections.get(struct, [])]) except IndexError: raise Exception(f"No valid structure placements remaining for player {player} ({world.player_name[player]})") set_pair(exit, struct) else: # write remaining default connections for (exit, struct) in default_connections: if exit in exits: set_pair(exit, struct) # Make sure we actually paired everything; might fail if plando try: assert len(exits) == len(structs) == 0 except AssertionError: raise Exception(f"Failed to connect all Minecraft structures for player {player} ({world.player_name[player]})") for exit in exits_spoiler: world.get_entrance(exit, player).connect(world.get_region(pairs[exit], player)) if world.shuffle_structures[player] or world.plando_connections[player]: world.spoiler.set_entrance(exit, pairs[exit], 'entrance', player) # (Region name, list of exits) mc_regions = [ ('Menu', ['New World']), ('Overworld', ['Nether Portal', 'End Portal', 'Overworld Structure 1', 'Overworld Structure 2']), ('The Nether', ['Nether Structure 1', 'Nether Structure 2']), ('The End', ['The End Structure']), ('Village', []), ('Pillager Outpost', []), ('Nether Fortress', []), ('Bastion Remnant', []), ('End City', []) ] # (Entrance, region pointed to) mandatory_connections = [ ('New World', 'Overworld'), ('Nether Portal', 'The Nether'), ('End Portal', 'The End') ] default_connections = [ ('Overworld Structure 1', 'Village'), ('Overworld Structure 2', 'Pillager Outpost'), ('Nether Structure 1', 'Nether Fortress'), ('Nether Structure 2', 'Bastion Remnant'), ('The End Structure', 'End City') ] # Structure: illegal locations illegal_connections = { 'Nether Fortress': ['The End Structure'] } <file_sep># Factorio ## Where is the settings page? The player settings page for this game is located <a href="../player-settings">here</a>. It contains all the options you need to configure and export a config file. ## What does randomization do to this game? In Factorio, the research tree is shuffled, causing certain technologies to be obtained in a non-standard order. Recipe costs, technology requirements, and science pack requirements may also be shuffled at the player's discretion. ## What Factorio items can appear in other players' worlds? Factorio's technologies are removed from its tech tree and placed into other players' worlds. When those technologies are found, they are sent back to Factorio along with, optionally, free samples of those technologies. ## What is a free sample? A free sample is a single or stack of items in Factorio, granted by a technology received from another world. For example, receiving the technology `Portable Solar Panel` may also grant the player a stack of portable solar panels, and place them directly into the player's inventory. ## What does another world's item look like in Factorio? In Factorio, items which need to be sent to other worlds appear in the tech tree as new research items. They are represented by the Archipelago icon, and must be researched as if it were a normal technology. Upon successful completion of research, the item will be sent to its home world. ## When the engineer receives an item, what happens? When the player receives a technology, it is instantly learned and able to be crafted. A message will appear in the chat log to notify the player, and if free samples are enabled the player may also receive some items directly to their inventory. <file_sep>{% extends 'pageWrapper.html' %} {% block head %} {{ super() }} <title>Generate Game</title> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename="styles/generate.css") }}" /> <script type="application/ecmascript" src="{{ url_for('static', filename="assets/generate.js") }}"></script> {% endblock %} {% block body %} {% include 'header/oceanHeader.html' %} <div id="generate-game-wrapper"> <div id="generate-game" class="grass-island"> <h1>Generate Game{% if race %} (Race Mode){% endif %}</h1> <p> This page allows you to generate a game by uploading a config file or a zip file containing config files. If you do not have a config (.yaml) file yet, you may create one on the game's settings page, which you can find via the <a href="{{ url_for("games") }}">supported games list</a>. </p> <p> {% if race -%} This game will be generated in race mode, meaning the spoiler log will be unavailable and game specific protections will be in place, like ROM encryption or cheat mode removal. {%- else -%} If you would like to generate a race game, <a href="{{ url_for("generate", race=True) }}">click here.</a><br /> Race games are generated without a spoiler log and game specific protections will be in place, like ROM encryption or cheat mode removal. {%- endif -%} </p> <div id="generate-game-form-wrapper"> <form id="generate-game-form" method="post" enctype="multipart/form-data"> <table> <tbody> <tr> <td><label for="forfeit_mode">Forfeit Permission:</label></td> <td> <select name="forfeit_mode" id="forfeit_mode"> <option value="auto">Automatic on goal completion</option> <option value="goal">Allow !forfeit after goal completion</option> <option value="auto-enabled">Automatic on goal completion and manual !forfeit</option> <option value="enabled">Manual !forfeit</option> <option value="disabled">Disabled</option> </select> </td> </tr> <tr> <td> <label for="hint_cost"> Hint Cost:</label> <span class="interactive" data-tooltip="After gathering this many checks, players can !hint <itemname> to get the location of that hint item.">(?) </span> </td> <td> <select name="hint_cost" id="hint_cost"> {% for n in range(0, 110, 5) %} <option {% if n == 10 %}selected="selected" {% endif %} value="{{ n }}"> {% if n > 100 %}Off{% else %}{{ n }}%{% endif %} </option> {% endfor %} </select> </td> </tr> </tbody> </table> <div id="generate-form-button-row"> <input id="file-input" type="file" name="file"> </div> </form> <button id="generate-game-button">Upload File</button> </div> </div> </div> {% include 'islandFooter.html' %} {% endblock %} <file_sep># Subnautica Randomizer Setup Guide ## Required Software - [Subnautica](https://store.steampowered.com/app/264710/Subnautica/) - [QModManager4](https://www.nexusmods.com/subnautica/mods/201) - [Archipelago Mod for Subnautica](https://github.com/Berserker66/ArchipelagoSubnauticaModSrc/releases) ## Installation Procedures 1. Install QModManager4 as per its instructions. 2. The folder you installed QModManager4 into will now have a /QMods directory. It might appear after a start of Subnautica. You can also create this folder yourself. 3. Unpack the Archipelago Mod into this folder, so that Subnautica/QMods/Archipelago/ is a valid path. 4. Start Subnautica. You should see a Connect Menu in the topleft of your main Menu. ## Troubleshooting If you don't see the connect window check that you see a qmodmanager_log-Subnautica.txt in Subnautica, if not QModManager4 is not correctly installed, otherwise open it and look for `[Info : BepInEx] Loading [Archipelago 1.0.0.0]`, version number doesn't matter. If it doesn't show this, then QModManager4 didn't find the Archipelago mod, so check your paths. ## Joining a MultiWorld Game 1. In Host, enter the address of the server, such as archipelago.gg:38281, your server host should be able to tell you this. 2. In Password enter the server password if one exists, otherwise leave blank. 3. In PlayerName enter your "name" field from the yaml, or website config. 4. Hit Connect. If it says succesfully authenticated you can now create a new savegame or resume the correct savegame.<file_sep># Archipelago Triggers Guide ## What are triggers? Triggers allow you to customize your game settings by allowing you to define certain options or even a variety of settings to occur or "trigger" under certain conditions. These are essentially "if, then statements" for options in your game. A good example of what you can do with triggers is the custom [mercenary mode](https://github.com/alwaysintreble/Archipelago-yaml-dump/blob/main/Snippets/Mercenary%20Mode%20Snippet.yaml) that was created using entirely triggers and plando. For more information on plando you can reference [this guide](/tutorial/archipelago/plando/en) or [this guide](/tutorial/zelda3/plando/en). ## Trigger use Triggers have to be defined in the root of the yaml file meaning it must be outside of a game section. The best place to do this is the bottom of the yaml. - Triggers comprise of the trigger section and then each trigger must have an `option_category`, `option_name`, and `option_result` from which it will react to and then an `options` section where the definition of what will happen. - `option_category` is the defining section from which the option is defined in. - Example: `A Link to the Past` - This is the root category the option is located in. If the option you're triggering off of is in root then you would use `null`, otherwise this is the game for which you want this option trigger to activate. - `option_name` is the option setting from which the triggered choice is going to react to. - Example: `shop_item_slots` - This can be any option from any category defined in the yaml file in either root or a game section except for `game`. - `option_result` is the result of this option setting from which you would like to react. - Example: `15` - Each trigger must be used for exactly one option result. If you would like the same thing to occur with multiple results you would need multiple triggers for this. - `options` is where you define what will happen when this is detected. This can be something as simple as ensuring another option also gets selected or placing an item in a certain location. - Example: ```yaml A Link to the Past: start_inventory: Rupees (300): 2 ``` This format must be: ```yaml root option: option to change: desired result ``` ### Examples The above examples all together will end up looking like this: ```yaml triggers: - option_category: A Link to the Past option_name: shop_item_slots option_result: 15 options: A Link to the Past: start_inventory: Rupees(300): 2 ``` For this example if the generator happens to roll 15 shuffled in shop item slots for your game you'll be granted 600 rupees at the beginning. These can also be used to change other options. For example: ```yaml triggers: - option_category: Timespinner option_name: SpecificKeycards option_result: true options: Timespinner: Inverted: true ``` In this example if your world happens to roll SpecificKeycards then your game will also start in inverted.<file_sep># generated by https://github.com/Berserker66/HollowKnight.RandomizerMod/blob/master/extract_data.py # do not edit manually lookup_id_to_name = \ { 17825793: 'Lurien', 17825794: 'Monomon', 17825795: 'Herrah', 17825796: 'World_Sense', 17825798: 'Mothwing_Cloak', 17825799: 'Mantis_Claw', 17825800: 'Crystal_Heart', 17825801: 'Monarch_Wings', 17825802: 'Shade_Cloak', 17825803: "Isma's_Tear", 17825804: 'Dream_Nail', 17825805: 'Dream_Gate', 17825806: 'Awoken_Dream_Nail', 17825807: 'Vengeful_Spirit', 17825808: 'Shade_Soul', 17825809: 'Desolate_Dive', 17825810: 'Descending_Dark', 17825811: 'Howling_Wraiths', 17825812: 'Abyss_Shriek', 17825813: 'Cyclone_Slash', 17825814: 'Dash_Slash', 17825815: 'Great_Slash', 17825816: 'Focus', 17825817: 'Gathering_Swarm', 17825818: 'Wayward_Compass', 17825819: 'Grubsong', 17825820: 'Stalwart_Shell', 17825821: 'Baldur_Shell', 17825822: 'Fury_of_the_Fallen', 17825823: 'Quick_Focus', 17825824: 'Lifeblood_Heart', 17825825: 'Lifeblood_Core', 17825826: "Defender's_Crest", 17825827: 'Flukenest', 17825828: 'Thorns_of_Agony', 17825829: 'Mark_of_Pride', 17825830: 'Steady_Body', 17825831: 'Heavy_Blow', 17825832: 'Sharp_Shadow', 17825833: 'Spore_Shroom', 17825834: 'Longnail', 17825835: 'Shaman_Stone', 17825836: 'Soul_Catcher', 17825837: 'Soul_Eater', 17825838: 'Glowing_Womb', 17825839: 'Fragile_Heart', 17825840: 'Fragile_Greed', 17825841: 'Fragile_Strength', 17825842: "Nailmaster's_Glory", 17825843: "Joni's_Blessing", 17825844: 'Shape_of_Unn', 17825845: 'Hiveblood', 17825846: 'Dream_Wielder', 17825847: 'Dashmaster', 17825848: 'Quick_Slash', 17825849: 'Spell_Twister', 17825850: 'Deep_Focus', 17825851: "Grubberfly's_Elegy", 17825852: 'Queen_Fragment', 17825853: 'King_Fragment', 17825854: 'Void_Heart', 17825855: 'Sprintmaster', 17825856: 'Dreamshield', 17825857: 'Weaversong', 17825858: 'Grimmchild', 17825859: 'City_Crest', 17825860: 'Lumafly_Lantern', 17825861: 'Tram_Pass', 17825862: 'Simple_Key-Sly', 17825863: 'Simple_Key-Basin', 17825864: 'Simple_Key-City', 17825865: 'Simple_Key-Lurker', 17825866: "Shopkeeper's_Key", 17825867: 'Elegant_Key', 17825868: 'Love_Key', 17825869: "King's_Brand", 17825870: 'Godtuner', 17825871: "Collector's_Map", 17825872: 'Mask_Shard-Sly1', 17825873: 'Mask_Shard-Sly2', 17825874: 'Mask_Shard-Sly3', 17825875: 'Mask_Shard-Sly4', 17825876: 'Mask_Shard-Seer', 17825877: 'Mask_Shard-5_Grubs', 17825878: 'Mask_Shard-Brooding_Mawlek', 17825879: 'Mask_Shard-Crossroads_Goam', 17825880: 'Mask_Shard-Stone_Sanctuary', 17825881: "Mask_Shard-Queen's_Station", 17825882: 'Mask_Shard-Deepnest', 17825883: 'Mask_Shard-Waterways', 17825884: 'Mask_Shard-Enraged_Guardian', 17825885: 'Mask_Shard-Hive', 17825886: 'Mask_Shard-Grey_Mourner', 17825887: 'Mask_Shard-Bretta', 17825888: 'Vessel_Fragment-Sly1', 17825889: 'Vessel_Fragment-Sly2', 17825890: 'Vessel_Fragment-Seer', 17825891: 'Vessel_Fragment-Greenpath', 17825892: 'Vessel_Fragment-City', 17825893: 'Vessel_Fragment-Crossroads', 17825894: 'Vessel_Fragment-Basin', 17825895: 'Vessel_Fragment-Deepnest', 17825896: 'Vessel_Fragment-Stag_Nest', 17825897: 'Charm_Notch-Shrumal_Ogres', 17825898: 'Charm_Notch-Fog_Canyon', 17825899: 'Charm_Notch-Colosseum', 17825900: 'Charm_Notch-Grimm', 17825901: 'Pale_Ore-Basin', 17825902: 'Pale_Ore-Crystal_Peak', 17825903: 'Pale_Ore-Nosk', 17825904: 'Pale_Ore-Seer', 17825905: 'Pale_Ore-Grubs', 17825906: 'Pale_Ore-Colosseum', 17825907: '200_Geo-False_Knight_Chest', 17825908: '380_Geo-Soul_Master_Chest', 17825909: '655_Geo-Watcher_Knights_Chest', 17825910: '85_Geo-Greenpath_Chest', 17825911: '620_Geo-Mantis_Lords_Chest', 17825912: '150_Geo-Resting_Grounds_Chest', 17825913: '80_Geo-Crystal_Peak_Chest', 17825914: '160_Geo-Weavers_Den_Chest', 17825916: 'Rancid_Egg-Sly', 17825917: 'Rancid_Egg-Grubs', 17825918: 'Rancid_Egg-Sheo', 17825919: 'Rancid_Egg-Fungal_Core', 17825920: "Rancid_Egg-Queen's_Gardens", 17825921: 'Rancid_Egg-Blue_Lake', 17825922: 'Rancid_Egg-Crystal_Peak_Dive_Entrance', 17825923: 'Rancid_Egg-Crystal_Peak_Dark_Room', 17825924: 'Rancid_Egg-Crystal_Peak_Tall_Room', 17825925: 'Rancid_Egg-City_of_Tears_Left', 17825926: 'Rancid_Egg-City_of_Tears_Pleasure_House', 17825927: "Rancid_Egg-Beast's_Den", 17825928: 'Rancid_Egg-Dark_Deepnest', 17825929: "Rancid_Egg-Weaver's_Den", 17825930: 'Rancid_Egg-Near_Quick_Slash', 17825931: "Rancid_Egg-Upper_Kingdom's_Edge", 17825932: 'Rancid_Egg-Waterways_East', 17825933: 'Rancid_Egg-Waterways_Main', 17825934: 'Rancid_Egg-Waterways_West_Bluggsac', 17825935: 'Rancid_Egg-Waterways_West_Pickup', 17825936: "Wanderer's_Journal-Cliffs", 17825937: "Wanderer's_Journal-Greenpath_Stag", 17825938: "Wanderer's_Journal-Greenpath_Lower", 17825939: "Wanderer's_Journal-Fungal_Wastes_Thorns_Gauntlet", 17825940: "Wanderer's_Journal-Above_Mantis_Village", 17825941: "Wanderer's_Journal-Crystal_Peak_Crawlers", 17825942: "Wanderer's_Journal-Resting_Grounds_Catacombs", 17825943: "Wanderer's_Journal-King's_Station", 17825944: "Wanderer's_Journal-Pleasure_House", 17825945: "Wanderer's_Journal-City_Storerooms", 17825946: "Wanderer's_Journal-Ancient_Basin", 17825947: "Wanderer's_Journal-Kingdom's_Edge_Entrance", 17825948: "Wanderer's_Journal-Kingdom's_Edge_Camp", 17825949: "Wanderer's_Journal-Kingdom's_Edge_Requires_Dive", 17825950: 'Hallownest_Seal-Crossroads_Well', 17825951: 'Hallownest_Seal-Grubs', 17825952: 'Hallownest_Seal-Greenpath', 17825953: 'Hallownest_Seal-Fog_Canyon_West', 17825954: 'Hallownest_Seal-Fog_Canyon_East', 17825955: "Hallownest_Seal-Queen's_Station", 17825956: 'Hallownest_Seal-Fungal_Wastes_Sporgs', 17825957: 'Hallownest_Seal-Mantis_Lords', 17825958: 'Hallownest_Seal-Seer', 17825959: 'Hallownest_Seal-Resting_Grounds_Catacombs', 17825960: "Hallownest_Seal-King's_Station", 17825961: 'Hallownest_Seal-City_Rafters', 17825962: 'Hallownest_Seal-Soul_Sanctum', 17825963: 'Hallownest_Seal-Watcher_Knight', 17825964: 'Hallownest_Seal-Deepnest_By_Mantis_Lords', 17825965: "Hallownest_Seal-Beast's_Den", 17825966: "Hallownest_Seal-Queen's_Gardens", 17825967: "King's_Idol-Grubs", 17825968: "King's_Idol-Cliffs", 17825969: "King's_Idol-Crystal_Peak", 17825970: "King's_Idol-Glade_of_Hope", 17825971: "King's_Idol-Dung_Defender", 17825972: "King's_Idol-Great_Hopper", 17825973: "King's_Idol-Pale_Lurker", 17825974: "King's_Idol-Deepnest", 17825975: 'Arcane_Egg-Seer', 17825976: 'Arcane_Egg-Lifeblood_Core', 17825977: 'Arcane_Egg-Shade_Cloak', 17825978: 'Arcane_Egg-Birthplace', 17825979: 'Whispering_Root-Crossroads', 17825980: 'Whispering_Root-Greenpath', 17825981: 'Whispering_Root-Leg_Eater', 17825982: 'Whispering_Root-Mantis_Village', 17825983: 'Whispering_Root-Deepnest', 17825984: 'Whispering_Root-Queens_Gardens', 17825985: 'Whispering_Root-Kingdoms_Edge', 17825986: 'Whispering_Root-Waterways', 17825987: 'Whispering_Root-City', 17825988: 'Whispering_Root-Resting_Grounds', 17825989: 'Whispering_Root-Spirits_Glade', 17825990: 'Whispering_Root-Crystal_Peak', 17825991: 'Whispering_Root-Howling_Cliffs', 17825992: 'Whispering_Root-Ancestral_Mound', 17825993: 'Whispering_Root-Hive', 17825994: 'Boss_Essence-Elder_Hu', 17825995: 'Boss_Essence-Xero', 17825996: 'Boss_Essence-Gorb', 17825997: 'Boss_Essence-Marmu', 17825998: 'Boss_Essence-No_Eyes', 17825999: 'Boss_Essence-Galien', 17826000: 'Boss_Essence-Markoth', 17826001: 'Boss_Essence-Failed_Champion', 17826002: 'Boss_Essence-Soul_Tyrant', 17826003: 'Boss_Essence-Lost_Kin', 17826004: 'Boss_Essence-White_Defender', 17826005: 'Boss_Essence-Grey_Prince_Zote', 17826006: 'Grub-Crossroads_Acid', 17826007: 'Grub-Crossroads_Center', 17826008: 'Grub-Crossroads_Stag', 17826009: 'Grub-Crossroads_Spike', 17826010: 'Grub-Crossroads_Guarded', 17826011: 'Grub-Greenpath_Cornifer', 17826012: 'Grub-Greenpath_Journal', 17826013: 'Grub-Greenpath_MMC', 17826014: 'Grub-Greenpath_Stag', 17826015: 'Grub-Fog_Canyon', 17826016: 'Grub-Fungal_Bouncy', 17826017: 'Grub-Fungal_Spore_Shroom', 17826018: 'Grub-Deepnest_Mimic', 17826019: 'Grub-Deepnest_Nosk', 17826020: 'Grub-Deepnest_Spike', 17826021: 'Grub-Dark_Deepnest', 17826022: "Grub-Beast's_Den", 17826023: "Grub-Kingdom's_Edge_Oro", 17826024: "Grub-Kingdom's_Edge_Camp", 17826025: 'Grub-Hive_External', 17826026: 'Grub-Hive_Internal', 17826027: 'Grub-Basin_Requires_Wings', 17826028: 'Grub-Basin_Requires_Dive', 17826029: 'Grub-Waterways_Main', 17826030: 'Grub-Waterways_East', 17826031: 'Grub-Waterways_Requires_Tram', 17826032: 'Grub-City_of_Tears_Left', 17826033: 'Grub-Soul_Sanctum', 17826034: "Grub-Watcher's_Spire", 17826035: 'Grub-City_of_Tears_Guarded', 17826036: "Grub-King's_Station", 17826037: 'Grub-Resting_Grounds', 17826038: 'Grub-Crystal_Peak_Below_Chest', 17826039: 'Grub-Crystallized_Mound', 17826040: 'Grub-Crystal_Peak_Spike', 17826041: 'Grub-Crystal_Peak_Mimic', 17826042: 'Grub-Crystal_Peak_Crushers', 17826043: 'Grub-Crystal_Heart', 17826044: 'Grub-Hallownest_Crown', 17826045: 'Grub-Howling_Cliffs', 17826046: "Grub-Queen's_Gardens_Stag", 17826047: "Grub-Queen's_Gardens_Marmu", 17826048: "Grub-Queen's_Gardens_Top", 17826049: 'Grub-Collector_1', 17826050: 'Grub-Collector_2', 17826051: 'Grub-Collector_3', 17826052: 'Crossroads_Map', 17826053: 'Greenpath_Map', 17826054: 'Fog_Canyon_Map', 17826055: 'Fungal_Wastes_Map', 17826056: 'Deepnest_Map-Upper', 17826057: 'Deepnest_Map-Right_[Gives_Quill]', 17826058: 'Ancient_Basin_Map', 17826059: "Kingdom's_Edge_Map", 17826060: 'City_of_Tears_Map', 17826061: 'Royal_Waterways_Map', 17826062: 'Howling_Cliffs_Map', 17826063: 'Crystal_Peak_Map', 17826064: "Queen's_Gardens_Map", 17826065: 'Resting_Grounds_Map', 17826066: 'Dirtmouth_Stag', 17826067: 'Crossroads_Stag', 17826068: 'Greenpath_Stag', 17826069: "Queen's_Station_Stag", 17826070: "Queen's_Gardens_Stag", 17826071: 'City_Storerooms_Stag', 17826072: "King's_Station_Stag", 17826073: 'Resting_Grounds_Stag', 17826074: 'Distant_Village_Stag', 17826075: 'Hidden_Station_Stag', 17826076: 'Stag_Nest_Stag', 17826077: "Lifeblood_Cocoon-King's_Pass", 17826078: 'Lifeblood_Cocoon-Ancestral_Mound', 17826079: 'Lifeblood_Cocoon-Greenpath', 17826080: 'Lifeblood_Cocoon-Fog_Canyon_West', 17826081: 'Lifeblood_Cocoon-Mantis_Village', 17826082: 'Lifeblood_Cocoon-Failed_Tramway', 17826083: 'Lifeblood_Cocoon-Galien', 17826084: "Lifeblood_Cocoon-Kingdom's_Edge", 17826085: 'Grimmkin_Flame-City_Storerooms', 17826086: 'Grimmkin_Flame-Greenpath', 17826087: 'Grimmkin_Flame-Crystal_Peak', 17826088: "Grimmkin_Flame-King's_Pass", 17826089: 'Grimmkin_Flame-Resting_Grounds', 17826090: "Grimmkin_Flame-Kingdom's_Edge", 17826091: 'Grimmkin_Flame-Fungal_Core', 17826092: 'Grimmkin_Flame-Ancient_Basin', 17826093: 'Grimmkin_Flame-Hive', 17826094: 'Grimmkin_Flame-Brumm'} lookup_name_to_id = {location_name: location_id for location_id, location_name in lookup_id_to_name.items()}<file_sep>import logging from typing import Set logger = logging.getLogger("Hollow Knight") from .Locations import lookup_name_to_id from .Items import item_table, lookup_type_to_names from .Regions import create_regions from .Rules import set_rules from .Options import hollow_knight_options from BaseClasses import Region, Entrance, Location, MultiWorld, Item from ..AutoWorld import World, LogicMixin class HKWorld(World): game: str = "Hollow Knight" options = hollow_knight_options item_name_to_id = {name: data.id for name, data in item_table.items() if data.type != "Event"} location_name_to_id = lookup_name_to_id hidden = True def generate_basic(self): # Link regions self.world.get_entrance('Hollow Nest S&Q', self.player).connect(self.world.get_region('Hollow Nest', self.player)) # Generate item pool pool = [] for item_name, item_data in item_table.items(): item = self.create_item(item_name) if item_data.type == "Event": event_location = self.world.get_location(item_name, self.player) self.world.push_item(event_location, item, collect=False) event_location.event = True event_location.locked = True if item.name == "King's_Pass": self.world.push_precollected(item) elif item_data.type == "Cursed": if self.world.CURSED[self.player]: pool.append(item) else: # fill Focus Location with Focus and add it to start inventory as well. event_location = self.world.get_location(item_name, self.player) self.world.push_item(event_location, item) event_location.event = True event_location.locked = True elif item_data.type == "Fake": pass elif item_data.type in not_shufflable_types: location = self.world.get_location(item_name, self.player) self.world.push_item(location, item, collect=False) location.event = item.advancement location.locked = True else: target = option_to_type_lookup[item.type] shuffle_it = getattr(self.world, target) if shuffle_it[self.player]: pool.append(item) else: location = self.world.get_location(item_name, self.player) self.world.push_item(location, item, collect=False) location.event = item.advancement location.locked = True logger.debug(f"Placed {item_name} to vanilla for player {self.player}") self.world.itempool += pool def set_rules(self): set_rules(self.world, self.player) def create_regions(self): create_regions(self.world, self.player) def generate_output(self): pass # Hollow Knight needs no output files def fill_slot_data(self): slot_data = {} for option_name in self.options: option = getattr(self.world, option_name)[self.player] slot_data[option_name] = int(option.value) return slot_data def create_item(self, name: str) -> Item: item_data = item_table[name] return HKItem(name, item_data.advancement, item_data.id, item_data.type, self.player) def create_region(world: MultiWorld, player: int, name: str, locations=None, exits=None): ret = Region(name, None, name, player) ret.world = world if locations: for location in locations: loc_id = lookup_name_to_id.get(location, 0) location = HKLocation(player, location, loc_id, ret) ret.locations.append(location) if exits: for exit in exits: ret.exits.append(Entrance(player, exit, ret)) return ret class HKLocation(Location): game: str = "Hollow Knight" def __init__(self, player: int, name: str, address=None, parent=None): super(HKLocation, self).__init__(player, name, address, parent) class HKItem(Item): game = "Hollow Knight" def __init__(self, name, advancement, code, type, player: int = None): super(HKItem, self).__init__(name, advancement, code, player) self.type = type not_shufflable_types = {"Essence_Boss"} option_to_type_lookup = { "Root": "RandomizeWhisperingRoots", "Dreamer": "RandomizeDreamers", "Geo": "RandomizeGeoChests", "Skill": "RandomizeSkills", "Map": "RandomizeMaps", "Relic": "RandomizeRelics", "Charm": "RandomizeCharms", "Notch": "RandomizeCharmNotches", "Key": "RandomizeKeys", "Stag": "RandomizeStags", "Flame": "RandomizeFlames", "Grub": "RandomizeGrubs", "Cocoon": "RandomizeLifebloodCocoons", "Mask": "RandomizeMaskShards", "Ore": "RandomizePaleOre", "Egg": "RandomizeRancidEggs", "Vessel": "RandomizeVesselFragments", } class HKLogic(LogicMixin): # these are all wip def _hk_has_essence(self, player: int, count: int): return self.prog_items["Dream_Nail", player] # return self.prog_items["Essence", player] >= count def _hk_has_grubs(self, player: int, count: int): found = 0 for item_name in lookup_type_to_names["Grub"]: found += self.prog_items[item_name, player] if found >= count: return True return False def _hk_has_flames(self, player: int, count: int): found = 0 for item_name in lookup_type_to_names["Flame"]: found += self.prog_items[item_name, player] if found >= count: return True return False<file_sep># generated by https://github.com/Berserker66/ori_rando_server # do not edit manually from .Types import * locations_data = \ {'AboveChargeFlameTreeExp': Location(code=262144, vanilla_item='EX100'), 'AboveChargeJumpAbilityCell': Location(code=262145, vanilla_item='AC'), 'AboveFourthHealth': Location(code=262146, vanilla_item='AC'), 'AboveGrottoTeleporterExp': Location(code=262147, vanilla_item='EX100'), 'BashAreaExp': Location(code=262148, vanilla_item='EX100'), 'BashSkillTree': Location(code=262149, vanilla_item='SKBash'), 'BelowGrottoTeleporterHealthCell': Location(code=262150, vanilla_item='HC'), 'BelowGrottoTeleporterPlant': Location(code=262151, vanilla_item='Plant'), 'BlackrootBoulderExp': Location(code=262152, vanilla_item='EX100'), 'BlackrootMap': Location(code=262153, vanilla_item='MapStone'), 'BlackrootTeleporterHealthCell': Location(code=262154, vanilla_item='HC'), 'ChargeFlameAreaExp': Location(code=262155, vanilla_item='EX100'), 'ChargeFlameAreaPlant': Location(code=262156, vanilla_item='Plant'), 'ChargeFlameSkillTree': Location(code=262157, vanilla_item='SKChargeFlame'), 'ChargeJumpSkillTree': Location(code=262158, vanilla_item='SKChargeJump'), 'ClimbSkillTree': Location(code=262159, vanilla_item='SKClimb'), 'DashAreaAbilityCell': Location(code=262160, vanilla_item='AC'), 'DashAreaMapstone': Location(code=262161, vanilla_item='MS'), 'DashAreaOrbRoomExp': Location(code=262162, vanilla_item='EX100'), 'DashAreaPlant': Location(code=262163, vanilla_item='Plant'), 'DashAreaRoofExp': Location(code=262164, vanilla_item='EX100'), 'DashSkillTree': Location(code=262165, vanilla_item='SKDash'), 'DeathGauntletEnergyCell': Location(code=262166, vanilla_item='EC'), 'DeathGauntletExp': Location(code=262167, vanilla_item='EX100'), 'DeathGauntletRoofHealthCell': Location(code=262168, vanilla_item='HC'), 'DeathGauntletRoofPlant': Location(code=262169, vanilla_item='Plant'), 'DeathGauntletStompSwim': Location(code=262170, vanilla_item='EX200'), 'DeathGauntletSwimEnergyDoor': Location(code=262171, vanilla_item='AC'), 'DoorWarpExp': Location(code=262172, vanilla_item='EX200'), 'DoubleJumpAreaExp': Location(code=262173, vanilla_item='EX100'), 'DoubleJumpSkillTree': Location(code=262174, vanilla_item='SKDoubleJump'), 'FarLeftGumoHideoutExp': Location(code=262175, vanilla_item='EX100'), 'FirstPickup': Location(code=262176, vanilla_item='EX15'), 'ForlornEntranceExp': Location(code=262177, vanilla_item='EX200'), 'ForlornEscape': Location(code=262178, vanilla_item='EVWind'), 'ForlornHiddenSpiderExp': Location(code=262179, vanilla_item='EX100'), 'ForlornKeystone1': Location(code=262180, vanilla_item='KS'), 'ForlornKeystone2': Location(code=262181, vanilla_item='KS'), 'ForlornKeystone3': Location(code=262182, vanilla_item='KS'), 'ForlornKeystone4': Location(code=262183, vanilla_item='KS'), 'ForlornMap': Location(code=262184, vanilla_item='MapStone'), 'ForlornPlant': Location(code=262185, vanilla_item='Plant'), 'FourthHealthCell': Location(code=262186, vanilla_item='HC'), 'FronkeyFight': Location(code=262187, vanilla_item='EX15'), 'FronkeyWalkRoof': Location(code=262188, vanilla_item='EX200'), 'GinsoEscapeExit': Location(code=262189, vanilla_item='EVWater'), 'GinsoEscapeHangingExp': Location(code=262190, vanilla_item='EX100'), 'GinsoEscapeJumpPadExp': Location(code=262191, vanilla_item='EX100'), 'GinsoEscapeProjectileExp': Location(code=262192, vanilla_item='EX100'), 'GinsoEscapeSpiderExp': Location(code=262193, vanilla_item='EX200'), 'GladesGrenadePool': Location(code=262194, vanilla_item='EX200'), 'GladesGrenadeTree': Location(code=262195, vanilla_item='AC'), 'GladesKeystone1': Location(code=262196, vanilla_item='KS'), 'GladesKeystone2': Location(code=262197, vanilla_item='KS'), 'GladesLaser': Location(code=262198, vanilla_item='EC'), 'GladesLaserGrenade': Location(code=262199, vanilla_item='AC'), 'GladesMainPool': Location(code=262200, vanilla_item='EX100'), 'GladesMainPoolDeep': Location(code=262201, vanilla_item='EC'), 'GladesMap': Location(code=262202, vanilla_item='MapStone'), 'GladesMapKeystone': Location(code=262203, vanilla_item='KS'), 'GlideSkillFeather': Location(code=262204, vanilla_item='SKGlide'), 'GrenadeAreaAbilityCell': Location(code=262205, vanilla_item='AC'), 'GrenadeAreaExp': Location(code=262206, vanilla_item='EX100'), 'GrenadeSkillTree': Location(code=262207, vanilla_item='SKGrenade'), 'GrottoEnergyDoorHealthCell': Location(code=262208, vanilla_item='HC'), 'GrottoEnergyDoorSwim': Location(code=262209, vanilla_item='EX100'), 'GrottoHideoutFallAbilityCell': Location(code=262210, vanilla_item='AC'), 'GrottoLasersRoofExp': Location(code=262211, vanilla_item='EX100'), 'GrottoSwampDrainAccessExp': Location(code=262212, vanilla_item='EX100'), 'GrottoSwampDrainAccessPlant': Location(code=262213, vanilla_item='Plant'), 'GroveAboveSpiderWaterEnergyCell': Location(code=262214, vanilla_item='EC'), 'GroveAboveSpiderWaterExp': Location(code=262215, vanilla_item='EX200'), 'GroveAboveSpiderWaterHealthCell': Location(code=262216, vanilla_item='HC'), 'GroveSpiderWaterSwim': Location(code=262217, vanilla_item='EX100'), 'GroveWaterStompAbilityCell': Location(code=262218, vanilla_item='AC'), 'GumoHideoutCrusherExp': Location(code=262219, vanilla_item='EX100'), 'GumoHideoutCrusherKeystone': Location(code=262220, vanilla_item='KS'), 'GumoHideoutEnergyCell': Location(code=262221, vanilla_item='EC'), 'GumoHideoutLeftHangingExp': Location(code=262222, vanilla_item='EX15'), 'GumoHideoutMap': Location(code=262223, vanilla_item='MapStone'), 'GumoHideoutMapstone': Location(code=262224, vanilla_item='MS'), 'GumoHideoutMiniboss': Location(code=262225, vanilla_item='KS'), 'GumoHideoutRedirectAbilityCell': Location(code=262226, vanilla_item='AC'), 'GumoHideoutRedirectEnergyCell': Location(code=262227, vanilla_item='EC'), 'GumoHideoutRedirectExp': Location(code=262228, vanilla_item='EX200'), 'GumoHideoutRedirectPlant': Location(code=262229, vanilla_item='Plant'), 'GumoHideoutRightHangingExp': Location(code=262230, vanilla_item='EX15'), 'GumoHideoutRockfallExp': Location(code=262231, vanilla_item='EX100'), 'GumonSeal': Location(code=262232, vanilla_item='EVForlornKey'), 'HollowGroveMap': Location(code=262233, vanilla_item='MapStone'), 'HollowGroveMapPlant': Location(code=262234, vanilla_item='Plant'), 'HollowGroveMapstone': Location(code=262235, vanilla_item='MS'), 'HollowGroveTreeAbilityCell': Location(code=262236, vanilla_item='AC'), 'HollowGroveTreePlant': Location(code=262237, vanilla_item='Plant'), 'HoruFieldsAbilityCell': Location(code=262238, vanilla_item='AC'), 'HoruFieldsEnergyCell': Location(code=262239, vanilla_item='EC'), 'HoruFieldsHealthCell': Location(code=262240, vanilla_item='HC'), 'HoruFieldsHiddenExp': Location(code=262241, vanilla_item='EX200'), 'HoruFieldsPlant': Location(code=262242, vanilla_item='Plant'), 'HoruL1': Location(code=262243, vanilla_item='CS'), 'HoruL2': Location(code=262244, vanilla_item='CS'), 'HoruL3': Location(code=262245, vanilla_item='CS'), 'HoruL4': Location(code=262246, vanilla_item='CS'), 'HoruL4ChaseExp': Location(code=262247, vanilla_item='EX200'), 'HoruL4LowerExp': Location(code=262248, vanilla_item='EX200'), 'HoruLavaDrainedLeftExp': Location(code=262249, vanilla_item='EX200'), 'HoruLavaDrainedRightExp': Location(code=262250, vanilla_item='EX200'), 'HoruMap': Location(code=262251, vanilla_item='MapStone'), 'HoruR1': Location(code=262252, vanilla_item='CS'), 'HoruR1EnergyCell': Location(code=262253, vanilla_item='EC'), 'HoruR1HangingExp': Location(code=262254, vanilla_item='EX100'), 'HoruR1Mapstone': Location(code=262255, vanilla_item='MS'), 'HoruR2': Location(code=262256, vanilla_item='CS'), 'HoruR3': Location(code=262257, vanilla_item='CS'), 'HoruR3Plant': Location(code=262258, vanilla_item='Plant'), 'HoruR4': Location(code=262259, vanilla_item='CS'), 'HoruR4DrainedExp': Location(code=262260, vanilla_item='EX200'), 'HoruR4LaserExp': Location(code=262261, vanilla_item='EX200'), 'HoruR4StompExp': Location(code=262262, vanilla_item='EX200'), 'HoruTeleporterExp': Location(code=262263, vanilla_item='EX200'), 'IcelessExp': Location(code=262264, vanilla_item='EX100'), 'InnerSwampDrainExp': Location(code=262265, vanilla_item='EX100'), 'InnerSwampEnergyCell': Location(code=262266, vanilla_item='EC'), 'InnerSwampHiddenSwimExp': Location(code=262267, vanilla_item='EX100'), 'InnerSwampStompExp': Location(code=262268, vanilla_item='EX100'), 'InnerSwampSwimLeftKeystone': Location(code=262269, vanilla_item='KS'), 'InnerSwampSwimMapstone': Location(code=262270, vanilla_item='MS'), 'InnerSwampSwimRightKeystone': Location(code=262271, vanilla_item='KS'), 'KuroPerchExp': Location(code=262272, vanilla_item='EX200'), 'LeftGladesExp': Location(code=262273, vanilla_item='EX15'), 'LeftGladesHiddenExp': Location(code=262274, vanilla_item='EX15'), 'LeftGladesKeystone': Location(code=262275, vanilla_item='KS'), 'LeftGladesMapstone': Location(code=262276, vanilla_item='MS'), 'LeftGrottoTeleporterExp': Location(code=262277, vanilla_item='EX200'), 'LeftGumoHideoutExp': Location(code=262278, vanilla_item='EX100'), 'LeftGumoHideoutHealthCell': Location(code=262279, vanilla_item='HC'), 'LeftGumoHideoutLowerPlant': Location(code=262280, vanilla_item='Plant'), 'LeftGumoHideoutSwim': Location(code=262281, vanilla_item='EX100'), 'LeftGumoHideoutUpperPlant': Location(code=262282, vanilla_item='Plant'), 'LeftSorrowAbilityCell': Location(code=262283, vanilla_item='AC'), 'LeftSorrowEnergyCell': Location(code=262284, vanilla_item='EC'), 'LeftSorrowGrenade': Location(code=262285, vanilla_item='EX200'), 'LeftSorrowKeystone1': Location(code=262286, vanilla_item='KS'), 'LeftSorrowKeystone2': Location(code=262287, vanilla_item='KS'), 'LeftSorrowKeystone3': Location(code=262288, vanilla_item='KS'), 'LeftSorrowKeystone4': Location(code=262289, vanilla_item='KS'), 'LeftSorrowPlant': Location(code=262290, vanilla_item='Plant'), 'LostGroveAbilityCell': Location(code=262291, vanilla_item='AC'), 'LostGroveHiddenExp': Location(code=262292, vanilla_item='EX100'), 'LostGroveLongSwim': Location(code=262293, vanilla_item='AC'), 'LostGroveTeleporter': Location(code=262294, vanilla_item='EX100'), 'LowerBlackrootAbilityCell': Location(code=262295, vanilla_item='AC'), 'LowerBlackrootGrenadeThrow': Location(code=262296, vanilla_item='AC'), 'LowerBlackrootLaserAbilityCell': Location(code=262297, vanilla_item='AC'), 'LowerBlackrootLaserExp': Location(code=262298, vanilla_item='EX100'), 'LowerGinsoHiddenExp': Location(code=262299, vanilla_item='EX100'), 'LowerGinsoKeystone1': Location(code=262300, vanilla_item='KS'), 'LowerGinsoKeystone2': Location(code=262301, vanilla_item='KS'), 'LowerGinsoKeystone3': Location(code=262302, vanilla_item='KS'), 'LowerGinsoKeystone4': Location(code=262303, vanilla_item='KS'), 'LowerGinsoPlant': Location(code=262304, vanilla_item='Plant'), 'LowerValleyExp': Location(code=262305, vanilla_item='EX100'), 'LowerValleyMapstone': Location(code=262306, vanilla_item='MS'), 'MistyAbilityCell': Location(code=262307, vanilla_item='AC'), 'MistyEntranceStompExp': Location(code=262308, vanilla_item='EX100'), 'MistyEntranceTreeExp': Location(code=262309, vanilla_item='EX100'), 'MistyFrogNookExp': Location(code=262310, vanilla_item='EX100'), 'MistyGrenade': Location(code=262311, vanilla_item='EX200'), 'MistyKeystone1': Location(code=262312, vanilla_item='KS'), 'MistyKeystone2': Location(code=262313, vanilla_item='KS'), 'MistyKeystone3': Location(code=262314, vanilla_item='KS'), 'MistyKeystone4': Location(code=262315, vanilla_item='KS'), 'MistyMortarCorridorHiddenExp': Location(code=262316, vanilla_item='EX100'), 'MistyMortarCorridorUpperExp': Location(code=262317, vanilla_item='EX100'), 'MistyPlant': Location(code=262318, vanilla_item='Plant'), 'MistyPostClimbAboveSpikePit': Location(code=262319, vanilla_item='EX200'), 'MistyPostClimbSpikeCave': Location(code=262320, vanilla_item='EX100'), 'MoonGrottoStompPlant': Location(code=262321, vanilla_item='Plant'), 'OuterSwampAbilityCell': Location(code=262322, vanilla_item='AC'), 'OuterSwampGrenadeExp': Location(code=262323, vanilla_item='EX200'), 'OuterSwampHealthCell': Location(code=262324, vanilla_item='HC'), 'OuterSwampMortarAbilityCell': Location(code=262325, vanilla_item='AC'), 'OuterSwampMortarPlant': Location(code=262326, vanilla_item='Plant'), 'OuterSwampStompExp': Location(code=262327, vanilla_item='EX100'), 'OutsideForlornCliffExp': Location(code=262328, vanilla_item='EX200'), 'OutsideForlornTreeExp': Location(code=262329, vanilla_item='EX100'), 'OutsideForlornWaterExp': Location(code=262330, vanilla_item='EX100'), 'RazielNo': Location(code=262331, vanilla_item='EX100'), 'RightForlornHealthCell': Location(code=262332, vanilla_item='HC'), 'RightForlornPlant': Location(code=262333, vanilla_item='Plant'), 'SorrowEntranceAbilityCell': Location(code=262334, vanilla_item='AC'), 'SorrowHealthCell': Location(code=262335, vanilla_item='HC'), 'SorrowHiddenKeystone': Location(code=262336, vanilla_item='KS'), 'SorrowLowerLeftKeystone': Location(code=262337, vanilla_item='KS'), 'SorrowMainShaftKeystone': Location(code=262338, vanilla_item='KS'), 'SorrowMap': Location(code=262339, vanilla_item='MapStone'), 'SorrowMapstone': Location(code=262340, vanilla_item='MS'), 'SorrowSpikeKeystone': Location(code=262341, vanilla_item='KS'), 'SpiderSacEnergyCell': Location(code=262342, vanilla_item='EC'), 'SpiderSacEnergyDoor': Location(code=262343, vanilla_item='AC'), 'SpiderSacGrenadeDoor': Location(code=262344, vanilla_item='AC'), 'SpiderSacHealthCell': Location(code=262345, vanilla_item='HC'), 'SpiritCavernsAbilityCell': Location(code=262346, vanilla_item='AC'), 'SpiritCavernsKeystone1': Location(code=262347, vanilla_item='KS'), 'SpiritCavernsKeystone2': Location(code=262348, vanilla_item='KS'), 'SpiritCavernsTopLeftKeystone': Location(code=262349, vanilla_item='KS'), 'SpiritCavernsTopRightKeystone': Location(code=262350, vanilla_item='KS'), 'StompAreaExp': Location(code=262351, vanilla_item='EX100'), 'StompAreaGrenadeExp': Location(code=262352, vanilla_item='EX200'), 'StompAreaRoofExp': Location(code=262353, vanilla_item='EX200'), 'StompSkillTree': Location(code=262354, vanilla_item='SKStomp'), 'Sunstone': Location(code=262355, vanilla_item='EVHoruKey'), 'SunstonePlant': Location(code=262356, vanilla_item='Plant'), 'SwampEntranceAbilityCell': Location(code=262357, vanilla_item='AC'), 'SwampEntrancePlant': Location(code=262358, vanilla_item='Plant'), 'SwampEntranceSwim': Location(code=262359, vanilla_item='EX200'), 'SwampMap': Location(code=262360, vanilla_item='MapStone'), 'SwampTeleporterAbilityCell': Location(code=262361, vanilla_item='AC'), 'TopGinsoLeftLowerExp': Location(code=262362, vanilla_item='EX100'), 'TopGinsoLeftUpperExp': Location(code=262363, vanilla_item='EX100'), 'TopGinsoRightPlant': Location(code=262364, vanilla_item='Plant'), 'UpperGinsoEnergyCell': Location(code=262365, vanilla_item='EC'), 'UpperGinsoLowerKeystone': Location(code=262366, vanilla_item='KS'), 'UpperGinsoRedirectLowerExp': Location(code=262367, vanilla_item='EX100'), 'UpperGinsoRedirectUpperExp': Location(code=262368, vanilla_item='EX100'), 'UpperGinsoRightKeystone': Location(code=262369, vanilla_item='KS'), 'UpperGinsoUpperLeftKeystone': Location(code=262370, vanilla_item='KS'), 'UpperGinsoUpperRightKeystone': Location(code=262371, vanilla_item='KS'), 'UpperSorrowFarLeftKeystone': Location(code=262372, vanilla_item='KS'), 'UpperSorrowFarRightKeystone': Location(code=262373, vanilla_item='KS'), 'UpperSorrowLeftKeystone': Location(code=262374, vanilla_item='KS'), 'UpperSorrowRightKeystone': Location(code=262375, vanilla_item='KS'), 'UpperSorrowSpikeExp': Location(code=262376, vanilla_item='EX100'), 'ValleyEntryAbilityCell': Location(code=262377, vanilla_item='AC'), 'ValleyEntryGrenadeLongSwim': Location(code=262378, vanilla_item='EC'), 'ValleyEntryTreeExp': Location(code=262379, vanilla_item='EX100'), 'ValleyEntryTreePlant': Location(code=262380, vanilla_item='Plant'), 'ValleyForlornApproachGrenade': Location(code=262381, vanilla_item='AC'), 'ValleyForlornApproachMapstone': Location(code=262382, vanilla_item='MS'), 'ValleyMainFACS': Location(code=262383, vanilla_item='AC'), 'ValleyMainPlant': Location(code=262384, vanilla_item='Plant'), 'ValleyMap': Location(code=262385, vanilla_item='MapStone'), 'ValleyRightBirdStompCell': Location(code=262386, vanilla_item='AC'), 'ValleyRightExp': Location(code=262387, vanilla_item='EX100'), 'ValleyRightFastStomplessCell': Location(code=262388, vanilla_item='AC'), 'ValleyRightSwimExp': Location(code=262389, vanilla_item='EX100'), 'ValleyThreeBirdAbilityCell': Location(code=262390, vanilla_item='AC'), 'WallJumpAreaEnergyCell': Location(code=262391, vanilla_item='EC'), 'WallJumpAreaExp': Location(code=262392, vanilla_item='EX200'), 'WallJumpSkillTree': Location(code=262393, vanilla_item='SKWallJump'), 'WaterVein': Location(code=262394, vanilla_item='EVGinsoKey'), 'WilhelmExp': Location(code=262395, vanilla_item='EX200')} lookup_name_to_id = {location_name: location_data.code for location_name, location_data in locations_data.items()}<file_sep>from typing import NamedTuple, Union import logging from ..AutoWorld import World class GenericWorld(World): game = "Archipelago" topology_present = False item_name_to_id = { "Nothing": -1 } location_name_to_id = { "Cheat Console" : -1, "Server": -2 } hidden = True class PlandoItem(NamedTuple): item: str location: str world: Union[bool, str] = False # False -> own world, True -> not own world from_pool: bool = True # if item should be removed from item pool force: str = 'silent' # false -> warns if item not successfully placed. true -> errors out on failure to place item. def warn(self, warning: str): if self.force in ['true', 'fail', 'failure', 'none', 'false', 'warn', 'warning']: logging.warning(f'{warning}') else: logging.debug(f'{warning}') def failed(self, warning: str, exception=Exception): if self.force in ['true', 'fail', 'failure']: raise exception(warning) else: self.warn(warning) class PlandoConnection(NamedTuple): entrance: str exit: str direction: str # entrance, exit or both <file_sep># generated by https://github.com/Berserker66/ori_rando_server # do not edit manually from typing import Dict item_table: Dict[str, int] = \ {'EX100': 262144, 'AC': 262145, 'Bash': 262146, 'HC': 262147, 'Plant': 262148, 'MapStone': 262149, 'ChargeFlame': 262150, 'ChargeJump': 262151, 'Climb': 262152, 'MS': 262153, 'Dash': 262154, 'EC': 262155, 'EX200': 262156, 'DoubleJump': 262157, 'EX15': 262158, 'Wind': 262159, 'KS': 262160, 'Water': 262161, 'Glide': 262162, 'Grenade': 262163, 'ForlornKey': 262164, 'CS': 262165, 'Stomp': 262166, 'HoruKey': 262167, 'WallJump': 262168, 'GinsoKey': 262169} default_pool: Dict[str, int] = \ {'EX100': 53, 'AC': 33, 'Bash': 1, 'HC': 12, 'Plant': 24, 'MapStone': 9, 'ChargeFlame': 1, 'ChargeJump': 1, 'Climb': 1, 'MS': 9, 'Dash': 1, 'EC': 14, 'EX200': 29, 'DoubleJump': 1, 'EX15': 6, 'Wind': 1, 'KS': 40, 'Water': 1, 'Glide': 1, 'Grenade': 1, 'ForlornKey': 1, 'CS': 8, 'Stomp': 1, 'HoruKey': 1, 'WallJump': 1, 'GinsoKey': 1}<file_sep>import argparse import logging import random import urllib.request import urllib.parse import typing import os from collections import Counter import string import ModuleUpdate ModuleUpdate.update() from worlds.alttp import Options as LttPOptions from worlds.generic import PlandoItem, PlandoConnection from Utils import parse_yaml, version_tuple, __version__, tuplize_version, get_options from worlds.alttp.EntranceRandomizer import parse_arguments from Main import main as ERmain from BaseClasses import seeddigits, get_seed import Options from worlds.alttp import Bosses from worlds.alttp.Text import TextTable from worlds.AutoWorld import AutoWorldRegister categories = set(AutoWorldRegister.world_types) def mystery_argparse(): options = get_options() defaults = options["generator"] parser = argparse.ArgumentParser(description="CMD Generation Interface, defaults come from host.yaml.") parser.add_argument('--weights_file_path', default = defaults["weights_file_path"], help='Path to the weights file to use for rolling game settings, urls are also valid') parser.add_argument('--samesettings', help='Rolls settings per weights file rather than per player', action='store_true') parser.add_argument('--player_files_path', default=defaults["player_files_path"], help="Input directory for player files.") parser.add_argument('--seed', help='Define seed number to generate.', type=int) parser.add_argument('--multi', default=defaults["players"], type=lambda value: max(int(value), 1)) parser.add_argument('--spoiler', type=int, default=defaults["spoiler"]) parser.add_argument('--rom', default=options["lttp_options"]["rom_file"], help="Path to the 1.0 JP LttP Baserom.") parser.add_argument('--enemizercli', default=defaults["enemizer_path"]) parser.add_argument('--outputpath', default=options["general_options"]["output_path"]) parser.add_argument('--race', action='store_true', default=defaults["race"]) parser.add_argument('--meta_file_path', default=defaults["meta_file_path"]) parser.add_argument('--log_output_path', help='Path to store output log') parser.add_argument('--log_level', default='info', help='Sets log level') parser.add_argument('--yaml_output', default=0, type=lambda value: max(int(value), 0), help='Output rolled mystery results to yaml up to specified number (made for async multiworld)') parser.add_argument('--plando', default=defaults["plando_options"], help='List of options that can be set manually. Can be combined, for example "bosses, items"') args = parser.parse_args() if not os.path.isabs(args.weights_file_path): args.weights_file_path = os.path.join(args.player_files_path, args.weights_file_path) if not os.path.isabs(args.meta_file_path): args.meta_file_path = os.path.join(args.player_files_path, args.meta_file_path) args.plando: typing.Set[str] = {arg.strip().lower() for arg in args.plando.split(",")} return args, options def get_seed_name(random): return f"{random.randint(0, pow(10, seeddigits) - 1)}".zfill(seeddigits) def main(args=None, callback=ERmain): if not args: args, options = mystery_argparse() seed = get_seed(args.seed) random.seed(seed) seed_name = get_seed_name(random) if args.race: random.seed() # reset to time-based random source weights_cache = {} if args.weights_file_path and os.path.exists(args.weights_file_path): try: weights_cache[args.weights_file_path] = read_weights_yaml(args.weights_file_path) except Exception as e: raise ValueError(f"File {args.weights_file_path} is destroyed. Please fix your yaml.") from e print(f"Weights: {args.weights_file_path} >> " f"{get_choice('description', weights_cache[args.weights_file_path], 'No description specified')}") if args.meta_file_path and os.path.exists(args.meta_file_path): try: weights_cache[args.meta_file_path] = read_weights_yaml(args.meta_file_path) except Exception as e: raise ValueError(f"File {args.meta_file_path} is destroyed. Please fix your yaml.") from e meta_weights = weights_cache[args.meta_file_path] print(f"Meta: {args.meta_file_path} >> {get_choice('meta_description', meta_weights, 'No description specified')}") if args.samesettings: raise Exception("Cannot mix --samesettings with --meta") else: meta_weights = None player_id = 1 player_files = {} for file in os.scandir(args.player_files_path): fname = file.name if file.is_file() and os.path.join(args.player_files_path, fname) not in {args.meta_file_path, args.weights_file_path}: path = os.path.join(args.player_files_path, fname) try: weights_cache[fname] = read_weights_yaml(path) except Exception as e: raise ValueError(f"File {fname} is destroyed. Please fix your yaml.") from e else: print(f"P{player_id} Weights: {fname} >> " f"{get_choice('description', weights_cache[fname], 'No description specified')}") player_files[player_id] = fname player_id += 1 args.multi = max(player_id-1, args.multi) print(f"Generating for {args.multi} player{'s' if args.multi > 1 else ''}, {seed_name} Seed {seed} with plando: " f"{', '.join(args.plando)}") if not weights_cache: raise Exception(f"No weights found. Provide a general weights file ({args.weights_file_path}) or individual player files. " f"A mix is also permitted.") erargs = parse_arguments(['--multi', str(args.multi)]) erargs.seed = seed erargs.glitch_triforce = options["generator"]["glitch_triforce_room"] erargs.spoiler = args.spoiler erargs.race = args.race erargs.outputname = seed_name erargs.outputpath = args.outputpath # set up logger if args.log_level: erargs.loglevel = args.log_level loglevel = {'error': logging.ERROR, 'info': logging.INFO, 'warning': logging.WARNING, 'debug': logging.DEBUG}[ erargs.loglevel] if args.log_output_path: os.makedirs(args.log_output_path, exist_ok=True) logging.basicConfig(format='%(message)s', level=loglevel, force=True, filename=os.path.join(args.log_output_path, f"{seed}.log")) else: logging.basicConfig(format='%(message)s', level=loglevel, force=True) erargs.rom = args.rom erargs.enemizercli = args.enemizercli settings_cache = {k: (roll_settings(v, args.plando) if args.samesettings else None) for k, v in weights_cache.items()} player_path_cache = {} for player in range(1, args.multi + 1): player_path_cache[player] = player_files.get(player, args.weights_file_path) if meta_weights: for player, path in player_path_cache.items(): weights_cache[path].setdefault("meta_ignore", []) for key in meta_weights: option = get_choice(key, meta_weights) if option is not None: for player, path in player_path_cache.items(): players_meta = weights_cache[path].get("meta_ignore", []) if key not in players_meta: weights_cache[path][key] = option elif type(players_meta) == dict and players_meta[key] and option not in players_meta[key]: weights_cache[path][key] = option name_counter = Counter() erargs.player_settings = {} for player in range(1, args.multi + 1): path = player_path_cache[player] if path: try: settings = settings_cache[path] if settings_cache[path] else \ roll_settings(weights_cache[path], args.plando) for k, v in vars(settings).items(): if v is not None: try: getattr(erargs, k)[player] = v except AttributeError: setattr(erargs, k, {player: v}) except Exception as e: raise Exception(f"Error setting {k} to {v} for player {player}") from e except Exception as e: raise ValueError(f"File {path} is destroyed. Please fix your yaml.") from e else: raise RuntimeError(f'No weights specified for player {player}') if path == args.weights_file_path: # if name came from the weights file, just use base player name erargs.name[player] = f"Player{player}" elif not erargs.name[player]: # if name was not specified, generate it from filename erargs.name[player] = os.path.splitext(os.path.split(path)[-1])[0] erargs.name[player] = handle_name(erargs.name[player], player, name_counter) if len(set(erargs.name.values())) != len(erargs.name): raise Exception(f"Names have to be unique. Names: {erargs.name}") if args.yaml_output: import yaml important = {} for option, player_settings in vars(erargs).items(): if type(player_settings) == dict: if all(type(value) != list for value in player_settings.values()): if len(player_settings.values()) > 1: important[option] = {player: value for player, value in player_settings.items() if player <= args.yaml_output} elif len(player_settings.values()) > 0: important[option] = player_settings[1] else: logging.debug(f"No player settings defined for option '{option}'") else: if player_settings != "": # is not empty name important[option] = player_settings else: logging.debug(f"No player settings defined for option '{option}'") if args.outputpath: os.makedirs(args.outputpath, exist_ok=True) with open(os.path.join(args.outputpath if args.outputpath else ".", f"generate_{seed_name}.yaml"), "wt") as f: yaml.dump(important, f) callback(erargs, seed) def read_weights_yaml(path): try: if urllib.parse.urlparse(path).scheme: yaml = str(urllib.request.urlopen(path).read(), "utf-8") else: with open(path, 'rb') as f: yaml = str(f.read(), "utf-8") except Exception as e: raise Exception(f"Failed to read weights ({path})") from e return parse_yaml(yaml) def interpret_on_off(value): return {"on": True, "off": False}.get(value, value) def convert_to_on_off(value): return {True: "on", False: "off"}.get(value, value) def get_choice_legacy(option, root, value=None) -> typing.Any: if option not in root: return value if type(root[option]) is list: return interpret_on_off(random.choices(root[option])[0]) if type(root[option]) is not dict: return interpret_on_off(root[option]) if not root[option]: return value if any(root[option].values()): return interpret_on_off( random.choices(list(root[option].keys()), weights=list(map(int, root[option].values())))[0]) raise RuntimeError(f"All options specified in \"{option}\" are weighted as zero.") def get_choice(option, root, value=None) -> typing.Any: if option not in root: return value if type(root[option]) is list: return random.choices(root[option])[0] if type(root[option]) is not dict: return root[option] if not root[option]: return value if any(root[option].values()): return random.choices(list(root[option].keys()), weights=list(map(int, root[option].values())))[0] raise RuntimeError(f"All options specified in \"{option}\" are weighted as zero.") class SafeDict(dict): def __missing__(self, key): return '{' + key + '}' def handle_name(name: str, player: int, name_counter: Counter): name_counter[name] += 1 new_name = "%".join([x.replace("%number%", "{number}").replace("%player%", "{player}") for x in name.split("%%")]) new_name = string.Formatter().vformat(new_name, (), SafeDict(number=name_counter[name], NUMBER=(name_counter[name] if name_counter[ name] > 1 else ''), player=player, PLAYER=(player if player > 1 else ''))) new_name = new_name.strip()[:16] if new_name == "Archipelago": raise Exception(f"You cannot name yourself \"{new_name}\"") return new_name def prefer_int(input_data: str) -> typing.Union[str, int]: try: return int(input_data) except: return input_data available_boss_names: typing.Set[str] = {boss.lower() for boss in Bosses.boss_table if boss not in {'Agahnim', 'Agahnim2', 'Ganon'}} available_boss_locations: typing.Set[str] = {f"{loc.lower()}{f' {level}' if level else ''}" for loc, level in Bosses.boss_location_table} boss_shuffle_options = {None: 'none', 'none': 'none', 'basic': 'basic', 'full': 'full', 'chaos': 'chaos', 'singularity': 'singularity' } goals = { 'ganon': 'ganon', 'crystals': 'crystals', 'bosses': 'bosses', 'pedestal': 'pedestal', 'ganon_pedestal': 'ganonpedestal', 'triforce_hunt': 'triforcehunt', 'local_triforce_hunt': 'localtriforcehunt', 'ganon_triforce_hunt': 'ganontriforcehunt', 'local_ganon_triforce_hunt': 'localganontriforcehunt', 'ice_rod_hunt': 'icerodhunt', } def roll_percentage(percentage: typing.Union[int, float]) -> bool: """Roll a percentage chance. percentage is expected to be in range [0, 100]""" return random.random() < (float(percentage) / 100) def update_weights(weights: dict, new_weights: dict, type: str, name: str) -> dict: logging.debug(f'Applying {new_weights}') new_options = set(new_weights) - set(weights) weights.update(new_weights) if new_options: for new_option in new_options: logging.warning(f'{type} Suboption "{new_option}" of "{name}" did not ' f'overwrite a root option. ' f'This is probably in error.') return weights def roll_linked_options(weights: dict) -> dict: weights = weights.copy() # make sure we don't write back to other weights sets in same_settings for option_set in weights["linked_options"]: if "name" not in option_set: raise ValueError("One of your linked options does not have a name.") try: if roll_percentage(option_set["percentage"]): logging.debug(f"Linked option {option_set['name']} triggered.") new_options = option_set["options"] for category_name, category_options in new_options.items(): currently_targeted_weights = weights if category_name: currently_targeted_weights = currently_targeted_weights[category_name] update_weights(currently_targeted_weights, category_options, "Linked", option_set["name"]) else: logging.debug(f"linked option {option_set['name']} skipped.") except Exception as e: raise ValueError(f"Linked option {option_set['name']} is destroyed. " f"Please fix your linked option.") from e return weights def roll_triggers(weights: dict, triggers: list) -> dict: weights = weights.copy() # make sure we don't write back to other weights sets in same_settings weights["_Generator_Version"] = "Archipelago" # Some means for triggers to know if the seed is on main or doors. for i, option_set in enumerate(triggers): try: currently_targeted_weights = weights category = option_set.get("option_category", None) if category: currently_targeted_weights = currently_targeted_weights[category] key = get_choice("option_name", option_set) if key not in currently_targeted_weights: logging.warning(f'Specified option name {option_set["option_name"]} did not ' f'match with a root option. ' f'This is probably in error.') trigger_result = get_choice("option_result", option_set) result = get_choice(key, currently_targeted_weights) currently_targeted_weights[key] = result if result == trigger_result and roll_percentage(get_choice("percentage", option_set, 100)): for category_name, category_options in option_set["options"].items(): currently_targeted_weights = weights if category_name: currently_targeted_weights = currently_targeted_weights[category_name] update_weights(currently_targeted_weights, category_options, "Triggered", option_set["option_name"]) except Exception as e: raise ValueError(f"Your trigger number {i + 1} is destroyed. " f"Please fix your triggers.") from e return weights def get_plando_bosses(boss_shuffle: str, plando_options: typing.Set[str]) -> str: if boss_shuffle in boss_shuffle_options: return boss_shuffle_options[boss_shuffle] elif "bosses" in plando_options: options = boss_shuffle.lower().split(";") remainder_shuffle = "none" # vanilla bosses = [] for boss in options: if boss in boss_shuffle_options: remainder_shuffle = boss_shuffle_options[boss] elif "-" in boss: loc, boss_name = boss.split("-") if boss_name not in available_boss_names: raise ValueError(f"Unknown Boss name {boss_name}") if loc not in available_boss_locations: raise ValueError(f"Unknown Boss Location {loc}") level = '' if loc.split(" ")[-1] in {"top", "middle", "bottom"}: # split off level loc = loc.split(" ") level = f" {loc[-1]}" loc = " ".join(loc[:-1]) loc = loc.title().replace("Of", "of") if not Bosses.can_place_boss(boss_name.title(), loc, level): raise ValueError(f"Cannot place {boss_name} at {loc}{level}") bosses.append(boss) elif boss not in available_boss_names: raise ValueError(f"Unknown Boss name or Boss shuffle option {boss}.") else: bosses.append(boss) return ";".join(bosses + [remainder_shuffle]) else: raise Exception(f"Boss Shuffle {boss_shuffle} is unknown and boss plando is turned off.") def handle_option(ret: argparse.Namespace, game_weights: dict, option_key: str, option: type(Options.Option)): if option_key in game_weights: try: if not option.supports_weighting: player_option = option.from_any(game_weights[option_key]) else: player_option = option.from_any(get_choice(option_key, game_weights)) setattr(ret, option_key, player_option) except Exception as e: raise Exception(f"Error generating option {option_key} in {ret.game}") from e else: # verify item names existing if getattr(player_option, "verify_item_name", False): for item_name in player_option.value: if item_name not in AutoWorldRegister.world_types[ret.game].item_names: raise Exception(f"Item {item_name} from option {player_option} " f"is not a valid item name from {ret.game}") elif getattr(player_option, "verify_location_name", False): for location_name in player_option.value: if location_name not in AutoWorldRegister.world_types[ret.game].location_names: raise Exception(f"Location {location_name} from option {player_option} " f"is not a valid location name from {ret.game}") else: setattr(ret, option_key, option(option.default)) def roll_settings(weights: dict, plando_options: typing.Set[str] = frozenset(("bosses",))): if "linked_options" in weights: weights = roll_linked_options(weights) if "triggers" in weights: weights = roll_triggers(weights, weights["triggers"]) requirements = weights.get("requires", {}) if requirements: version = requirements.get("version", __version__) if tuplize_version(version) > version_tuple: raise Exception(f"Settings reports required version of generator is at least {version}, " f"however generator is of version {__version__}") required_plando_options = requirements.get("plando", "") if required_plando_options: required_plando_options = set(option.strip() for option in required_plando_options.split(",")) required_plando_options -= plando_options if required_plando_options: if len(required_plando_options) == 1: raise Exception(f"Settings reports required plando module {', '.join(required_plando_options)}, " f"which is not enabled.") else: raise Exception(f"Settings reports required plando modules {', '.join(required_plando_options)}, " f"which are not enabled.") ret = argparse.Namespace() for option_key in Options.per_game_common_options: if option_key in weights: raise Exception(f"Option {option_key} has to be in a game's section, not on its own.") ret.game = get_choice("game", weights) if ret.game not in weights: raise Exception(f"No game options for selected game \"{ret.game}\" found.") world_type = AutoWorldRegister.world_types[ret.game] game_weights = weights[ret.game] if "triggers" in game_weights: weights = roll_triggers(weights, game_weights["triggers"]) game_weights = weights[ret.game] ret.name = get_choice('name', weights) for option_key, option in Options.common_options.items(): setattr(ret, option_key, option.from_any(get_choice(option_key, weights, option.default))) if ret.game in AutoWorldRegister.world_types: for option_key, option in world_type.options.items(): handle_option(ret, game_weights, option_key, option) for option_key, option in Options.per_game_common_options.items(): handle_option(ret, game_weights, option_key, option) if "items" in plando_options: ret.plando_items = roll_item_plando(world_type, game_weights) if ret.game == "Minecraft": # bad hardcoded behavior to make this work for now ret.plando_connections = [] if "connections" in plando_options: options = game_weights.get("plando_connections", []) for placement in options: if roll_percentage(get_choice("percentage", placement, 100)): ret.plando_connections.append(PlandoConnection( get_choice("entrance", placement), get_choice("exit", placement), get_choice("direction", placement, "both") )) elif ret.game == "A Link to the Past": roll_alttp_settings(ret, game_weights, plando_options) else: raise Exception(f"Unsupported game {ret.game}") return ret def roll_item_plando(world_type, weights): plando_items = [] def add_plando_item(item: str, location: str): if item not in world_type.item_name_to_id: raise Exception(f"Could not plando item {item} as the item was not recognized") if location not in world_type.location_name_to_id: raise Exception( f"Could not plando item {item} at location {location} as the location was not recognized") plando_items.append(PlandoItem(item, location, location_world, from_pool, force)) options = weights.get("plando_items", []) for placement in options: if roll_percentage(get_choice_legacy("percentage", placement, 100)): from_pool = get_choice_legacy("from_pool", placement, PlandoItem._field_defaults["from_pool"]) location_world = get_choice_legacy("world", placement, PlandoItem._field_defaults["world"]) force = str(get_choice_legacy("force", placement, PlandoItem._field_defaults["force"])).lower() if "items" in placement and "locations" in placement: items = placement["items"] locations = placement["locations"] if isinstance(items, dict): item_list = [] for key, value in items.items(): item_list += [key] * value items = item_list if not items or not locations: raise Exception("You must specify at least one item and one location to place items.") random.shuffle(items) random.shuffle(locations) for item, location in zip(items, locations): add_plando_item(item, location) else: item = get_choice_legacy("item", placement, get_choice_legacy("items", placement)) location = get_choice_legacy("location", placement) add_plando_item(item, location) return plando_items def roll_alttp_settings(ret: argparse.Namespace, weights, plando_options): if "dungeon_items" in weights and get_choice_legacy('dungeon_items', weights, "none") != "none": raise Exception(f"dungeon_items key in A Link to the Past was removed, but is present in these weights as {get_choice_legacy('dungeon_items', weights, False)}.") glitches_required = get_choice_legacy('glitches_required', weights) if glitches_required not in [None, 'none', 'no_logic', 'overworld_glitches', 'hybrid_major_glitches', 'minor_glitches']: logging.warning("Only NMG, OWG, HMG and No Logic supported") glitches_required = 'none' ret.logic = {None: 'noglitches', 'none': 'noglitches', 'no_logic': 'nologic', 'overworld_glitches': 'owglitches', 'minor_glitches': 'minorglitches', 'hybrid_major_glitches': 'hybridglitches'}[ glitches_required] ret.dark_room_logic = get_choice_legacy("dark_room_logic", weights, "lamp") if not ret.dark_room_logic: # None/False ret.dark_room_logic = "none" if ret.dark_room_logic == "sconces": ret.dark_room_logic = "torches" if ret.dark_room_logic not in {"lamp", "torches", "none"}: raise ValueError(f"Unknown Dark Room Logic: \"{ret.dark_room_logic}\"") entrance_shuffle = get_choice_legacy('entrance_shuffle', weights, 'vanilla') if entrance_shuffle.startswith('none-'): ret.shuffle = 'vanilla' else: ret.shuffle = entrance_shuffle if entrance_shuffle != 'none' else 'vanilla' goal = get_choice_legacy('goals', weights, 'ganon') ret.goal = goals[goal] # TODO consider moving open_pyramid to an automatic variable in the core roller, set to True when # fast ganon + ganon at hole ret.open_pyramid = get_choice_legacy('open_pyramid', weights, 'goal') extra_pieces = get_choice_legacy('triforce_pieces_mode', weights, 'available') ret.triforce_pieces_required = LttPOptions.TriforcePieces.from_any(get_choice_legacy('triforce_pieces_required', weights, 20)) # sum a percentage to required if extra_pieces == 'percentage': percentage = max(100, float(get_choice_legacy('triforce_pieces_percentage', weights, 150))) / 100 ret.triforce_pieces_available = int(round(ret.triforce_pieces_required * percentage, 0)) # vanilla mode (specify how many pieces are) elif extra_pieces == 'available': ret.triforce_pieces_available = LttPOptions.TriforcePieces.from_any( get_choice_legacy('triforce_pieces_available', weights, 30)) # required pieces + fixed extra elif extra_pieces == 'extra': extra_pieces = max(0, int(get_choice_legacy('triforce_pieces_extra', weights, 10))) ret.triforce_pieces_available = ret.triforce_pieces_required + extra_pieces # change minimum to required pieces to avoid problems ret.triforce_pieces_available = min(max(ret.triforce_pieces_required, int(ret.triforce_pieces_available)), 90) ret.shop_shuffle = get_choice_legacy('shop_shuffle', weights, '') if not ret.shop_shuffle: ret.shop_shuffle = '' ret.mode = get_choice_legacy("mode", weights) ret.difficulty = get_choice_legacy('item_pool', weights) ret.item_functionality = get_choice_legacy('item_functionality', weights) boss_shuffle = get_choice_legacy('boss_shuffle', weights) ret.shufflebosses = get_plando_bosses(boss_shuffle, plando_options) ret.enemy_damage = {None: 'default', 'default': 'default', 'shuffled': 'shuffled', 'random': 'chaos', # to be removed 'chaos': 'chaos', }[get_choice_legacy('enemy_damage', weights)] ret.enemy_health = get_choice_legacy('enemy_health', weights) ret.timer = {'none': False, None: False, False: False, 'timed': 'timed', 'timed_ohko': 'timed-ohko', 'ohko': 'ohko', 'timed_countdown': 'timed-countdown', 'display': 'display'}[get_choice_legacy('timer', weights, False)] ret.countdown_start_time = int(get_choice_legacy('countdown_start_time', weights, 10)) ret.red_clock_time = int(get_choice_legacy('red_clock_time', weights, -2)) ret.blue_clock_time = int(get_choice_legacy('blue_clock_time', weights, 2)) ret.green_clock_time = int(get_choice_legacy('green_clock_time', weights, 4)) ret.dungeon_counters = get_choice_legacy('dungeon_counters', weights, 'default') ret.shuffle_prizes = get_choice_legacy('shuffle_prizes', weights, "g") ret.required_medallions = [get_choice_legacy("misery_mire_medallion", weights, "random"), get_choice_legacy("turtle_rock_medallion", weights, "random")] for index, medallion in enumerate(ret.required_medallions): ret.required_medallions[index] = {"ether": "Ether", "quake": "Quake", "bombos": "Bombos", "random": "random"} \ .get(medallion.lower(), None) if not ret.required_medallions[index]: raise Exception(f"unknown Medallion {medallion} for {'misery mire' if index == 0 else 'turtle rock'}") ret.plando_texts = {} if "texts" in plando_options: tt = TextTable() tt.removeUnwantedText() options = weights.get("plando_texts", []) for placement in options: if roll_percentage(get_choice_legacy("percentage", placement, 100)): at = str(get_choice_legacy("at", placement)) if at not in tt: raise Exception(f"No text target \"{at}\" found.") ret.plando_texts[at] = str(get_choice_legacy("text", placement)) ret.plando_connections = [] if "connections" in plando_options: options = weights.get("plando_connections", []) for placement in options: if roll_percentage(get_choice_legacy("percentage", placement, 100)): ret.plando_connections.append(PlandoConnection( get_choice_legacy("entrance", placement), get_choice_legacy("exit", placement), get_choice_legacy("direction", placement, "both") )) ret.sprite_pool = weights.get('sprite_pool', []) ret.sprite = get_choice_legacy('sprite', weights, "Link") if 'random_sprite_on_event' in weights: randomoneventweights = weights['random_sprite_on_event'] if get_choice_legacy('enabled', randomoneventweights, False): ret.sprite = 'randomon' ret.sprite += '-hit' if get_choice_legacy('on_hit', randomoneventweights, True) else '' ret.sprite += '-enter' if get_choice_legacy('on_enter', randomoneventweights, False) else '' ret.sprite += '-exit' if get_choice_legacy('on_exit', randomoneventweights, False) else '' ret.sprite += '-slash' if get_choice_legacy('on_slash', randomoneventweights, False) else '' ret.sprite += '-item' if get_choice_legacy('on_item', randomoneventweights, False) else '' ret.sprite += '-bonk' if get_choice_legacy('on_bonk', randomoneventweights, False) else '' ret.sprite = 'randomonall' if get_choice_legacy('on_everything', randomoneventweights, False) else ret.sprite ret.sprite = 'randomonnone' if ret.sprite == 'randomon' else ret.sprite if (not ret.sprite_pool or get_choice_legacy('use_weighted_sprite_pool', randomoneventweights, False)) \ and 'sprite' in weights: # Use sprite as a weighted sprite pool, if a sprite pool is not already defined. for key, value in weights['sprite'].items(): if key.startswith('random'): ret.sprite_pool += ['random'] * int(value) else: ret.sprite_pool += [key] * int(value) if __name__ == '__main__': import atexit confirmation = atexit.register(input, "Press enter to close.") main() # in case of error-free exit should not need confirmation atexit.unregister(confirmation) <file_sep>bsdiff4>=1.2.1 maseya-z3pr>=1.0.0rc1 xxtea>=2.0.0.post0<file_sep>import json import os with open(os.path.join(os.path.dirname(__file__), 'items.json'), 'r') as file: item_table = json.loads(file.read()) lookup_id_to_name = {} lookup_name_to_item = {} advancement_item_names = set() non_advancement_item_names = set() for item in item_table: item_name = item["name"] lookup_id_to_name[item["id"]] = item_name lookup_name_to_item[item_name] = item if item["progression"]: advancement_item_names.add(item_name) else: non_advancement_item_names.add(item_name) lookup_id_to_name[None] = "Victory" lookup_name_to_id = {name: id for id, name in lookup_id_to_name.items()}<file_sep>import os from Utils import __version__ from jinja2 import Template import yaml import json from worlds.AutoWorld import AutoWorldRegister import Options target_folder = os.path.join("WebHostLib", "static", "generated") def create(): def dictify_range(option): data = {option.range_start: 0, option.range_end: 0, "random": 0, "random-low": 0, "random-high": 0, option.default: 50} notes = { option.range_start: "minimum value", option.range_end: "maximum value" } return data, notes def default_converter(default_value): if isinstance(default_value, (set, frozenset)): return list(default_value) return default_value for game_name, world in AutoWorldRegister.world_types.items(): res = Template(open(os.path.join("WebHostLib", "templates", "options.yaml")).read()).render( options={**world.options, **Options.per_game_common_options}, __version__=__version__, game=game_name, yaml_dump=yaml.dump, dictify_range=dictify_range, default_converter=default_converter, ) os.makedirs(os.path.join(target_folder, 'configs'), exist_ok=True) with open(os.path.join(target_folder, 'configs', game_name + ".yaml"), "w") as f: f.write(res) # Generate JSON files for player-settings pages player_settings = { "baseOptions": { "description": "Generated by https://archipelago.gg/", "game": game_name, "name": "Player", }, } game_options = {} for option_name, option in world.options.items(): if option.options: this_option = { "type": "select", "displayName": option.displayname if hasattr(option, "displayname") else option_name, "description": option.__doc__ if option.__doc__ else "Please document me!", "defaultValue": None, "options": [] } for sub_option_id, sub_option_name in option.name_lookup.items(): this_option["options"].append({ "name": option.get_option_name(sub_option_id), "value": sub_option_name, }) if sub_option_id == option.default: this_option["defaultValue"] = sub_option_name game_options[option_name] = this_option elif hasattr(option, "range_start") and hasattr(option, "range_end"): game_options[option_name] = { "type": "range", "displayName": option.displayname if hasattr(option, "displayname") else option_name, "description": option.__doc__ if option.__doc__ else "Please document me!", "defaultValue": option.default if hasattr(option, "default") else option.range_start, "min": option.range_start, "max": option.range_end, } player_settings["gameOptions"] = game_options os.makedirs(os.path.join(target_folder, 'player-settings'), exist_ok=True) with open(os.path.join(target_folder, 'player-settings', game_name + ".json"), "w") as f: f.write(json.dumps(player_settings, indent=2, separators=(',', ': '))) <file_sep>from ..generic.Rules import set_rule from .Locations import location_table import logging import math def has_seaglide(state, player): return state.has("Seaglide Fragment", player, 2) def has_modification_station(state, player): return state.has("Modification Station Fragment", player, 3) def has_mobile_vehicle_bay(state, player): return state.has("Mobile Vehicle Bay Fragment", player, 3) def has_moonpool(state, player): return state.has("Moonpool Fragment", player, 2) def has_vehicle_upgrade_console(state, player): return state.has("Vehicle Upgrade Console", player) and \ has_moonpool(state, player) def has_seamoth(state, player): return state.has("Seamoth Fragment", player, 3) and \ has_mobile_vehicle_bay(state, player) def has_seamoth_depth_module_mk1(state, player): return has_vehicle_upgrade_console(state, player) def has_seamoth_depth_module_mk2(state, player): return has_seamoth_depth_module_mk1(state, player) and \ has_modification_station(state, player) def has_seamoth_depth_module_mk3(state, player): return has_seamoth_depth_module_mk2(state, player) and \ has_modification_station(state, player) def has_cyclops_bridge(state, player): return state.has("Cyclops Bridge Fragment", player, 3) def has_cyclops_engine(state, player): return state.has("Cyclops Engine Fragment", player, 3) def has_cyclops_hull(state, player): return state.has("Cyclops Hull Fragment", player, 3) def has_cyclops(state, player): return has_cyclops_bridge(state, player) and \ has_cyclops_engine(state, player) and \ has_cyclops_hull(state, player) and \ has_mobile_vehicle_bay(state, player) def has_cyclops_depth_module_mk1(state, player): return state.has("Cyclops Depth Module MK1", player) and \ has_modification_station(state, player) def has_cyclops_depth_module_mk2(state, player): return has_cyclops_depth_module_mk1(state, player) and \ has_modification_station(state, player) def has_cyclops_depth_module_mk3(state, player): return has_cyclops_depth_module_mk2(state, player) and \ has_modification_station(state, player) def has_prawn(state, player): return state.has("Prawn Suit Fragment", player, 4) and \ has_mobile_vehicle_bay(state, player) def has_praw_propulsion_arm(state, player): return state.has("Prawn Suit Propulsion Cannon Fragment", player, 2) and \ has_vehicle_upgrade_console(state, player) def has_prawn_depth_module_mk1(state, player): return has_vehicle_upgrade_console(state, player) def has_prawn_depth_module_mk2(state, player): return has_prawn_depth_module_mk1(state, player) and \ has_modification_station(state, player) def has_laser_cutter(state, player): return state.has("Laser Cutter Fragment", player, 3) # Either we have propulsion cannon, or prawn + propulsion cannon arm def has_propulsion_cannon(state, player): return state.has("Propulsion Cannon Fragment", player, 2) or \ (has_prawn(state, player) and has_praw_propulsion_arm(state, player)) def has_cyclops_shield(state, player): return has_cyclops(state, player) and \ state.has("Cyclops Shield Generator", player) # Swim depth rules: # Rebreather, high capacity tank and fins are available from the start. # All tests for those were done without inventory for light weight. # Fins and ultra Fins are better than charge fins, so we ignore charge fins. # We're ignoring lightweight tank in the chart, because the difference is # negligeable with from high capacity tank. 430m -> 460m # Fins are not used when using seaglide # def get_max_swim_depth(state, player): # TODO, Make this a difficulty setting. # Only go up to 200m without any submarines for now. return 200 # Rules bellow, are what are technically possible # has_ultra_high_capacity_tank = state.has("Ultra High Capacity Tank", player) # has_ultra_glide_fins = state.has("Ultra Glide Fins", player) # max_depth = 400 # More like 430m. Give some room # if has_seaglide(state, player): # if has_ultra_high_capacity_tank: # max_depth = 750 # It's about 50m more. Give some room # else: # max_depth = 600 # It's about 50m more. Give some room # elif has_ultra_high_capacity_tank: # if has_ultra_glide_fins: # pass # else: # pass # elif has_ultra_glide_fins: # max_depth = 500 # return max_depth def get_seamoth_max_depth(state, player): if has_seamoth(state, player): if has_seamoth_depth_module_mk3(state, player): return 900 elif has_seamoth_depth_module_mk2(state, player): # Will never be the case, 3 is craftable return 500 elif has_seamoth_depth_module_mk1(state, player): return 300 else: return 200 else: return 0 def get_cyclops_max_depth(state, player): if has_cyclops(state, player): if has_cyclops_depth_module_mk3(state, player): return 1700 elif has_cyclops_depth_module_mk2(state, player): # Will never be the case, 3 is craftable return 1300 elif has_cyclops_depth_module_mk1(state, player): return 900 else: return 500 else: return 0 def get_prawn_max_depth(state, player): if has_prawn(state, player): if has_prawn_depth_module_mk2(state, player): return 1700 elif has_prawn_depth_module_mk1(state, player): return 1300 else: return 900 else: return 0 def get_max_depth(state, player): # TODO, Difficulty option, we can add vehicle depth + swim depth # But at this point, we have to consider traver distance in caves, not # just depth return max(get_max_swim_depth(state, player), get_seamoth_max_depth(state, player), get_cyclops_max_depth(state, player), get_prawn_max_depth(state, player)) def can_access_location(state, player, loc): pos_x = loc.get("position").get("x") pos_y = loc.get("position").get("y") pos_z = loc.get("position").get("z") depth = -pos_y # y-up map_center_dist = math.sqrt(pos_x ** 2 + pos_z ** 2) aurora_dist = math.sqrt((pos_x - 1038.0) ** 2 + (pos_y - -3.4) ** 2 + (pos_z - -163.1) ** 2) need_radiation_suit = aurora_dist < 950 need_laser_cutter = loc.get("need_laser_cutter", False) need_propulsion_cannon = loc.get("need_propulsion_cannon", False) if need_laser_cutter and not has_laser_cutter(state, player): return False if need_radiation_suit and not state.has("Radiation Suit", player): return False if need_propulsion_cannon and not has_propulsion_cannon(state, player): return False # Seaglide doesn't unlock anything specific, but just allows for faster movement. # Otherwise the game is painfully slow. if (map_center_dist > 800 or pos_y < -200) and not has_seaglide(state, player): return False return get_max_depth(state, player) >= depth def set_location_rule(world, player, loc): set_rule(world.get_location(loc["name"], player), lambda state: can_access_location(state, player, loc)) def set_rules(world, player): for loc in location_table: set_location_rule(world, player, loc) # Victory location set_rule(world.get_location("Neptune Launch", player), lambda state: \ get_max_depth(state, player) >= 1444 and \ has_mobile_vehicle_bay(state, player) and \ state.has('Neptune Launch Platform', player) and \ state.has('Neptune Gantry', player) and \ state.has('Neptune Boosters', player) and \ state.has('Neptune Fuel Reserve', player) and \ state.has('Neptune Cockpit', player) and \ state.has('Ion Power Cell', player) and \ state.has('Ion Battery', player) and \ has_cyclops_shield(state, player)) world.completion_condition[player] = lambda state: state.has('Victory', player) <file_sep>from test.hollow_knight import TestVanilla class TestBasic(TestVanilla): def testSimple(self): self.run_location_tests([ ["200_Geo-False_Knight_Chest", True, [], []], ["380_Geo-Soul_Master_Chest", False, [], ["Mantis_Claw"]], ])<file_sep>import os import json from base64 import b64encode, b64decode from math import ceil from .Items import MinecraftItem, item_table, required_items, junk_weights from .Locations import MinecraftAdvancement, advancement_table, exclusion_table, events_table from .Regions import mc_regions, link_minecraft_structures, default_connections from .Rules import set_rules from worlds.generic.Rules import exclusion_rules from BaseClasses import Region, Entrance, Item from .Options import minecraft_options from ..AutoWorld import World client_version = 6 class MinecraftWorld(World): """ Minecraft is a game about creativity. In a world made entirely of cubes, you explore, discover, mine, craft, and try not to explode. Delve deep into the earth and discover abandoned mines, ancient structures, and materials to create a portal to another world. Defeat the Ender Dragon, and claim victory! """ game: str = "Minecraft" options = minecraft_options topology_present = True item_name_to_id = {name: data.code for name, data in item_table.items()} location_name_to_id = {name: data.id for name, data in advancement_table.items()} data_version = 3 def _get_mc_data(self): exits = [connection[0] for connection in default_connections] return { 'world_seed': self.world.slot_seeds[self.player].getrandbits(32), 'seed_name': self.world.seed_name, 'player_name': self.world.get_player_name(self.player), 'player_id': self.player, 'client_version': client_version, 'structures': {exit: self.world.get_entrance(exit, self.player).connected_region.name for exit in exits}, 'advancement_goal': self.world.advancement_goal[self.player], 'egg_shards_required': self.world.egg_shards_required[self.player], 'egg_shards_available': self.world.egg_shards_available[self.player], 'MC35': bool(self.world.send_defeated_mobs[self.player]), 'race': self.world.is_race } def generate_basic(self): # Generate item pool itempool = [] junk_pool = junk_weights.copy() # Add all required progression items for (name, num) in required_items.items(): itempool += [name] * num # Add structure compasses if desired if self.world.structure_compasses[self.player]: structures = [connection[1] for connection in default_connections] for struct_name in structures: itempool.append(f"Structure Compass ({struct_name})") # Add dragon egg shards itempool += ["Dragon Egg Shard"] * self.world.egg_shards_available[self.player] # Add bee traps if desired bee_trap_quantity = ceil(self.world.bee_traps[self.player] * (len(self.location_names)-len(itempool)) * 0.01) itempool += ["Bee Trap (Minecraft)"] * bee_trap_quantity # Fill remaining items with randomly generated junk itempool += self.world.random.choices(list(junk_pool.keys()), weights=list(junk_pool.values()), k=len(self.location_names)-len(itempool)) # Convert itempool into real items itempool = [item for item in map(lambda name: self.create_item(name), itempool)] # Choose locations to automatically exclude based on settings exclusion_pool = set() exclusion_types = ['hard', 'insane', 'postgame'] for key in exclusion_types: if not getattr(self.world, f"include_{key}_advancements")[self.player]: exclusion_pool.update(exclusion_table[key]) exclusion_rules(self.world, self.player, exclusion_pool) # Prefill event locations with their events self.world.get_location("Blaze Spawner", self.player).place_locked_item(self.create_item("Blaze Rods")) self.world.get_location("Ender Dragon", self.player).place_locked_item(self.create_item("Victory")) self.world.itempool += itempool def set_rules(self): set_rules(self.world, self.player) def create_regions(self): def MCRegion(region_name: str, exits=[]): ret = Region(region_name, None, region_name, self.player, self.world) ret.locations = [MinecraftAdvancement(self.player, loc_name, loc_data.id, ret) for loc_name, loc_data in advancement_table.items() if loc_data.region == region_name] for exit in exits: ret.exits.append(Entrance(self.player, exit, ret)) return ret self.world.regions += [MCRegion(*r) for r in mc_regions] link_minecraft_structures(self.world, self.player) def generate_output(self, output_directory: str): data = self._get_mc_data() filename = f"AP_{self.world.seed_name}_P{self.player}_{self.world.get_player_name(self.player)}.apmc" with open(os.path.join(output_directory, filename), 'wb') as f: f.write(b64encode(bytes(json.dumps(data), 'utf-8'))) def fill_slot_data(self): slot_data = self._get_mc_data() for option_name in minecraft_options: option = getattr(self.world, option_name)[self.player] slot_data[option_name] = int(option.value) return slot_data def create_item(self, name: str) -> Item: item_data = item_table[name] item = MinecraftItem(name, item_data.progression, item_data.code, self.player) nonexcluded_items = ["Sharpness III Book", "Infinity Book", "Looting III Book"] if name in nonexcluded_items: # prevent books from going on excluded locations item.never_exclude = True return item def mc_update_output(raw_data, server, port): data = json.loads(b64decode(raw_data)) data['server'] = server data['port'] = port return b64encode(bytes(json.dumps(data), 'utf-8')) <file_sep>import typing class HKItemData(typing.NamedTuple): advancement: bool id: int type: str<file_sep>import importlib import os __all__ = {"lookup_any_item_id_to_name", "lookup_any_location_id_to_name", "network_data_package"} # import all submodules to trigger AutoWorldRegister for file in os.scandir(os.path.dirname(__file__)): if file.is_dir(): importlib.import_module(f".{file.name}", "worlds") from .AutoWorld import AutoWorldRegister lookup_any_item_id_to_name = {} lookup_any_location_id_to_name = {} games = {} for world_name, world in AutoWorldRegister.world_types.items(): games[world_name] = { "item_name_to_id" : world.item_name_to_id, "location_name_to_id": world.location_name_to_id, "version": world.data_version, # seems clients don't actually want this. Keeping it here in case someone changes their mind. # "item_name_groups": {name: tuple(items) for name, items in world.item_name_groups.items()} } lookup_any_item_id_to_name.update(world.item_id_to_name) lookup_any_location_id_to_name.update(world.location_id_to_name) network_data_package = { "version": sum(world.data_version for world in AutoWorldRegister.world_types.values()), "games": games, } # Set entire datapackage to version 0 if any of them are set to 0 if any(not world.data_version for world in AutoWorldRegister.world_types.values()): network_data_package["version"] = 0 import logging logging.warning("Datapackage is in custom mode.") <file_sep>from __future__ import annotations from typing import Dict, Set, Tuple, List, Optional, TextIO from BaseClasses import MultiWorld, Item, CollectionState, Location from Options import Option class AutoWorldRegister(type): world_types: Dict[str, World] = {} def __new__(cls, name, bases, dct): # filter out any events dct["item_name_to_id"] = {name: id for name, id in dct["item_name_to_id"].items() if id} dct["location_name_to_id"] = {name: id for name, id in dct["location_name_to_id"].items() if id} # build reverse lookups dct["item_id_to_name"] = {code: name for name, code in dct["item_name_to_id"].items()} dct["location_id_to_name"] = {code: name for name, code in dct["location_name_to_id"].items()} # build rest dct["item_names"] = frozenset(dct["item_name_to_id"]) dct["location_names"] = frozenset(dct["location_name_to_id"]) dct["all_names"] = dct["item_names"] | dct["location_names"] | set(dct.get("item_name_groups", {})) # construct class new_class = super().__new__(cls, name, bases, dct) if "game" in dct: AutoWorldRegister.world_types[dct["game"]] = new_class return new_class class AutoLogicRegister(type): def __new__(cls, name, bases, dct): new_class = super().__new__(cls, name, bases, dct) for item_name, function in dct.items(): if not item_name.startswith("__"): if hasattr(CollectionState, item_name): raise Exception(f"Name conflict on Logic Mixin {name} trying to overwrite {item_name}") setattr(CollectionState, item_name, function) return new_class def call_single(world: MultiWorld, method_name: str, player: int, *args): method = getattr(world.worlds[player], method_name) return method(*args) def call_all(world: MultiWorld, method_name: str, *args): world_types = set() for player in world.player_ids: world_types.add(world.worlds[player].__class__) call_single(world, method_name, player, *args) for world_type in world_types: stage_callable = getattr(world_type, f"stage_{method_name}", None) if stage_callable: stage_callable(world, *args) def call_stage(world: MultiWorld, method_name: str, *args): world_types = {world.worlds[player].__class__ for player in world.player_ids} for world_type in world_types: stage_callable = getattr(world_type, f"stage_{method_name}", None) if stage_callable: stage_callable(world, *args) class World(metaclass=AutoWorldRegister): """A World object encompasses a game's Items, Locations, Rules and additional data or functionality required. A Game should have its own subclass of World in which it defines the required data structures.""" options: Dict[str, type(Option)] = {} # link your Options mapping game: str # name the game topology_present: bool = False # indicate if world type has any meaningful layout/pathing all_names: Set[str] = frozenset() # gets automatically populated with all item, item group and location names # map names to their IDs item_name_to_id: Dict[str, int] = {} location_name_to_id: Dict[str, int] = {} # maps item group names to sets of items. Example: "Weapons" -> {"Sword", "Bow"} item_name_groups: Dict[str, Set[str]] = {} # increment this every time something in your world's names/id mappings changes. # While this is set to 0 in *any* AutoWorld, the entire DataPackage is considered in testing mode and will be # retrieved by clients on every connection. data_version: int = 1 hint_blacklist: Set[str] = frozenset() # any names that should not be hintable # if a world is set to remote_items, then it just needs to send location checks to the server and the server # sends back the items # if a world is set to remote_items = False, then the server never sends an item where receiver == finder, # the client finds its own items in its own world. remote_items: bool = True # If remote_start_inventory is true, the start_inventory/world.precollected_items is sent on connection, # otherwise the world implementation is in charge of writing the items to their output data. remote_start_inventory: bool = True # For games where after a victory it is impossible to go back in and get additional/remaining Locations checked. # this forces forfeit: auto for those games. forced_auto_forfeit: bool = False # Hide World Type from various views. Does not remove functionality. hidden: bool = False # autoset on creation: world: MultiWorld player: int # automatically generated item_id_to_name: Dict[int, str] location_id_to_name: Dict[int, str] item_names: Set[str] # set of all potential item names location_names: Set[str] # set of all potential location names # If there is visibility in what is being sent, this is where it will be known. sending_visible: bool = False def __init__(self, world: MultiWorld, player: int): self.world = world self.player = player # overridable methods that get called by Main.py, sorted by execution order # can also be implemented as a classmethod and called "stage_<original_name", # in that case the MultiWorld object is passed as an argument and it gets called once for the entire multiworld. # An example of this can be found in alttp as stage_pre_fill def generate_early(self): pass def create_regions(self): pass def create_items(self): pass def set_rules(self): pass def generate_basic(self): pass def pre_fill(self): """Optional method that is supposed to be used for special fill stages. This is run *after* plando.""" pass @classmethod def fill_hook(cls, progitempool: List[Item], nonexcludeditempool: List[Item], localrestitempool: Dict[int, List[Item]], nonlocalrestitempool: Dict[int, List[Item]], restitempool: List[Item], fill_locations: List[Location]): """Special method that gets called as part of distribute_items_restrictive (main fill). This gets called once per present world type.""" pass def post_fill(self): """Optional Method that is called after regular fill. Can be used to do adjustments before output generation.""" def generate_output(self, output_directory: str): """This method gets called from a threadpool, do not use world.random here. If you need any last-second randomization, use MultiWorld.slot_seeds[slot] instead.""" pass def fill_slot_data(self) -> dict: """Fill in the slot_data field in the Connected network package.""" return {} def modify_multidata(self, multidata: dict): """For deeper modification of server multidata.""" pass def get_required_client_version(self) -> Tuple[int, int, int]: return 0, 1, 6 # Spoiler writing is optional, these may not get called. def write_spoiler_header(self, spoiler_handle: TextIO): """Write to the spoiler header. If individual it's right at the end of that player's options, if as stage it's right under the common header before per-player options.""" pass def write_spoiler(self, spoiler_handle: TextIO): """Write to the spoiler "middle", this is after the per-player options and before locations, meant for useful or interesting info.""" pass def write_spoiler_end(self, spoiler_handle: TextIO): """Write to the end of the spoiler""" pass # end of ordered Main.py calls def collect_item(self, state: CollectionState, item: Item, remove: bool = False) -> Optional[str]: """Collect an item name into state. For speed reasons items that aren't logically useful get skipped. Collect None to skip item. :param remove: indicate if this is meant to remove from state instead of adding.""" if item.advancement: return item.name def create_item(self, name: str) -> Item: """Create an item for this world type and player. Warning: this may be called with self.world = None, for example by MultiServer""" raise NotImplementedError # following methods should not need to be overridden. def collect(self, state: CollectionState, item: Item) -> bool: name = self.collect_item(state, item) if name: state.prog_items[name, item.player] += 1 return True return False def remove(self, state: CollectionState, item: Item) -> bool: name = self.collect_item(state, item, True) if name: state.prog_items[name, item.player] -= 1 if state.prog_items[name, item.player] < 1: del (state.prog_items[name, item.player]) return True return False # any methods attached to this can be used as part of CollectionState, # please use a prefix as all of them get clobbered together class LogicMixin(metaclass=AutoLogicRegister): pass <file_sep># Minecraft Randomizer Setup Guide #Automatic Hosting Install - download and install [Archipelago](https://github.com/ArchipelagoMW/Archipelago/releases) and choose the `Minecraft Client` module ## Required Software - [Minecraft Java Edition](https://www.minecraft.net/en-us/store/minecraft-java-edition) ## Configuring your YAML file ### What is a YAML file and why do I need one? Your YAML file contains a set of configuration options which provide the generator with information about how it should generate your game. Each player of a multiworld will provide their own YAML file. This setup allows each player to enjoy an experience customized for their taste, and different players in the same multiworld can all have different options. ### Where do I get a YAML file? A basic minecraft yaml will look like this. ```yaml description: Basic Minecraft Yaml # Your name in-game. Spaces will be replaced with underscores and # there is a 16 character limit name: YourName game: Minecraft # Shared Options supported by all games: accessibility: locations progression_balancing: on # Minecraft Specific Options Minecraft: # Number of advancements required (87 max) to spawn the Ender Dragon and complete the game. advancement_goal: 50 # Number of dragon egg shards to collect (30 max) before the Ender Dragon will spawn. egg_shards_required: 10 # Number of egg shards available in the pool (30 max). egg_shards_available: 15 # Modifies the level of items logically required for # exploring dangerous areas and fighting bosses. combat_difficulty: easy: 0 normal: 1 hard: 0 # Junk-fills certain RNG-reliant or tedious advancements. include_hard_advancements: on: 0 off: 1 # Junk-fills extremely difficult advancements; # this is only How Did We Get Here? and Adventuring Time. include_insane_advancements: on: 0 off: 1 # Some advancements require defeating the Ender Dragon; # this will junk-fill them, so you won't have to finish them to send some items. include_postgame_advancements: on: 0 off: 1 # Enables shuffling of villages, outposts, fortresses, bastions, and end cities. shuffle_structures: on: 0 off: 1 # Adds structure compasses to the item pool, # which point to the nearest indicated structure. structure_compasses: on: 0 off: 1 # Replaces a percentage of junk items with bee traps # which spawn multiple angered bees around every player when received. bee_traps: 0: 1 25: 0 50: 0 75: 0 100: 0 ``` ## Joining a MultiWorld Game ### Obtain your Minecraft data file **Only one yaml file needs to be submitted per minecraft world regardless of how many players play on it.** When you join a multiworld game, you will be asked to provide your YAML file to whoever is hosting. Once that is done, the host will provide you with either a link to download your data file, or with a zip file containing everyone's data files. Your data file should have a `.apmc` extension. double click on your `.apmc` file to have the minecraft client auto-launch the installed forge server. ### Connect to the MultiServer After having placed your data file in the `APData` folder, start the Forge server and make sure you have OP status by typing `/op YourMinecraftUsername` in the forge server console then connecting in your Minecraft client. Once in game type `/connect <AP-Address> (Port) (Password)` where `<AP-Address>` is the address of the Archipelago server. `(Port)` is only required if the Archipelago server is not using the default port of 38281. `(Password)` is only required if the Archipleago server you are using has a password set. ### Play the game When the console tells you that you have joined the room, you're ready to begin playing. Congratulations on successfully joining a multiworld game! At this point any additional minecraft players may connect to your forge server. ## Manual Installation Procedures this is only required if you wish to set up a forge install yourself, its recommended to just use the Archipelago Installer. ###Required Software - [Minecraft Forge](https://files.minecraftforge.net/net/minecraftforge/forge/index_1.16.5.html) - [Minecraft Archipelago Randomizer Mod](https://github.com/KonoTyran/Minecraft_AP_Randomizer/releases) **DO NOT INSTALL THIS ON YOUR CLIENT** ### Dedicated Server Setup Only one person has to do this setup and host a dedicated server for everyone else playing to connect to. 1. Download the 1.16.5 **Minecraft Forge** installer from the link above, making sure to download the most recent recommended version. 2. Run the `forge-1.16.5-xx.x.x-installer.jar` file and choose **install server**. - On this page you will also choose where to install the server to remember this directory it's important in the next step. 3. Navigate to where you installed the server and open `forge-1.16.5-xx.x.x.jar` - Upon first launch of the server it will close and ask you to accept Minecraft's EULA. There will be a new file called `eula.txt` that contains a link to Minecraft's EULA, and a line that you need to change to `eula=true` to accept Minecraft's EULA. - This will create the appropriate directories for you to place the files in the following step. 4. Place the `aprandomizer-x.x.x.jar` from the link above file into the `mods` folder of the above installation of your forge server. - Once again run the server, it will load up and generate the required directory `APData` for when you are ready to play a game! <file_sep># generated by https://github.com/Berserker66/ori_rando_server # do not edit manually locations_by_region = \ {'AboveChargeJumpArea': {'AboveChargeJumpAbilityCell'}, 'BashTree': {'BashAreaExp', 'BashSkillTree'}, 'BashTreeDoorClosed': set(), 'BashTreeDoorOpened': set(), 'BelowSunstoneArea': set(), 'BlackrootDarknessRoom': {'DashAreaOrbRoomExp', 'DashAreaAbilityCell', 'DashAreaRoofExp'}, 'BlackrootGrottoConnection': {'BlackrootBoulderExp', 'BlackrootMap', 'BlackrootTeleporterHealthCell'}, 'ChargeFlameAreaPlantAccess': {'ChargeFlameAreaPlant'}, 'ChargeFlameAreaStump': set(), 'ChargeFlameSkillTreeChamber': {'ChargeFlameSkillTree'}, 'ChargeJumpArea': {'ChargeJumpSkillTree'}, 'ChargeJumpDoor': set(), 'ChargeJumpDoorOpen': set(), 'ChargeJumpDoorOpenLeft': {'UpperSorrowSpikeExp', 'UpperSorrowRightKeystone', 'UpperSorrowLeftKeystone', 'UpperSorrowFarRightKeystone', 'UpperSorrowFarLeftKeystone'}, 'DashArea': {'DashAreaMapstone', 'DashSkillTree'}, 'DashPlantAccess': {'DashAreaPlant'}, 'DeathGauntlet': {'DeathGauntletEnergyCell', 'DeathGauntletStompSwim', 'DeathGauntletExp'}, 'DeathGauntletDoor': set(), 'DeathGauntletDoorOpened': set(), 'DeathGauntletMoat': {'DeathGauntletSwimEnergyDoor'}, 'DeathGauntletRoof': {'DeathGauntletRoofHealthCell'}, 'DeathGauntletRoofPlantAccess': {'DeathGauntletRoofPlant'}, 'DoubleJumpKeyDoor': set(), 'DoubleJumpKeyDoorOpened': {'DoubleJumpSkillTree', 'DoubleJumpAreaExp'}, 'ForlornGravityRoom': {'ForlornKeystone2', 'ForlornHiddenSpiderExp', 'ForlornKeystone1'}, 'ForlornInnerDoor': {'ForlornEntranceExp'}, 'ForlornKeyDoor': set(), 'ForlornLaserRoom': {'ForlornEscape'}, 'ForlornMapArea': {'ForlornMap', 'ForlornKeystone4'}, 'ForlornOrbPossession': {'ForlornKeystone2', 'ForlornHiddenSpiderExp', 'ForlornKeystone1', 'ForlornKeystone4', 'ForlornKeystone3'}, 'ForlornOuterDoor': set(), 'ForlornPlantAccess': {'ForlornPlant'}, 'ForlornStompDoor': set(), 'ForlornTeleporter': {'ForlornKeystone3'}, 'GinsoEscape': set(), 'GinsoEscapeComplete': {'GinsoEscapeExit', 'GinsoEscapeSpiderExp', 'GinsoEscapeProjectileExp', 'GinsoEscapeJumpPadExp', 'GinsoEscapeHangingExp'}, 'GinsoInnerDoor': set(), 'GinsoMiniBossDoor': {'LowerGinsoKeystone2', 'LowerGinsoKeystone1', 'LowerGinsoKeystone3', 'LowerGinsoKeystone4'}, 'GinsoOuterDoor': set(), 'GinsoTeleporter': set(), 'GladesLaserArea': {'GladesLaserGrenade', 'GladesLaser'}, 'GladesMain': {'FourthHealthCell', 'GladesMap', 'GladesMapKeystone'}, 'GladesMainAttic': {'AboveFourthHealth'}, 'GrenadeArea': {'GrenadeAreaAbilityCell', 'GrenadeAreaExp', 'GrenadeSkillTree'}, 'GrenadeAreaAccess': set(), 'GumoHideout': {'GumoHideoutMapstone', 'GumoHideoutCrusherExp', 'GumoHideoutRightHangingExp', 'GumoHideoutEnergyCell', 'GumoHideoutCrusherKeystone', 'GumoHideoutMap', 'GumoHideoutMiniboss'}, 'GumoHideoutRedirectArea': {'GumoHideoutRedirectAbilityCell', 'GumoHideoutRedirectPlant'}, 'GumoHideoutRedirectEnergyVault': {'GumoHideoutRedirectExp', 'GumoHideoutRedirectEnergyCell'}, 'HollowGrove': {'GroveWaterStompAbilityCell', 'HollowGroveTreeAbilityCell', 'HollowGroveMapPlant', 'HoruFieldsHealthCell', 'HollowGroveMap', 'SwampTeleporterAbilityCell', 'HollowGroveMapstone', 'HollowGroveTreePlant'}, 'HoruBasement': {'DoorWarpExp'}, 'HoruEscapeInnerDoor': set(), 'HoruEscapeOuterDoor': set(), 'HoruFields': set(), 'HoruFieldsPushBlock': {'HoruFieldsEnergyCell', 'HoruFieldsPlant', 'HoruFieldsHiddenExp', 'HoruFieldsAbilityCell'}, 'HoruInnerDoor': {'HoruLavaDrainedLeftExp', 'HoruLavaDrainedRightExp'}, 'HoruL4CutscenePeg': {'HoruL4', 'HoruL4LowerExp'}, 'HoruL4LavaChasePeg': {'HoruL4ChaseExp'}, 'HoruMapLedge': {'HoruMap'}, 'HoruOuterDoor': set(), 'HoruR1CutsceneTrigger': {'HoruR1EnergyCell', 'HoruR1'}, 'HoruR1MapstoneSecret': {'HoruR1Mapstone'}, 'HoruR3CutsceneTrigger': {'HoruR3'}, 'HoruR3ElevatorLever': set(), 'HoruR3PlantCove': {'HoruR3Plant'}, 'HoruR4CutsceneTrigger': {'HoruR4DrainedExp', 'HoruR4'}, 'HoruR4PuzzleEntrance': {'HoruR4LaserExp'}, 'HoruR4StompHideout': {'HoruR4StompExp'}, 'HoruTeleporter': {'HoruTeleporterExp'}, 'Iceless': {'IcelessExp'}, 'InnerSwampAboveDrainArea': set(), 'InnerSwampDrainBroken': {'InnerSwampDrainExp'}, 'InnerSwampSkyArea': {'InnerSwampEnergyCell'}, 'L1': {'HoruL1'}, 'L1InnerDoor': set(), 'L1OuterDoor': set(), 'L2': {'HoruL2'}, 'L2InnerDoor': set(), 'L2OuterDoor': set(), 'L3': {'HoruL3'}, 'L3InnerDoor': set(), 'L3OuterDoor': set(), 'L4': set(), 'L4InnerDoor': set(), 'L4OuterDoor': {'HoruLavaDrainedLeftExp'}, 'LeftGlades': {'WallJumpAreaEnergyCell', 'LeftGladesHiddenExp', 'WallJumpAreaExp', 'WallJumpSkillTree'}, 'LeftGumoHideout': {'FarLeftGumoHideoutExp', 'LeftGumoHideoutUpperPlant'}, 'LeftSorrow': {'LeftSorrowAbilityCell', 'LeftSorrowPlant', 'LeftSorrowGrenade'}, 'LeftSorrowKeystones': {'LeftSorrowEnergyCell', 'LeftSorrowKeystone1', 'LeftSorrowKeystone2', 'LeftSorrowKeystone4', 'LeftSorrowKeystone3'}, 'LeftSorrowLowerDoor': set(), 'LeftSorrowMiddleDoor': set(), 'LostGrove': {'LostGroveLongSwim'}, 'LostGroveExit': {'LostGroveTeleporter', 'LostGroveAbilityCell', 'LostGroveHiddenExp'}, 'LowerBlackroot': {'LowerBlackrootAbilityCell', 'LowerBlackrootLaserAbilityCell', 'LowerBlackrootGrenadeThrow', 'LowerBlackrootLaserExp'}, 'LowerChargeFlameArea': {'ChargeFlameAreaExp'}, 'LowerGinsoTree': {'LowerGinsoPlant', 'LowerGinsoHiddenExp'}, 'LowerLeftGumoHideout': {'LeftGumoHideoutSwim', 'LeftGumoHideoutHealthCell', 'LeftGumoHideoutExp', 'GumoHideoutLeftHangingExp', 'GumoHideoutRightHangingExp', 'LeftGumoHideoutLowerPlant'}, 'LowerSorrow': {'SorrowLowerLeftKeystone', 'SorrowHiddenKeystone', 'SorrowEntranceAbilityCell', 'SorrowHealthCell', 'SorrowSpikeKeystone'}, 'LowerSpiritCaverns': {'SpiritCavernsKeystone1', 'SpiritCavernsAbilityCell', 'SpiritCavernsKeystone2'}, 'LowerValley': {'LowerValleyExp', 'LowerValleyMapstone', 'KuroPerchExp'}, 'LowerValleyPlantApproach': {'ValleyMainPlant'}, 'MidSpiritCaverns': set(), 'MiddleSorrow': set(), 'MistyAbove200xp': {'MistyGrenade'}, 'MistyBeforeDocks': set(), 'MistyBeforeMiniBoss': set(), 'MistyEntrance': {'MistyEntranceStompExp', 'MistyEntranceTreeExp'}, 'MistyKeystone3Ledge': {'MistyKeystone3'}, 'MistyKeystone4Ledge': {'MistyKeystone4'}, 'MistyMortarSpikeCave': {'MistyPostClimbAboveSpikePit'}, 'MistyOrbRoom': {'GumonSeal'}, 'MistyPostClimb': set(), 'MistyPostFeatherTutorial': {'MistyFrogNookExp', 'MistyKeystone1'}, 'MistyPostKeystone1': set(), 'MistyPostLasers': {'MistyPostClimbSpikeCave'}, 'MistyPostMortarCorridor': set(), 'MistyPreClimb': {'ClimbSkillTree'}, 'MistyPreKeystone2': {'MistyKeystone2', 'MistyAbilityCell'}, 'MistyPreLasers': set(), 'MistyPreMortarCorridor': {'MistyMortarCorridorUpperExp', 'MistyMortarCorridorHiddenExp'}, 'MistyPrePlantLedge': {'MistyPlant'}, 'MistySpikeCave': set(), 'MoonGrotto': {'GrottoEnergyDoorHealthCell', 'GrottoEnergyDoorSwim'}, 'MoonGrottoAboveTeleporter': {'LeftGrottoTeleporterExp', 'AboveGrottoTeleporterExp'}, 'MoonGrottoBelowTeleporter': {'BelowGrottoTeleporterPlant', 'BelowGrottoTeleporterHealthCell'}, 'MoonGrottoStompPlantAccess': {'MoonGrottoStompPlant'}, 'MoonGrottoSwampAccessArea': {'GrottoSwampDrainAccessExp', 'GrottoSwampDrainAccessPlant'}, 'OuterSwampAbilityCellNook': {'OuterSwampAbilityCell'}, 'OuterSwampLowerArea': {'OuterSwampHealthCell', 'OuterSwampStompExp'}, 'OuterSwampMortarAbilityCellLedge': {'OuterSwampMortarAbilityCell'}, 'OuterSwampMortarPlantAccess': {'OuterSwampMortarPlant'}, 'OuterSwampUpperArea': {'OuterSwampGrenadeExp'}, 'OutsideForlorn': {'OutsideForlornTreeExp', 'OutsideForlornWaterExp'}, 'OutsideForlornCliff': {'OutsideForlornCliffExp'}, 'R1': {'HoruR1HangingExp'}, 'R1InnerDoor': set(), 'R1OuterDoor': set(), 'R2': {'HoruR2'}, 'R2InnerDoor': set(), 'R2OuterDoor': set(), 'R3': set(), 'R3InnerDoor': set(), 'R3OuterDoor': set(), 'R4': {'HoruR4DrainedExp'}, 'R4InnerDoor': set(), 'R4OuterDoor': {'HoruLavaDrainedRightExp'}, 'RazielNoArea': {'RazielNo'}, 'RightForlorn': {'RightForlornPlant', 'RightForlornHealthCell'}, 'RightSwamp': {'StompAreaGrenadeExp', 'StompSkillTree', 'StompAreaExp', 'StompAreaRoofExp'}, 'SideFallCell': {'GrottoHideoutFallAbilityCell'}, 'SorrowBashLedge': set(), 'SorrowMainShaftKeystoneArea': {'SorrowMainShaftKeystone'}, 'SorrowMapstoneArea': {'SorrowMap', 'SorrowMapstone'}, 'SorrowTeleporter': set(), 'SpiderSacArea': {'AboveChargeFlameTreeExp'}, 'SpiderSacEnergyNook': {'SpiderSacEnergyCell'}, 'SpiderSacTetherArea': {'SpiderSacGrenadeDoor', 'SpiderSacEnergyDoor', 'SpiderSacHealthCell'}, 'SpiderWaterArea': {'GroveSpiderWaterSwim', 'GroveAboveSpiderWaterEnergyCell', 'GroveAboveSpiderWaterExp', 'GroveAboveSpiderWaterHealthCell'}, 'SpiritCavernsDoor': set(), 'SpiritCavernsDoorOpened': set(), 'SpiritTreeDoor': set(), 'SpiritTreeDoorOpened': set(), 'SpiritTreeRefined': {'AboveChargeFlameTreeExp'}, 'SunkenGladesRunaway': {'FronkeyWalkRoof', 'GladesGrenadePool', 'GladesMainPoolDeep', 'FirstPickup', 'FronkeyFight', 'GladesMainPool', 'GladesKeystone1', 'GladesGrenadeTree', 'GladesKeystone2'}, 'SunstoneArea': {'Sunstone', 'SunstonePlant'}, 'Swamp': {'InnerSwampDrainExp', 'SwampMap'}, 'SwampDrainlessArea': {'SwampEntranceAbilityCell'}, 'SwampEntryArea': {'SwampEntrancePlant', 'SwampEntranceSwim'}, 'SwampKeyDoorOpened': set(), 'SwampKeyDoorPlatform': {'InnerSwampStompExp'}, 'SwampTeleporter': set(), 'SwampWater': {'InnerSwampSwimRightKeystone', 'InnerSwampSwimMapstone', 'InnerSwampHiddenSwimExp', 'InnerSwampSwimLeftKeystone'}, 'TopGinsoTree': {'TopGinsoLeftLowerExp', 'TopGinsoLeftUpperExp', 'TopGinsoRightPlant'}, 'UpperGinsoDoorClosed': set(), 'UpperGinsoDoorOpened': set(), 'UpperGinsoRedirectArea': {'BashAreaExp', 'UpperGinsoRedirectUpperExp', 'UpperGinsoRedirectLowerExp'}, 'UpperGinsoTree': {'UpperGinsoUpperLeftKeystone', 'UpperGinsoLowerKeystone', 'UpperGinsoRightKeystone', 'UpperGinsoUpperRightKeystone', 'UpperGinsoEnergyCell'}, 'UpperGrotto': {'GrottoLasersRoofExp'}, 'UpperLeftGlades': {'LeftGladesKeystone', 'LeftGladesExp', 'LeftGladesMapstone'}, 'UpperSorrow': {'UpperSorrowSpikeExp', 'UpperSorrowRightKeystone', 'UpperSorrowLeftKeystone', 'UpperSorrowFarRightKeystone', 'UpperSorrowFarLeftKeystone'}, 'UpperSpiritCaverns': {'SpiritCavernsTopRightKeystone', 'SpiritCavernsTopLeftKeystone'}, 'ValleyEntry': {'ValleyEntryAbilityCell', 'ValleyThreeBirdAbilityCell'}, 'ValleyEntryTree': {'ValleyEntryTreeExp', 'ValleyEntryGrenadeLongSwim'}, 'ValleyEntryTreePlantAccess': {'ValleyEntryTreePlant'}, 'ValleyForlornApproach': {'ValleyMap', 'ValleyForlornApproachGrenade', 'ValleyForlornApproachMapstone'}, 'ValleyMain': {'GlideSkillFeather', 'KuroPerchExp'}, 'ValleyPostStompDoor': {'ValleyRightSwimExp'}, 'ValleyRight': set(), 'ValleyStompFloor': set(), 'ValleyStompless': {'KuroPerchExp'}, 'ValleyStomplessApproach': {'ValleyRightFastStomplessCell', 'ValleyRightBirdStompCell', 'ValleyRightExp'}, 'ValleyTeleporter': set(), 'ValleyThreeBirdLever': {'ValleyThreeBirdAbilityCell', 'ValleyMainFACS'}, 'WaterVeinArea': {'WaterVein', 'GumoHideoutRockfallExp'}, 'WilhelmLedge': {'WilhelmExp', 'KuroPerchExp'}} connectors = \ {'AboveChargeJumpArea': {'SorrowTeleporter', 'ChargeJumpArea'}, 'BashTree': {'BashTreeDoorClosed', 'UpperGinsoRedirectArea'}, 'BashTreeDoorClosed': {'BashTreeDoorOpened'}, 'BashTreeDoorOpened': {'GinsoMiniBossDoor', 'BashTree'}, 'BelowSunstoneArea': {'SunstoneArea', 'UpperSorrow'}, 'BlackrootDarknessRoom': {'DashArea'}, 'BlackrootGrottoConnection': {'SideFallCell'}, 'ChargeFlameAreaStump': {'LowerChargeFlameArea', 'ChargeFlameSkillTreeChamber', 'ChargeFlameAreaPlantAccess'}, 'ChargeFlameSkillTreeChamber': {'SpiritTreeRefined', 'ChargeFlameAreaStump'}, 'ChargeJumpArea': {'AboveChargeJumpArea', 'ChargeJumpDoor'}, 'ChargeJumpDoor': {'ChargeJumpDoorOpen'}, 'ChargeJumpDoorOpen': {'ChargeJumpDoorOpenLeft', 'ChargeJumpArea'}, 'ChargeJumpDoorOpenLeft': {'UpperSorrow'}, 'DashArea': {'RazielNoArea', 'GrenadeAreaAccess', 'DashPlantAccess'}, 'DeathGauntlet': {'DeathGauntletRoofPlantAccess', 'MoonGrotto', 'DeathGauntletMoat', 'MoonGrottoAboveTeleporter', 'DeathGauntletRoof', 'DeathGauntletDoor'}, 'DeathGauntletDoor': {'DeathGauntletDoorOpened'}, 'DeathGauntletDoorOpened': {'SunkenGladesRunaway', 'DeathGauntlet', 'DeathGauntletMoat'}, 'DeathGauntletRoof': {'DeathGauntlet', 'DeathGauntletRoofPlantAccess'}, 'DoubleJumpKeyDoor': {'DoubleJumpKeyDoorOpened'}, 'ForlornGravityRoom': {'ForlornMapArea', 'ForlornInnerDoor'}, 'ForlornInnerDoor': {'ForlornGravityRoom', 'ForlornOrbPossession', 'ForlornOuterDoor'}, 'ForlornKeyDoor': {'ForlornLaserRoom'}, 'ForlornLaserRoom': {'ForlornStompDoor'}, 'ForlornMapArea': {'ForlornGravityRoom', 'ForlornKeyDoor', 'ForlornPlantAccess', 'ForlornTeleporter'}, 'ForlornOrbPossession': {'ForlornMapArea', 'ForlornKeyDoor', 'ForlornPlantAccess', 'ForlornInnerDoor'}, 'ForlornOuterDoor': {'OutsideForlorn', 'ForlornInnerDoor'}, 'ForlornStompDoor': {'RightForlorn'}, 'ForlornTeleporter': {'ForlornMapArea', 'ForlornGravityRoom', 'ForlornOrbPossession'}, 'GinsoEscape': {'GinsoEscapeComplete'}, 'GinsoEscapeComplete': {'Swamp'}, 'GinsoInnerDoor': {'LowerGinsoTree'}, 'GinsoMiniBossDoor': {'BashTreeDoorClosed'}, 'GinsoOuterDoor': {'GinsoInnerDoor'}, 'GinsoTeleporter': {'UpperGinsoDoorClosed', 'TopGinsoTree'}, 'GladesLaserArea': {'MidSpiritCaverns', 'GladesMain'}, 'GladesMain': {'LeftGlades', 'SpiritCavernsDoor', 'LowerChargeFlameArea', 'GladesMainAttic', 'GladesLaserArea'}, 'GladesMainAttic': {'LowerChargeFlameArea', 'GladesMain'}, 'GrenadeAreaAccess': {'LowerBlackroot', 'GrenadeArea'}, 'GumoHideout': {'SideFallCell', 'LeftGumoHideout', 'LowerLeftGumoHideout', 'DoubleJumpKeyDoor'}, 'GumoHideoutRedirectArea': {'GumoHideoutRedirectEnergyVault'}, 'HollowGrove': {'MoonGrottoStompPlantAccess', 'Iceless', 'SwampTeleporter', 'SpiderWaterArea', 'HoruFields', 'OuterSwampUpperArea'}, 'HoruBasement': {'HoruEscapeOuterDoor'}, 'HoruEscapeOuterDoor': {'HoruEscapeInnerDoor'}, 'HoruFields': {'HoruOuterDoor', 'HoruFieldsPushBlock'}, 'HoruFieldsPushBlock': {'HollowGrove'}, 'HoruInnerDoor': {'HoruBasement', 'R2OuterDoor', 'HoruMapLedge', 'L1OuterDoor', 'L2OuterDoor', 'HoruTeleporter', 'L3OuterDoor', 'R1OuterDoor', 'R4OuterDoor', 'HoruOuterDoor', 'L4OuterDoor', 'R3OuterDoor'}, 'HoruL4LavaChasePeg': {'HoruL4CutscenePeg'}, 'HoruOuterDoor': {'HoruFieldsPushBlock', 'HoruInnerDoor'}, 'HoruR1CutsceneTrigger': {'LowerGinsoTree'}, 'HoruR1MapstoneSecret': {'HoruR1CutsceneTrigger'}, 'HoruR3CutsceneTrigger': {'HoruR3PlantCove'}, 'HoruR3ElevatorLever': {'HoruR3PlantCove', 'HoruR3CutsceneTrigger'}, 'HoruR4PuzzleEntrance': {'HoruR4CutsceneTrigger'}, 'HoruR4StompHideout': {'HoruR4CutsceneTrigger', 'HoruR4PuzzleEntrance'}, 'HoruTeleporter': {'HoruInnerDoor'}, 'Iceless': {'HollowGrove', 'UpperGrotto'}, 'InnerSwampAboveDrainArea': {'InnerSwampDrainBroken'}, 'InnerSwampDrainBroken': {'Swamp'}, 'InnerSwampSkyArea': {'SwampKeyDoorPlatform', 'Swamp'}, 'L1InnerDoor': {'L1'}, 'L1OuterDoor': {'L1InnerDoor', 'HoruInnerDoor'}, 'L2InnerDoor': {'L2'}, 'L2OuterDoor': {'L2InnerDoor', 'HoruInnerDoor'}, 'L3InnerDoor': {'L3'}, 'L3OuterDoor': {'L3InnerDoor', 'HoruInnerDoor'}, 'L4': {'HoruL4CutscenePeg', 'HoruL4LavaChasePeg'}, 'L4InnerDoor': {'L4'}, 'L4OuterDoor': {'L4InnerDoor', 'HoruInnerDoor'}, 'LeftGlades': {'UpperLeftGlades', 'GladesMain'}, 'LeftGumoHideout': {'WaterVeinArea', 'LowerLeftGumoHideout'}, 'LeftSorrow': {'LeftSorrowKeystones'}, 'LeftSorrowKeystones': {'LeftSorrowMiddleDoor', 'MiddleSorrow'}, 'LeftSorrowLowerDoor': {'LeftSorrow'}, 'LeftSorrowMiddleDoor': {'MiddleSorrow'}, 'LostGrove': {'LostGroveExit'}, 'LowerBlackroot': {'LostGrove'}, 'LowerChargeFlameArea': {'ChargeFlameAreaStump', 'GladesMain'}, 'LowerGinsoTree': {'R4InnerDoor', 'GinsoMiniBossDoor'}, 'LowerLeftGumoHideout': {'LowerBlackroot', 'GumoHideoutRedirectArea'}, 'LowerSorrow': {'SorrowMainShaftKeystoneArea', 'SorrowMapstoneArea', 'LeftSorrowLowerDoor', 'LeftSorrow', 'SunstoneArea', 'WilhelmLedge', 'MiddleSorrow'}, 'LowerSpiritCaverns': {'SpiritCavernsDoor', 'MidSpiritCaverns', 'GladesLaserArea'}, 'LowerValley': {'ValleyThreeBirdLever', 'LowerValleyPlantApproach', 'ValleyTeleporter', 'MistyEntrance'}, 'MidSpiritCaverns': {'UpperSpiritCaverns', 'LowerSpiritCaverns', 'GladesLaserArea'}, 'MiddleSorrow': {'SorrowMainShaftKeystoneArea', 'LeftSorrowKeystones', 'LeftSorrow', 'LowerSorrow', 'UpperSorrow', 'SunstoneArea'}, 'MistyAbove200xp': {'MistyBeforeMiniBoss'}, 'MistyBeforeDocks': {'MistyAbove200xp'}, 'MistyBeforeMiniBoss': {'MistyOrbRoom'}, 'MistyEntrance': {'MistyPostFeatherTutorial'}, 'MistyKeystone3Ledge': {'MistyPreLasers'}, 'MistyKeystone4Ledge': {'MistyBeforeDocks'}, 'MistyMortarSpikeCave': {'MistyKeystone4Ledge'}, 'MistyOrbRoom': {'MistyPreKeystone2'}, 'MistyPostClimb': {'MistySpikeCave'}, 'MistyPostFeatherTutorial': {'MistyPostKeystone1'}, 'MistyPostKeystone1': {'MistyPreMortarCorridor'}, 'MistyPostLasers': {'MistyMortarSpikeCave'}, 'MistyPostMortarCorridor': {'MistyPrePlantLedge'}, 'MistyPreClimb': {'MistyPostClimb', 'ForlornTeleporter', 'RightForlorn'}, 'MistyPreLasers': {'MistyPostLasers'}, 'MistyPreMortarCorridor': {'MistyPostMortarCorridor', 'RightForlorn'}, 'MistyPrePlantLedge': {'MistyPreClimb'}, 'MistySpikeCave': {'MistyKeystone3Ledge'}, 'MoonGrotto': {'MoonGrottoBelowTeleporter', 'MoonGrottoAboveTeleporter', 'WaterVeinArea', 'DeathGauntlet', 'GumoHideout'}, 'MoonGrottoAboveTeleporter': {'MoonGrottoSwampAccessArea', 'MoonGrottoBelowTeleporter', 'MoonGrottoStompPlantAccess', 'MoonGrotto', 'DeathGauntletRoof', 'UpperGrotto'}, 'MoonGrottoSwampAccessArea': {'InnerSwampAboveDrainArea'}, 'OuterSwampAbilityCellNook': {'InnerSwampSkyArea'}, 'OuterSwampLowerArea': {'OuterSwampAbilityCellNook', 'OuterSwampMortarPlantAccess', 'SwampEntryArea', 'OuterSwampMortarAbilityCellLedge', 'UpperGrotto', 'OuterSwampUpperArea'}, 'OuterSwampMortarAbilityCellLedge': {'OuterSwampMortarPlantAccess', 'UpperGrotto'}, 'OuterSwampUpperArea': {'OuterSwampLowerArea', 'OuterSwampAbilityCellNook', 'GinsoOuterDoor'}, 'OutsideForlorn': {'OutsideForlornCliff', 'RightForlorn', 'ForlornOuterDoor'}, 'OutsideForlornCliff': {'OutsideForlorn', 'ValleyForlornApproach'}, 'R1': {'HoruR1MapstoneSecret'}, 'R1InnerDoor': {'R1'}, 'R1OuterDoor': {'R1InnerDoor', 'L1OuterDoor'}, 'R2InnerDoor': {'R2'}, 'R2OuterDoor': {'R2InnerDoor', 'HoruInnerDoor'}, 'R3': {'HoruR3ElevatorLever'}, 'R3InnerDoor': {'R3'}, 'R3OuterDoor': {'R3InnerDoor', 'HoruInnerDoor'}, 'R4': {'HoruR4StompHideout'}, 'R4InnerDoor': {'R4'}, 'R4OuterDoor': {'R4InnerDoor', 'HoruInnerDoor'}, 'RazielNoArea': {'GumoHideout', 'BlackrootGrottoConnection'}, 'SideFallCell': {'LeftGumoHideout', 'GumoHideout'}, 'SorrowBashLedge': {'LowerSorrow'}, 'SorrowMainShaftKeystoneArea': {'LowerSorrow'}, 'SorrowMapstoneArea': {'HoruInnerDoor'}, 'SorrowTeleporter': {'AboveChargeJumpArea', 'BelowSunstoneArea'}, 'SpiderSacArea': {'SpiritTreeRefined', 'SpiderWaterArea', 'SpiderSacTetherArea', 'SpiderSacEnergyNook'}, 'SpiderSacEnergyNook': {'ChargeFlameAreaPlantAccess'}, 'SpiderSacTetherArea': {'SpiderWaterArea', 'SpiderSacEnergyNook'}, 'SpiderWaterArea': {'HollowGrove', 'DeathGauntletRoof', 'SpiderSacEnergyNook', 'SpiderSacArea'}, 'SpiritCavernsDoor': {'SpiritCavernsDoorOpened'}, 'SpiritCavernsDoorOpened': {'LowerSpiritCaverns', 'GladesMain'}, 'SpiritTreeDoor': {'SpiritTreeDoorOpened'}, 'SpiritTreeDoorOpened': {'SpiritTreeRefined', 'UpperSpiritCaverns'}, 'SpiritTreeRefined': {'ChargeFlameAreaStump', 'SpiritTreeDoor', 'ChargeFlameSkillTreeChamber', 'ValleyEntry', 'SpiderSacArea'}, 'SunkenGladesRunaway': {'MoonGrotto', 'LowerChargeFlameArea', 'ValleyTeleporter', 'SorrowTeleporter', 'HoruTeleporter', 'GladesMain', 'GinsoTeleporter', 'SwampTeleporter', 'SpiritTreeRefined', 'BlackrootDarknessRoom', 'DeathGauntletDoor', 'ForlornTeleporter'}, 'SunstoneArea': {'SorrowTeleporter', 'UpperSorrow'}, 'Swamp': {'SwampKeyDoorPlatform', 'SwampDrainlessArea', 'SwampWater'}, 'SwampEntryArea': {'SwampDrainlessArea', 'Swamp'}, 'SwampKeyDoorOpened': {'RightSwamp'}, 'SwampKeyDoorPlatform': {'SwampKeyDoorOpened', 'InnerSwampSkyArea'}, 'SwampTeleporter': {'HollowGrove', 'OuterSwampMortarAbilityCellLedge'}, 'TopGinsoTree': {'GinsoEscape'}, 'UpperGinsoDoorClosed': {'UpperGinsoDoorOpened'}, 'UpperGinsoDoorOpened': {'GinsoTeleporter', 'UpperGinsoTree'}, 'UpperGinsoRedirectArea': {'UpperGinsoTree', 'BashTree'}, 'UpperGinsoTree': {'UpperGinsoDoorClosed', 'UpperGinsoRedirectArea'}, 'UpperGrotto': {'MoonGrottoStompPlantAccess', 'Iceless', 'MoonGrottoAboveTeleporter', 'OuterSwampMortarAbilityCellLedge', 'OuterSwampLowerArea'}, 'UpperLeftGlades': {'LeftGlades'}, 'UpperSorrow': {'SunstoneArea', 'MiddleSorrow', 'SorrowTeleporter', 'ChargeJumpDoor'}, 'UpperSpiritCaverns': {'SpiritTreeDoor', 'MidSpiritCaverns'}, 'ValleyEntry': {'ValleyThreeBirdLever', 'ValleyStompFloor', 'ValleyPostStompDoor', 'ValleyEntryTreePlantAccess', 'ValleyEntryTree', 'SpiritTreeRefined'}, 'ValleyEntryTree': {'ValleyPostStompDoor', 'ValleyEntryTreePlantAccess'}, 'ValleyForlornApproach': {'ValleyStompFloor', 'OutsideForlornCliff'}, 'ValleyMain': {'LowerValleyPlantApproach', 'LowerValley', 'MistyEntrance', 'WilhelmLedge', 'ValleyStompless'}, 'ValleyPostStompDoor': {'ValleyEntry', 'ValleyRight', 'ValleyEntryTree'}, 'ValleyRight': {'ValleyPostStompDoor', 'ValleyStomplessApproach'}, 'ValleyStompFloor': {'ValleyThreeBirdLever', 'ValleyEntry', 'ValleyForlornApproach'}, 'ValleyStompless': {'LowerValleyPlantApproach', 'ValleyMain', 'LowerValley', 'WilhelmLedge', 'MistyEntrance', 'ValleyStomplessApproach'}, 'ValleyStomplessApproach': {'ValleyRight', 'ValleyStompless'}, 'ValleyTeleporter': {'LowerValleyPlantApproach', 'ValleyRight', 'ValleyPostStompDoor', 'LowerValley', 'MistyEntrance', 'ValleyStompless'}, 'ValleyThreeBirdLever': {'ValleyStompFloor', 'ValleyEntry', 'LowerValley'}, 'WaterVeinArea': {'MoonGrotto', 'LeftGumoHideout', 'LowerLeftGumoHideout'}, 'WilhelmLedge': {'ValleyMain', 'SorrowBashLedge', 'ValleyStompless'}} <file_sep>from Options import Choice class ItemPool(Choice): """Valuable item pool moves all not progression relevant items to starting inventory and creates random duplicates of important items in their place.""" option_standard = 0 option_valuable = 1 options = { "item_pool": ItemPool } <file_sep># generated by https://github.com/Berserker66/HollowKnight.RandomizerMod/blob/master/extract_data.py # do not edit manually def create_regions(world, player: int): from . import create_region from .Items import item_table from .Locations import lookup_name_to_id world.regions += [ create_region(world, player, 'Menu', None, ['Hollow Nest S&Q']), create_region(world, player, 'Hollow Nest', [location for location in lookup_name_to_id] + [item_name for item_name, item_data in item_table.items() if item_data.type == "Event"]) ] <file_sep>colorama>=0.4.4 websockets>=10.0 PyYAML>=6.0 fuzzywuzzy>=0.18.0 prompt_toolkit>=3.0.20 appdirs>=1.4.4 jinja2>=3.0.2 schema>=0.7.4 <file_sep>import typing from Options import Choice, Option, Range, Toggle class Character(Choice): """Pick What Character you wish to play with.""" display_name = "Character" option_ironclad = 0 option_silent = 1 option_defect = 2 option_watcher = 3 default = 0 class Ascension(Range): """What Ascension do you wish to play with.""" display_name = "Ascension" range_start = 0 range_end = 20 default = 0 class HeartRun(Toggle): """Whether or not you will need to collect they 3 keys to unlock the final act and beat the heart to finish the game.""" display_name = "Heart Run" option_true = 1 option_false = 0 default = 0 spire_options: typing.Dict[str, type(Option)] = { "character": Character, "ascension": Ascension, "heart_run": HeartRun }<file_sep># Timespinner Randomizer Setup Guide ## Required Software - [Timespinner (steam)](https://store.steampowered.com/app/368620/Timespinner/) or [Timespinner (drm free)](https://www.humblebundle.com/store/timespinner) - [Timespinner Randomizer](https://github.com/JarnoWesthof/TsRandomizer) ## General Concept The timespinner Randomizer loads Timespinner.exe from the same folder, and alters its state in memory to allow for randomization of the items ## Installation Procedures Download latest version of [Timespinner Randomizer](https://github.com/JarnoWesthof/TsRandomizer) you can find the .zip files on the releases page, download the zip for your current platform. Then extract the zip to the folder where your Timespinner game is installed. Then just run TsRandomizer.exe instead of Timespinner.exe to start the game in randomized mode, for more info see the [readme](https://github.com/JarnoWesthof/TsRandomizer) ## Joining a MultiWorld Game 1. Run TsRandomizer.exe 2. Select "New Game" 3. Switch "<< Select Seed >>" to "<< Archiplago >>" by pressing left on the controller or keyboard 4. Select "<< Archiplago >>" to open a new menu where you can enter your Archipelago login credentails * NOTE: the input fields support Ctrl + V pasting of values 5. Select "Connect" 6. If all went well you will be taken back the difficulty selection menu and the game will start as soon as you select a difficulty ## YAML Settings An example YAML would look like this: ```yaml description: Default Timespinner Template name: Lunais{number} # Your name in-game. Spaces will be replaced with underscores and there is a 16 character limit game: Timespinner: 1 requires: version: 0.1.8 Timespinner: StartWithJewelryBox: # Start with Jewelry Box unlocked false: 50 true: 0 DownloadableItems: # With the tablet you will be able to download items at terminals false: 50 true: 50 FacebookMode: # Requires Oculus Rift(ng) to spot the weakspots in walls and floors false: 50 true: 0 StartWithMeyef: # Start with Meyef, ideal for when you want to play multiplayer false: 50 true: 50 QuickSeed: # Start with Talaria Attachment, Nyoom! false: 50 true: 0 SpecificKeycards: # Keycards can only open corresponding doors false: 0 true: 50 Inverted: # Start in the past false: 50 true: 50 ``` * All Options are either enabled or not, if values are specified for both true & false the generator will select one based on weight * The Timespinner Randomizer option "StinkyMaw" is currently always enabled for Archipelago generated seeds * The Timespinner Randomizer options "ProgressiveVerticalMovement" & "ProgressiveKeycards" are currently not supported on Archipelago generated seeds<file_sep>import worlds.minecraft.Options from test.TestBase import TestBase from BaseClasses import MultiWorld from worlds import AutoWorld from worlds.minecraft import MinecraftWorld from worlds.minecraft.Items import MinecraftItem, item_table from worlds.minecraft.Options import AdvancementGoal, CombatDifficulty, BeeTraps from Options import Toggle, Range # Converts the name of an item into an item object def MCItemFactory(items, player: int): ret = [] singleton = False if isinstance(items, str): items = [items] singleton = True for item in items: if item in item_table: ret.append(MinecraftItem(item, item_table[item].progression, item_table[item].code, player)) else: raise Exception(f"Unknown item {item}") if singleton: return ret[0] return ret class TestMinecraft(TestBase): def setUp(self): self.world = MultiWorld(1) self.world.game[1] = "Minecraft" self.world.worlds[1] = MinecraftWorld(self.world, 1) exclusion_pools = ['hard', 'insane', 'postgame'] for pool in exclusion_pools: setattr(self.world, f"include_{pool}_advancements", [False, False]) setattr(self.world, "advancement_goal", {1: AdvancementGoal(30)}) setattr(self.world, "shuffle_structures", {1: Toggle(False)}) setattr(self.world, "combat_difficulty", {1: CombatDifficulty(1)}) # normal setattr(self.world, "bee_traps", {1: BeeTraps(0)}) setattr(self.world, "structure_compasses", {1: Toggle(False)}) setattr(self.world, "egg_shards_required", {1: Range(0)}) setattr(self.world, "egg_shards_available", {1: Range(0)}) AutoWorld.call_single(self.world, "create_regions", 1) AutoWorld.call_single(self.world, "generate_basic", 1) AutoWorld.call_single(self.world, "set_rules", 1) def _get_items(self, item_pool, all_except): if all_except and len(all_except) > 0: items = self.world.itempool[:] items = [item for item in items if item.name not in all_except and not ("Bottle" in item.name and "AnyBottle" in all_except)] items.extend(MCItemFactory(item_pool[0], 1)) else: items = MCItemFactory(item_pool[0], 1) return self.get_state(items) def _get_items_partial(self, item_pool, missing_item): new_items = item_pool[0].copy() new_items.remove(missing_item) items = MCItemFactory(new_items, 1) return self.get_state(items) <file_sep>import string from BaseClasses import Item, MultiWorld, Region, Location, Entrance from .Items import item_table, item_pool, event_item_pairs from .Locations import location_table from .Regions import create_regions from .Rules import set_rules from ..AutoWorld import World from .Options import spire_options class SpireWorld(World): options = spire_options game = "Slay the Spire" topology_present = False data_version = 1 item_name_to_id = {name: data.code for name, data in item_table.items()} location_name_to_id = location_table forced_auto_forfeit = True def _get_slot_data(self): return { 'seed': "".join(self.world.slot_seeds[self.player].choice(string.ascii_letters) for i in range(16)), 'character': self.world.character[self.player], 'ascension': self.world.ascension[self.player], 'heart_run': self.world.heart_run[self.player] } def generate_basic(self): # Fill out our pool with our items from item_pool, assuming 1 item if not present in item_pool pool = [] for name, data in item_table.items(): if not data.event: if name in item_pool: card_draw = 0 for amount in range(item_pool[name]): item = SpireItem(name, self.player) # This feels wrong but it makes our failure rate drop dramatically # makes all but 7 basic card draws trash fill if item.name == "Card Draw": card_draw += 1 if card_draw > 7: item.advancement = False pool.append(item) else: item = SpireItem(name, self.player) pool.append(item) self.world.itempool += pool # Pair up our event locations with our event items for event, item in event_item_pairs.items(): event_item = SpireItem(item, self.player) self.world.get_location(event, self.player).place_locked_item(event_item) if self.world.logic[self.player] != 'no logic': self.world.completion_condition[self.player] = lambda state: state.has("Victory", self.player) def set_rules(self): set_rules(self.world, self.player) def create_item(self, name: str) -> Item: item_data = item_table[name] return Item(name, item_data.progression, item_data.code, self.player) def create_regions(self): create_regions(self.world, self.player) def fill_slot_data(self) -> dict: slot_data = self._get_slot_data() for option_name in spire_options: option = getattr(self.world, option_name)[self.player] slot_data[option_name] = int(option.value) return slot_data def create_region(world: MultiWorld, player: int, name: str, locations=None, exits=None): ret = Region(name, None, name, player) ret.world = world if locations: for location in locations: loc_id = location_table.get(location, 0) location = SpireLocation(player, location, loc_id, ret) ret.locations.append(location) if exits: for exit in exits: ret.exits.append(Entrance(player, exit, ret)) return ret class SpireLocation(Location): game: str = "Slay the Spire" def __init__(self, player: int, name: str, address=None, parent=None): super(SpireLocation, self).__init__(player, name, address, parent) if address is None: self.event = True self.locked = True class SpireItem(Item): game = "Slay the Spire" def __init__(self, name, player: int = None): item_data = item_table[name] super(SpireItem, self).__init__(name, item_data.progression, item_data.code, player) <file_sep>from itertools import zip_longest, chain import logging import os import time import zlib import concurrent.futures import pickle import tempfile import zipfile from typing import Dict, Tuple, Optional from BaseClasses import MultiWorld, CollectionState, Region, RegionType from worlds.alttp.Items import item_name_groups from worlds.alttp.Regions import lookup_vanilla_location_to_entrance from Fill import distribute_items_restrictive, flood_items, balance_multiworld_progression, distribute_planned from worlds.alttp.Shops import SHOP_ID_START, total_shop_slots, FillDisabledShopSlots from Utils import output_path, get_options, __version__, version_tuple from worlds.generic.Rules import locality_rules, exclusion_rules from worlds import AutoWorld ordered_areas = ( 'Light World', 'Dark World', 'Hyrule Castle', 'Agahnims Tower', 'Eastern Palace', 'Desert Palace', 'Tower of Hera', 'Palace of Darkness', 'Swamp Palace', 'Skull Woods', 'Thieves Town', 'Ice Palace', 'Misery Mire', 'Turtle Rock', 'Ganons Tower', "Total" ) def main(args, seed=None, baked_server_options: Optional[Dict[str, object]] = None): if not baked_server_options: baked_server_options = get_options()["server_options"] if args.outputpath: os.makedirs(args.outputpath, exist_ok=True) output_path.cached_path = args.outputpath start = time.perf_counter() # initialize the world world = MultiWorld(args.multi) logger = logging.getLogger() world.set_seed(seed, args.race, str(args.outputname if args.outputname else world.seed)) world.shuffle = args.shuffle.copy() world.logic = args.logic.copy() world.mode = args.mode.copy() world.difficulty = args.difficulty.copy() world.item_functionality = args.item_functionality.copy() world.timer = args.timer.copy() world.goal = args.goal.copy() if hasattr(args, "algorithm"): # current GUI options world.algorithm = args.algorithm world.shuffleganon = args.shuffleganon world.custom = args.custom world.customitemarray = args.customitemarray world.open_pyramid = args.open_pyramid.copy() world.boss_shuffle = args.shufflebosses.copy() world.enemy_health = args.enemy_health.copy() world.enemy_damage = args.enemy_damage.copy() world.beemizer_total_chance = args.beemizer_total_chance.copy() world.beemizer_trap_chance = args.beemizer_trap_chance.copy() world.timer = args.timer.copy() world.countdown_start_time = args.countdown_start_time.copy() world.red_clock_time = args.red_clock_time.copy() world.blue_clock_time = args.blue_clock_time.copy() world.green_clock_time = args.green_clock_time.copy() world.dungeon_counters = args.dungeon_counters.copy() world.triforce_pieces_available = args.triforce_pieces_available.copy() world.triforce_pieces_required = args.triforce_pieces_required.copy() world.shop_shuffle = args.shop_shuffle.copy() world.shuffle_prizes = args.shuffle_prizes.copy() world.sprite_pool = args.sprite_pool.copy() world.dark_room_logic = args.dark_room_logic.copy() world.plando_items = args.plando_items.copy() world.plando_texts = args.plando_texts.copy() world.plando_connections = args.plando_connections.copy() world.required_medallions = args.required_medallions.copy() world.game = args.game.copy() world.set_options(args) world.player_name = args.name.copy() world.enemizer = args.enemizercli world.sprite = args.sprite.copy() world.glitch_triforce = args.glitch_triforce # This is enabled/disabled globally, no per player option. logger.info('Archipelago Version %s - Seed: %s\n', __version__, world.seed) logger.info("Found World Types:") longest_name = max(len(text) for text in AutoWorld.AutoWorldRegister.world_types) numlength = 8 for name, cls in AutoWorld.AutoWorldRegister.world_types.items(): if not cls.hidden: logger.info(f" {name:{longest_name}}: {len(cls.item_names):3} Items | " f"{len(cls.location_names):3} Locations") logger.info(f" Item IDs: {min(cls.item_id_to_name):{numlength}} - " f"{max(cls.item_id_to_name):{numlength}} | " f"Location IDs: {min(cls.location_id_to_name):{numlength}} - " f"{max(cls.location_id_to_name):{numlength}}") AutoWorld.call_all(world, "generate_early") logger.info('') for player in world.player_ids: for item_name, count in world.start_inventory[player].value.items(): for _ in range(count): world.push_precollected(world.create_item(item_name, player)) for player in world.player_ids: if player in world.get_game_players("A Link to the Past"): # enforce pre-defined local items. if world.goal[player] in ["localtriforcehunt", "localganontriforcehunt"]: world.local_items[player].value.add('Triforce Piece') # Not possible to place pendants/crystals out side of boss prizes yet. world.non_local_items[player].value -= item_name_groups['Pendants'] world.non_local_items[player].value -= item_name_groups['Crystals'] # items can't be both local and non-local, prefer local world.non_local_items[player].value -= world.local_items[player].value logger.info('Creating World.') AutoWorld.call_all(world, "create_regions") logger.info('Creating Items.') AutoWorld.call_all(world, "create_items") logger.info('Calculating Access Rules.') if world.players > 1: for player in world.player_ids: locality_rules(world, player) else: world.non_local_items[1].value = set() world.local_items[1].value = set() AutoWorld.call_all(world, "set_rules") for player in world.player_ids: exclusion_rules(world, player, world.exclude_locations[player].value) AutoWorld.call_all(world, "generate_basic") logger.info("Running Item Plando") for item in world.itempool: item.world = world distribute_planned(world) logger.info('Running Pre Main Fill.') AutoWorld.call_all(world, "pre_fill") logger.info(f'Filling the world with {len(world.itempool)} items.') if world.algorithm == 'flood': flood_items(world) # different algo, biased towards early game progress items elif world.algorithm == 'balanced': distribute_items_restrictive(world) AutoWorld.call_all(world, 'post_fill') if world.players > 1: balance_multiworld_progression(world) logger.info(f'Beginning output...') outfilebase = 'AP_' + world.seed_name output = tempfile.TemporaryDirectory() with output as temp_dir: with concurrent.futures.ThreadPoolExecutor(world.players + 2) as pool: check_accessibility_task = pool.submit(world.fulfills_accessibility) output_file_futures = [pool.submit(AutoWorld.call_stage, world, "generate_output", temp_dir)] for player in world.player_ids: # skip starting a thread for methods that say "pass". if AutoWorld.World.generate_output.__code__ is not world.worlds[player].generate_output.__code__: output_file_futures.append( pool.submit(AutoWorld.call_single, world, "generate_output", player, temp_dir)) def get_entrance_to_region(region: Region): for entrance in region.entrances: if entrance.parent_region.type in (RegionType.DarkWorld, RegionType.LightWorld, RegionType.Generic): return entrance for entrance in region.entrances: # BFS might be better here, trying DFS for now. return get_entrance_to_region(entrance.parent_region) # collect ER hint info er_hint_data = {player: {} for player in world.get_game_players("A Link to the Past") if world.shuffle[player] != "vanilla" or world.retro[player]} for region in world.regions: if region.player in er_hint_data and region.locations: main_entrance = get_entrance_to_region(region) for location in region.locations: if type(location.address) == int: # skips events and crystals if lookup_vanilla_location_to_entrance[location.address] != main_entrance.name: er_hint_data[region.player][location.address] = main_entrance.name checks_in_area = {player: {area: list() for area in ordered_areas} for player in range(1, world.players + 1)} for player in range(1, world.players + 1): checks_in_area[player]["Total"] = 0 for location in world.get_filled_locations(): if type(location.address) is int: main_entrance = get_entrance_to_region(location.parent_region) if location.game != "A Link to the Past": checks_in_area[location.player]["Light World"].append(location.address) elif location.parent_region.dungeon: dungeonname = {'Inverted Agahnims Tower': 'Agahnims Tower', 'Inverted Ganons Tower': 'Ganons Tower'} \ .get(location.parent_region.dungeon.name, location.parent_region.dungeon.name) checks_in_area[location.player][dungeonname].append(location.address) elif main_entrance.parent_region.type == RegionType.LightWorld: checks_in_area[location.player]["Light World"].append(location.address) elif main_entrance.parent_region.type == RegionType.DarkWorld: checks_in_area[location.player]["Dark World"].append(location.address) checks_in_area[location.player]["Total"] += 1 oldmancaves = [] takeanyregions = ["Old Man Sword Cave", "Take-Any #1", "Take-Any #2", "Take-Any #3", "Take-Any #4"] for index, take_any in enumerate(takeanyregions): for region in [world.get_region(take_any, player) for player in world.get_game_players("A Link to the Past") if world.retro[player]]: item = world.create_item( region.shop.inventory[(0 if take_any == "Old Man Sword Cave" else 1)]['item'], region.player) player = region.player location_id = SHOP_ID_START + total_shop_slots + index main_entrance = get_entrance_to_region(region) if main_entrance.parent_region.type == RegionType.LightWorld: checks_in_area[player]["Light World"].append(location_id) else: checks_in_area[player]["Dark World"].append(location_id) checks_in_area[player]["Total"] += 1 er_hint_data[player][location_id] = main_entrance.name oldmancaves.append(((location_id, player), (item.code, player))) FillDisabledShopSlots(world) def write_multidata(): import NetUtils slot_data = {} client_versions = {} minimum_versions = {"server": (0, 1, 8), "clients": client_versions} games = {} for slot in world.player_ids: client_versions[slot] = world.worlds[slot].get_required_client_version() games[slot] = world.game[slot] precollected_items = {player: [item.code for item in world_precollected] for player, world_precollected in world.precollected_items.items()} precollected_hints = {player: set() for player in range(1, world.players + 1)} # for now special case Factorio tech_tree_information sending_visible_players = set() for slot in world.player_ids: slot_data[slot] = world.worlds[slot].fill_slot_data() if world.worlds[slot].sending_visible: sending_visible_players.add(slot) def precollect_hint(location): hint = NetUtils.Hint(location.item.player, location.player, location.address, location.item.code, False) precollected_hints[location.player].add(hint) precollected_hints[location.item.player].add(hint) locations_data: Dict[int, Dict[int, Tuple[int, int]]] = {player: {} for player in world.player_ids} for location in world.get_filled_locations(): if type(location.address) == int: # item code None should be event, location.address should then also be None assert location.item.code is not None locations_data[location.player][location.address] = location.item.code, location.item.player if location.player in sending_visible_players: precollect_hint(location) elif location.name in world.start_location_hints[location.player]: precollect_hint(location) elif location.item.name in world.start_hints[location.item.player]: precollect_hint(location) multidata = { "slot_data": slot_data, "games": games, "names": [[name for player, name in sorted(world.player_name.items())]], "connect_names": {name: (0, player) for player, name in world.player_name.items()}, "remote_items": {player for player in world.player_ids if world.worlds[player].remote_items}, "remote_start_inventory": {player for player in world.player_ids if world.worlds[player].remote_start_inventory}, "locations": locations_data, "checks_in_area": checks_in_area, "server_options": baked_server_options, "er_hint_data": er_hint_data, "precollected_items": precollected_items, "precollected_hints": precollected_hints, "version": tuple(version_tuple), "tags": ["AP"], "minimum_versions": minimum_versions, "seed_name": world.seed_name } AutoWorld.call_all(world, "modify_multidata", multidata) multidata = zlib.compress(pickle.dumps(multidata), 9) with open(os.path.join(temp_dir, f'{outfilebase}.archipelago'), 'wb') as f: f.write(bytes([1])) # version of format f.write(multidata) multidata_task = pool.submit(write_multidata) if not check_accessibility_task.result(): if not world.can_beat_game(): raise Exception("Game appears as unbeatable. Aborting.") else: logger.warning("Location Accessibility requirements not fulfilled.") # retrieve exceptions via .result() if they occured. if multidata_task: multidata_task.result() for i, future in enumerate(concurrent.futures.as_completed(output_file_futures), start=1): if i % 10 == 0 or i == len(output_file_futures): logger.info(f'Generating output files ({i}/{len(output_file_futures)}).') future.result() if args.spoiler > 1: logger.info('Calculating playthrough.') create_playthrough(world) if args.spoiler: world.spoiler.to_file(os.path.join(temp_dir, '%s_Spoiler.txt' % outfilebase)) zipfilename = output_path(f"AP_{world.seed_name}.zip") logger.info(f'Creating final archive at {zipfilename}.') with zipfile.ZipFile(zipfilename, mode="w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zf: for file in os.scandir(temp_dir): zf.write(file.path, arcname=file.name) logger.info('Done. Enjoy. Total Time: %s', time.perf_counter() - start) return world def create_playthrough(world): """Destructive to the world while it is run, damage gets repaired afterwards.""" # get locations containing progress items prog_locations = {location for location in world.get_filled_locations() if location.item.advancement} state_cache = [None] collection_spheres = [] state = CollectionState(world) sphere_candidates = set(prog_locations) logging.debug('Building up collection spheres.') while sphere_candidates: # build up spheres of collection radius. # Everything in each sphere is independent from each other in dependencies and only depends on lower spheres sphere = {location for location in sphere_candidates if state.can_reach(location)} for location in sphere: state.collect(location.item, True, location) sphere_candidates -= sphere collection_spheres.append(sphere) state_cache.append(state.copy()) logging.debug('Calculated sphere %i, containing %i of %i progress items.', len(collection_spheres), len(sphere), len(prog_locations)) if not sphere: logging.debug('The following items could not be reached: %s', ['%s (Player %d) at %s (Player %d)' % ( location.item.name, location.item.player, location.name, location.player) for location in sphere_candidates]) if any([world.accessibility[location.item.player] != 'minimal' for location in sphere_candidates]): raise RuntimeError(f'Not all progression items reachable ({sphere_candidates}). ' f'Something went terribly wrong here.') else: world.spoiler.unreachables = sphere_candidates break # in the second phase, we cull each sphere such that the game is still beatable, # reducing each range of influence to the bare minimum required inside it restore_later = {} for num, sphere in reversed(tuple(enumerate(collection_spheres))): to_delete = set() for location in sphere: # we remove the item at location and check if game is still beatable logging.debug('Checking if %s (Player %d) is required to beat the game.', location.item.name, location.item.player) old_item = location.item location.item = None if world.can_beat_game(state_cache[num]): to_delete.add(location) restore_later[location] = old_item else: # still required, got to keep it around location.item = old_item # cull entries in spheres for spoiler walkthrough at end sphere -= to_delete # second phase, sphere 0 removed_precollected = [] for item in (i for i in chain.from_iterable(world.precollected_items.values()) if i.advancement): logging.debug('Checking if %s (Player %d) is required to beat the game.', item.name, item.player) world.precollected_items[item.player].remove(item) world.state.remove(item) if not world.can_beat_game(): world.push_precollected(item) else: removed_precollected.append(item) # we are now down to just the required progress items in collection_spheres. Unfortunately # the previous pruning stage could potentially have made certain items dependant on others # in the same or later sphere (because the location had 2 ways to access but the item originally # used to access it was deemed not required.) So we need to do one final sphere collection pass # to build up the correct spheres required_locations = {item for sphere in collection_spheres for item in sphere} state = CollectionState(world) collection_spheres = [] while required_locations: state.sweep_for_events(key_only=True) sphere = set(filter(state.can_reach, required_locations)) for location in sphere: state.collect(location.item, True, location) required_locations -= sphere collection_spheres.append(sphere) logging.debug('Calculated final sphere %i, containing %i of %i progress items.', len(collection_spheres), len(sphere), len(required_locations)) if not sphere: raise RuntimeError(f'Not all required items reachable. Unreachable locations: {required_locations}') def flist_to_iter(node): while node: value, node = node yield value def get_path(state, region): reversed_path_as_flist = state.path.get(region, (region, None)) string_path_flat = reversed(list(map(str, flist_to_iter(reversed_path_as_flist)))) # Now we combine the flat string list into (region, exit) pairs pathsiter = iter(string_path_flat) pathpairs = zip_longest(pathsiter, pathsiter) return list(pathpairs) world.spoiler.paths = {} topology_worlds = (player for player in world.player_ids if world.worlds[player].topology_present) for player in topology_worlds: world.spoiler.paths.update( {str(location): get_path(state, location.parent_region) for sphere in collection_spheres for location in sphere if location.player == player}) if player in world.get_game_players("A Link to the Past"): # If Pyramid Fairy Entrance needs to be reached, also path to Big Bomb Shop # Maybe move the big bomb over to the Event system instead? if any(exit_path == 'Pyramid Fairy' for path in world.spoiler.paths.values() for (_, exit_path) in path): if world.mode[player] != 'inverted': world.spoiler.paths[str(world.get_region('Big Bomb Shop', player))] = \ get_path(state, world.get_region('Big Bomb Shop', player)) else: world.spoiler.paths[str(world.get_region('Inverted Big Bomb Shop', player))] = \ get_path(state, world.get_region('Inverted Big Bomb Shop', player)) # we can finally output our playthrough world.spoiler.playthrough = {"0": sorted([str(item) for item in chain.from_iterable(world.precollected_items.values()) if item.advancement])} for i, sphere in enumerate(collection_spheres): world.spoiler.playthrough[str(i + 1)] = {str(location): str(location.item) for location in sorted(sphere)} # repair the world again for location, item in restore_later.items(): location.item = item for item in removed_precollected: world.push_precollected(item) <file_sep>from argparse import Namespace from BaseClasses import MultiWorld from worlds.alttp.Dungeons import create_dungeons, get_dungeon_item_pool from worlds.alttp.EntranceShuffle import link_entrances from worlds.alttp.InvertedRegions import mark_dark_world_regions from worlds.alttp.ItemPool import difficulties, generate_itempool from worlds.alttp.Items import ItemFactory from worlds.alttp.Regions import create_regions from worlds.alttp.Shops import create_shops from worlds.alttp.Rules import set_rules from test.TestBase import TestBase from worlds import AutoWorld class TestVanillaOWG(TestBase): def setUp(self): self.world = MultiWorld(1) args = Namespace() for name, option in AutoWorld.AutoWorldRegister.world_types["A Link to the Past"].options.items(): setattr(args, name, {1: option.from_any(option.default)}) self.world.set_options(args) self.world.set_default_common_options() self.world.difficulty_requirements[1] = difficulties['normal'] self.world.logic[1] = "owglitches" create_regions(self.world, 1) create_dungeons(self.world, 1) create_shops(self.world, 1) link_entrances(self.world, 1) self.world.worlds[1].create_items() self.world.required_medallions[1] = ['Ether', 'Quake'] self.world.itempool.extend(get_dungeon_item_pool(self.world)) self.world.itempool.extend(ItemFactory(['Green Pendant', 'Red Pendant', 'Blue Pendant', 'Beat Agahnim 1', 'Beat Agahnim 2', 'Crystal 1', 'Crystal 2', 'Crystal 3', 'Crystal 4', 'Crystal 5', 'Crystal 6', 'Crystal 7'], 1)) self.world.get_location('Agahnim 1', 1).item = None self.world.get_location('Agahnim 2', 1).item = None self.world.precollected_items[1].clear() self.world.itempool.append(ItemFactory('Pegasus Boots', 1)) mark_dark_world_regions(self.world, 1) self.world.worlds[1].set_rules()<file_sep>let gameName = null; window.addEventListener('load', () => { gameName = document.getElementById('player-settings').getAttribute('data-game'); // Update game name on page document.getElementById('game-name').innerText = gameName; Promise.all([fetchSettingData()]).then((results) => { let settingHash = localStorage.getItem(`${gameName}-hash`); if (!settingHash) { // If no hash data has been set before, set it now localStorage.setItem(`${gameName}-hash`, md5(results[0])); localStorage.removeItem(gameName); settingHash = md5(results[0]); } if (settingHash !== md5(results[0])) { const userMessage = document.getElementById('user-message'); userMessage.innerText = "Your settings are out of date! Click here to update them! Be aware this will reset " + "them all to default."; userMessage.style.display = "block"; userMessage.addEventListener('click', resetSettings); } // Page setup createDefaultSettings(results[0]); buildUI(results[0]); adjustHeaderWidth(); // Event listeners document.getElementById('export-settings').addEventListener('click', () => exportSettings()); document.getElementById('generate-race').addEventListener('click', () => generateGame(true)); document.getElementById('generate-game').addEventListener('click', () => generateGame()); // Name input field const playerSettings = JSON.parse(localStorage.getItem(gameName)); const nameInput = document.getElementById('player-name'); nameInput.addEventListener('keyup', (event) => updateBaseSetting(event)); nameInput.value = playerSettings.name; }).catch((error) => { const url = new URL(window.location.href); window.location.replace(`${url.protocol}//${url.hostname}/page-not-found`); }) }); const resetSettings = () => { localStorage.removeItem(gameName); localStorage.removeItem(`${gameName}-hash`) window.location.reload(); }; const fetchSettingData = () => new Promise((resolve, reject) => { const ajax = new XMLHttpRequest(); ajax.onreadystatechange = () => { if (ajax.readyState !== 4) { return; } if (ajax.status !== 200) { reject(ajax.responseText); return; } try{ resolve(JSON.parse(ajax.responseText)); } catch(error){ reject(error); } }; ajax.open('GET', `${window.location.origin}/static/generated/player-settings/${gameName}.json`, true); ajax.send(); }); const createDefaultSettings = (settingData) => { if (!localStorage.getItem(gameName)) { const newSettings = { [gameName]: {}, }; for (let baseOption of Object.keys(settingData.baseOptions)){ newSettings[baseOption] = settingData.baseOptions[baseOption]; } for (let gameOption of Object.keys(settingData.gameOptions)){ newSettings[gameName][gameOption] = settingData.gameOptions[gameOption].defaultValue; } localStorage.setItem(gameName, JSON.stringify(newSettings)); } }; const buildUI = (settingData) => { // Game Options const leftGameOpts = {}; const rightGameOpts = {}; Object.keys(settingData.gameOptions).forEach((key, index) => { if (index < Object.keys(settingData.gameOptions).length / 2) { leftGameOpts[key] = settingData.gameOptions[key]; } else { rightGameOpts[key] = settingData.gameOptions[key]; } }); document.getElementById('game-options-left').appendChild(buildOptionsTable(leftGameOpts)); document.getElementById('game-options-right').appendChild(buildOptionsTable(rightGameOpts)); }; const buildOptionsTable = (settings, romOpts = false) => { const currentSettings = JSON.parse(localStorage.getItem(gameName)); const table = document.createElement('table'); const tbody = document.createElement('tbody'); Object.keys(settings).forEach((setting) => { const tr = document.createElement('tr'); // td Left const tdl = document.createElement('td'); const label = document.createElement('label'); label.setAttribute('for', setting); label.setAttribute('data-tooltip', settings[setting].description); label.innerText = `${settings[setting].displayName}:`; tdl.appendChild(label); tr.appendChild(tdl); // td Right const tdr = document.createElement('td'); let element = null; switch(settings[setting].type){ case 'select': element = document.createElement('div'); element.classList.add('select-container'); let select = document.createElement('select'); select.setAttribute('id', setting); select.setAttribute('data-key', setting); if (romOpts) { select.setAttribute('data-romOpt', '1'); } settings[setting].options.forEach((opt) => { const option = document.createElement('option'); option.setAttribute('value', opt.value); option.innerText = opt.name; if ((isNaN(currentSettings[gameName][setting]) && (parseInt(opt.value, 10) === parseInt(currentSettings[gameName][setting]))) || (opt.value === currentSettings[gameName][setting])) { option.selected = true; } select.appendChild(option); }); select.addEventListener('change', (event) => updateGameSetting(event)); element.appendChild(select); break; case 'range': element = document.createElement('div'); element.classList.add('range-container'); let range = document.createElement('input'); range.setAttribute('type', 'range'); range.setAttribute('data-key', setting); range.setAttribute('min', settings[setting].min); range.setAttribute('max', settings[setting].max); range.value = currentSettings[gameName][setting]; range.addEventListener('change', (event) => { document.getElementById(`${setting}-value`).innerText = event.target.value; updateGameSetting(event); }); element.appendChild(range); let rangeVal = document.createElement('span'); rangeVal.classList.add('range-value'); rangeVal.setAttribute('id', `${setting}-value`); rangeVal.innerText = currentSettings[gameName][setting] ?? settings[setting].defaultValue; element.appendChild(rangeVal); break; default: console.error(`Unknown setting type: ${settings[setting].type}`); console.error(setting); return; } tdr.appendChild(element); tr.appendChild(tdr); tbody.appendChild(tr); }); table.appendChild(tbody); return table; }; const updateBaseSetting = (event) => { const options = JSON.parse(localStorage.getItem(gameName)); options[event.target.getAttribute('data-key')] = isNaN(event.target.value) ? event.target.value : parseInt(event.target.value); localStorage.setItem(gameName, JSON.stringify(options)); }; const updateGameSetting = (event) => { const options = JSON.parse(localStorage.getItem(gameName)); options[gameName][event.target.getAttribute('data-key')] = isNaN(event.target.value) ? event.target.value : parseInt(event.target.value, 10); localStorage.setItem(gameName, JSON.stringify(options)); }; const exportSettings = () => { const settings = JSON.parse(localStorage.getItem(gameName)); if (!settings.name || settings.name.trim().length === 0) { settings.name = "noname"; } const yamlText = jsyaml.safeDump(settings, { noCompatMode: true }).replaceAll(/'(\d+)':/g, (x, y) => `${y}:`); download(`${document.getElementById('player-name').value}.yaml`, yamlText); }; /** Create an anchor and trigger a download of a text file. */ const download = (filename, text) => { const downloadLink = document.createElement('a'); downloadLink.setAttribute('href','data:text/yaml;charset=utf-8,'+ encodeURIComponent(text)) downloadLink.setAttribute('download', filename); downloadLink.style.display = 'none'; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); }; const generateGame = (raceMode = false) => { axios.post('/api/generate', { weights: { player: localStorage.getItem(gameName) }, presetData: { player: localStorage.getItem(gameName) }, playerCount: 1, race: raceMode ? '1' : '0', }).then((response) => { window.location.href = response.data.url; }).catch((error) => { const userMessage = document.getElementById('user-message'); userMessage.innerText = 'Something went wrong and your game could not be generated.'; if (error.response.data.text) { userMessage.innerText += ' ' + error.response.data.text; } userMessage.classList.add('visible'); window.scrollTo(0, 0); console.error(error); }); }; <file_sep>from BaseClasses import Location import typing class RiskOfRainLocation(Location): game: str = "Risk of Rain 2" # 37000 - 38000 base_location_table = { "Victory": None, "Level One": None, "Level Two": None, "Level Three": None, "Level Four": None, "Level Five": None } # 37006 - 37106 item_pickups = { f"ItemPickup{i}": 37005+i for i in range(1, 101) } location_table = {**base_location_table, **item_pickups} lookup_id_to_name: typing.Dict[int, str] = {id: name for name, id in location_table.items()} <file_sep>import os import sys import subprocess import pkg_resources requirements_files = {'requirements.txt'} if sys.version_info < (3, 8, 6): raise RuntimeError("Incompatible Python Version. 3.8.7+ is supported.") update_ran = getattr(sys, "frozen", False) # don't run update if environment is frozen/compiled if not update_ran: for entry in os.scandir("worlds"): if entry.is_dir(): req_file = os.path.join(entry.path, "requirements.txt") if os.path.exists(req_file): requirements_files.add(req_file) def update_command(): for file in requirements_files: subprocess.call([sys.executable, '-m', 'pip', 'install', '-r', file, '--upgrade']) def update(yes = False, force = False): global update_ran if not update_ran: update_ran = True if force: update_command() return for req_file in requirements_files: path = os.path.join(os.path.dirname(sys.argv[0]), req_file) if not os.path.exists(path): path = os.path.join(os.path.dirname(__file__), req_file) with open(path) as requirementsfile: requirements = pkg_resources.parse_requirements(requirementsfile) for requirement in requirements: requirement = str(requirement) try: pkg_resources.require(requirement) except pkg_resources.ResolutionError: if not yes: import traceback traceback.print_exc() input(f'Requirement {requirement} is not satisfied, press enter to install it') update_command() return if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Install archipelago requirements') parser.add_argument('-y', '--yes', dest='yes', action='store_true', help='answer "yes" to all questions') parser.add_argument('-f', '--force', dest='force', action='store_true', help='force update') args = parser.parse_args() update(args.yes, args.force) <file_sep>import logging import threading import copy from collections import Counter logger = logging.getLogger("Ocarina of Time") from .Location import OOTLocation, LocationFactory, location_name_to_id from .Entrance import OOTEntrance from .EntranceShuffle import shuffle_random_entrances from .Items import OOTItem, item_table, oot_data_to_ap_id from .ItemPool import generate_itempool, add_dungeon_items, get_junk_item, get_junk_pool from .Regions import OOTRegion, TimeOfDay from .Rules import set_rules, set_shop_rules, set_entrances_based_rules from .RuleParser import Rule_AST_Transformer from .Options import oot_options from .Utils import data_path, read_json from .LocationList import business_scrubs, set_drop_location_names from .DungeonList import dungeon_table, create_dungeons from .LogicTricks import normalized_name_tricks from .Rom import Rom from .Patches import patch_rom from .N64Patch import create_patch_file from .Cosmetics import patch_cosmetics from .Hints import hint_dist_keys, get_hint_area, buildWorldGossipHints from .HintList import getRequiredHints from Utils import get_options, output_path from BaseClasses import MultiWorld, CollectionState, RegionType from Options import Range, Toggle, OptionList from Fill import fill_restrictive, FillError from worlds.generic.Rules import exclusion_rules from ..AutoWorld import World location_id_offset = 67000 # OoT's generate_output doesn't benefit from more than 2 threads, instead it uses a lot of memory. i_o_limiter = threading.Semaphore(2) class OOTWorld(World): game: str = "Ocarina of Time" options: dict = oot_options topology_present: bool = True item_name_to_id = {item_name: oot_data_to_ap_id(data, False) for item_name, data in item_table.items() if data[2] is not None} location_name_to_id = location_name_to_id remote_items: bool = False remote_start_inventory: bool = False data_version = 1 def __new__(cls, world, player): # Add necessary objects to CollectionState on initialization orig_init = CollectionState.__init__ orig_copy = CollectionState.copy def oot_init(self, parent: MultiWorld): orig_init(self, parent) self.child_reachable_regions = {player: set() for player in range(1, parent.players + 1)} self.adult_reachable_regions = {player: set() for player in range(1, parent.players + 1)} self.child_blocked_connections = {player: set() for player in range(1, parent.players + 1)} self.adult_blocked_connections = {player: set() for player in range(1, parent.players + 1)} self.age = {player: None for player in range(1, parent.players + 1)} def oot_copy(self): ret = orig_copy(self) ret.child_reachable_regions = {player: copy.copy(self.child_reachable_regions[player]) for player in range(1, self.world.players + 1)} ret.adult_reachable_regions = {player: copy.copy(self.adult_reachable_regions[player]) for player in range(1, self.world.players + 1)} ret.child_blocked_connections = {player: copy.copy(self.child_blocked_connections[player]) for player in range(1, self.world.players + 1)} ret.adult_blocked_connections = {player: copy.copy(self.adult_blocked_connections[player]) for player in range(1, self.world.players + 1)} return ret CollectionState.__init__ = oot_init CollectionState.copy = oot_copy # also need to add the names to the passed MultiWorld's CollectionState, since it was initialized before we could get to it if world: world.state.child_reachable_regions = {player: set() for player in range(1, world.players + 1)} world.state.adult_reachable_regions = {player: set() for player in range(1, world.players + 1)} world.state.child_blocked_connections = {player: set() for player in range(1, world.players + 1)} world.state.adult_blocked_connections = {player: set() for player in range(1, world.players + 1)} world.state.age = {player: None for player in range(1, world.players + 1)} return super().__new__(cls) def __init__(self, world, player): self.hint_data_available = threading.Event() super(OOTWorld, self).__init__(world, player) def generate_early(self): # Player name MUST be at most 16 bytes ascii-encoded, otherwise won't write to ROM correctly if len(bytes(self.world.get_player_name(self.player), 'ascii')) > 16: raise Exception( f"OoT: Player {self.player}'s name ({self.world.get_player_name(self.player)}) must be ASCII-compatible") self.parser = Rule_AST_Transformer(self, self.player) for (option_name, option) in oot_options.items(): result = getattr(self.world, option_name)[self.player] if isinstance(result, Range): option_value = int(result) elif isinstance(result, Toggle): option_value = bool(result) elif isinstance(result, OptionList): option_value = result.value else: option_value = result.current_key setattr(self, option_name, option_value) self.shop_prices = {} self.regions = [] # internal cache of regions for this world, used later self.remove_from_start_inventory = [] # some items will be precollected but not in the inventory self.starting_items = Counter() self.starting_songs = False # whether starting_items contains a song self.file_hash = [self.world.random.randint(0, 31) for i in range(5)] self.item_name_groups = { "medallions": {"Light Medallion", "Forest Medallion", "Fire Medallion", "Water Medallion", "Shadow Medallion", "Spirit Medallion"}, "stones": {"<NAME>", "<NAME>", "Zora Sapphire"}, "rewards": {"Light Medallion", "Forest Medallion", "Fire Medallion", "Water Medallion", "Shadow Medallion", "Spirit Medallion", \ "<NAME>", "<NAME>", "Zora Sapphire"}, "bottles": {"Bottle", "Bottle with Milk", "Deliver Letter", "Sell Big Poe", "Bottle with Red Potion", "Bottle with Green Potion", \ "Bottle with Blue Potion", "Bottle with Fairy", "Bottle with Fish", "Bottle with Blue Fire", "Bottle with Bugs", "Bottle with Poe"} } # Incompatible option handling # ER and glitched logic are not compatible; glitched takes priority if self.logic_rules == 'glitched': self.shuffle_interior_entrances = False self.shuffle_grotto_entrances = False self.shuffle_dungeon_entrances = False self.shuffle_overworld_entrances = False self.owl_drops = False self.warp_songs = False self.spawn_positions = False # Closed forest and adult start are not compatible; closed forest takes priority if self.open_forest == 'closed': self.starting_age = 'child' # Skip child zelda and shuffle egg are not compatible; skip-zelda takes priority if self.skip_child_zelda: self.shuffle_weird_egg = False # Determine skipped trials in GT # This needs to be done before the logic rules in GT are parsed trial_list = ['Forest', 'Fire', 'Water', 'Spirit', 'Shadow', 'Light'] chosen_trials = self.world.random.sample(trial_list, self.trials) # chooses a list of trials to NOT skip self.skipped_trials = {trial: (trial not in chosen_trials) for trial in trial_list} # Determine which dungeons are MQ # Possible future plan: allow user to pick which dungeons are MQ mq_dungeons = self.world.random.sample(dungeon_table, self.mq_dungeons) self.dungeon_mq = {item['name']: (item in mq_dungeons) for item in dungeon_table} # Determine tricks in logic for trick in self.logic_tricks: normalized_name = trick.casefold() if normalized_name in normalized_name_tricks: setattr(self, normalized_name_tricks[normalized_name]['name'], True) else: raise Exception(f'Unknown OOT logic trick for player {self.player}: {trick}') # Not implemented for now, but needed to placate the generator. Remove as they are implemented self.mq_dungeons_random = False # this will be a deprecated option later self.ocarina_songs = False # just need to pull in the OcarinaSongs module self.big_poe_count = 1 # disabled due to client-side issues for now # ER options self.shuffle_interior_entrances = 'off' self.shuffle_grotto_entrances = False self.shuffle_dungeon_entrances = False self.shuffle_overworld_entrances = False self.owl_drops = False self.warp_songs = False self.spawn_positions = False # Set internal names used by the OoT generator self.keysanity = self.shuffle_smallkeys in ['keysanity', 'remove', 'any_dungeon', 'overworld'] # Hint stuff self.misc_hints = True # this is just always on self.clearer_hints = True # this is being enforced since non-oot items do not have non-clear hint text self.gossip_hints = {} self.required_locations = [] self.empty_areas = {} self.major_item_locations = [] # ER names self.ensure_tod_access = (self.shuffle_interior_entrances != 'off') or self.shuffle_overworld_entrances or self.spawn_positions self.entrance_shuffle = (self.shuffle_interior_entrances != 'off') or self.shuffle_grotto_entrances or self.shuffle_dungeon_entrances or \ self.shuffle_overworld_entrances or self.owl_drops or self.warp_songs or self.spawn_positions self.disable_trade_revert = (self.shuffle_interior_entrances != 'off') or self.shuffle_overworld_entrances self.shuffle_special_interior_entrances = self.shuffle_interior_entrances == 'all' # Convert the double option used by shopsanity into a single option if self.shopsanity == 'random_number': self.shopsanity = 'random' elif self.shopsanity == 'fixed_number': self.shopsanity = str(self.shop_slots) # fixing some options self.starting_tod = self.starting_tod.replace('_', '-') # Fixes starting time spelling: "witching_hour" -> "witching-hour" self.shuffle_scrubs = self.shuffle_scrubs.replace('_prices', '') # Get hint distribution self.hint_dist_user = read_json(data_path('Hints', f'{self.hint_dist}.json')) self.added_hint_types = {} self.item_added_hint_types = {} self.hint_exclusions = set() if self.skip_child_zelda: self.hint_exclusions.add('Song from Impa') self.hint_type_overrides = {} self.item_hint_type_overrides = {} # unused hint stuff self.named_item_pool = {} self.hint_text_overrides = {} for dist in hint_dist_keys: self.added_hint_types[dist] = [] for loc in self.hint_dist_user['add_locations']: if 'types' in loc: if dist in loc['types']: self.added_hint_types[dist].append(loc['location']) self.item_added_hint_types[dist] = [] for i in self.hint_dist_user['add_items']: if dist in i['types']: self.item_added_hint_types[dist].append(i['item']) self.hint_type_overrides[dist] = [] for loc in self.hint_dist_user['remove_locations']: if dist in loc['types']: self.hint_type_overrides[dist].append(loc['location']) self.item_hint_type_overrides[dist] = [] for i in self.hint_dist_user['remove_items']: if dist in i['types']: self.item_hint_type_overrides[dist].append(i['item']) self.always_hints = [hint.name for hint in getRequiredHints(self)] # Determine items which are not considered advancement based on settings. They will never be excluded. self.nonadvancement_items = {'Double Defense', 'Ice Arrows'} if (self.damage_multiplier != 'ohko' and self.damage_multiplier != 'quadruple' and self.shuffle_scrubs == 'off' and not self.shuffle_grotto_entrances): # nayru's love may be required to prevent forced damage self.nonadvancement_items.add('Nayrus Love') if getattr(self, 'logic_grottos_without_agony', False) and self.hints != 'agony': # Stone of Agony skippable if not used for hints or grottos self.nonadvancement_items.add('Stone of Agony') if (not self.shuffle_special_interior_entrances and not self.shuffle_overworld_entrances and not self.warp_songs and not self.spawn_positions): # Serenade and Prelude are never required unless one of those settings is enabled self.nonadvancement_items.add('Serenade of Water') self.nonadvancement_items.add('Prelude of Light') if self.logic_rules == 'glitchless': # Both two-handed swords can be required in glitch logic, so only consider them nonprogression in glitchless self.nonadvancement_items.add('Biggoron Sword') self.nonadvancement_items.add('Giants Knife') def load_regions_from_json(self, file_path): region_json = read_json(file_path) for region in region_json: new_region = OOTRegion(region['region_name'], RegionType.Generic, None, self.player) new_region.world = self.world if 'scene' in region: new_region.scene = region['scene'] if 'hint' in region: new_region.hint_text = region['hint'] if 'dungeon' in region: new_region.dungeon = region['dungeon'] if 'time_passes' in region: new_region.time_passes = region['time_passes'] new_region.provides_time = TimeOfDay.ALL if new_region.name == 'Ganons Castle Grounds': new_region.provides_time = TimeOfDay.DAMPE if 'locations' in region: for location, rule in region['locations'].items(): new_location = LocationFactory(location, self.player) if new_location.type in ['HintStone', 'Hint']: continue new_location.parent_region = new_region new_location.rule_string = rule if self.world.logic_rules != 'none': self.parser.parse_spot_rule(new_location) if new_location.never: # We still need to fill the location even if ALR is off. logger.debug('Unreachable location: %s', new_location.name) new_location.player = self.player new_region.locations.append(new_location) if 'events' in region: for event, rule in region['events'].items(): # Allow duplicate placement of events lname = '%s from %s' % (event, new_region.name) new_location = OOTLocation(self.player, lname, type='Event', parent=new_region) new_location.rule_string = rule if self.world.logic_rules != 'none': self.parser.parse_spot_rule(new_location) if new_location.never: logger.debug('Dropping unreachable event: %s', new_location.name) else: new_location.player = self.player new_region.locations.append(new_location) self.make_event_item(event, new_location) new_location.show_in_spoiler = False if 'exits' in region: for exit, rule in region['exits'].items(): new_exit = OOTEntrance(self.player, '%s => %s' % (new_region.name, exit), new_region) new_exit.vanilla_connected_region = exit new_exit.rule_string = rule if self.world.logic_rules != 'none': self.parser.parse_spot_rule(new_exit) if new_exit.never: logger.debug('Dropping unreachable exit: %s', new_exit.name) else: new_region.exits.append(new_exit) self.world.regions.append(new_region) self.regions.append(new_region) self.world._recache() def set_scrub_prices(self): # Get Deku Scrub Locations scrub_locations = [location for location in self.get_locations() if 'Deku Scrub' in location.name] scrub_dictionary = {} self.scrub_prices = {} for location in scrub_locations: if location.default not in scrub_dictionary: scrub_dictionary[location.default] = [] scrub_dictionary[location.default].append(location) # Loop through each type of scrub. for (scrub_item, default_price, text_id, text_replacement) in business_scrubs: price = default_price if self.shuffle_scrubs == 'low': price = 10 elif self.shuffle_scrubs == 'random': # this is a random value between 0-99 # average value is ~33 rupees price = int(self.world.random.betavariate(1, 2) * 99) # Set price in the dictionary as well as the location. self.scrub_prices[scrub_item] = price if scrub_item in scrub_dictionary: for location in scrub_dictionary[scrub_item]: location.price = price if location.item is not None: location.item.price = price def random_shop_prices(self): shop_item_indexes = ['7', '5', '8', '6'] self.shop_prices = {} for region in self.regions: if self.shopsanity == 'random': shop_item_count = self.world.random.randint(0, 4) else: shop_item_count = int(self.shopsanity) for location in region.locations: if location.type == 'Shop': if location.name[-1:] in shop_item_indexes[:shop_item_count]: self.shop_prices[location.name] = int(self.world.random.betavariate(1.5, 2) * 60) * 5 def fill_bosses(self, bossCount=9): rewardlist = ( '<NAME>', '<NAME>', '<NAME>', 'Forest Medallion', 'Fire Medallion', 'Water Medallion', 'Spirit Medallion', 'Shadow Medallion', 'Light Medallion' ) boss_location_names = ( '<NAME>', '<NAME>', 'Barinade', '<NAME>', 'Volvagia', 'Morpha', 'Bongo Bongo', 'Twinrova', 'Links Pocket' ) boss_rewards = [self.create_item(reward) for reward in rewardlist] boss_locations = [self.world.get_location(loc, self.player) for loc in boss_location_names] placed_prizes = [loc.item.name for loc in boss_locations if loc.item is not None] prizepool = [item for item in boss_rewards if item.name not in placed_prizes] prize_locs = [loc for loc in boss_locations if loc.item is None] while bossCount: bossCount -= 1 self.world.random.shuffle(prizepool) self.world.random.shuffle(prize_locs) item = prizepool.pop() loc = prize_locs.pop() self.world.push_item(loc, item, collect=False) loc.locked = True loc.event = True def create_item(self, name: str): if name in item_table: return OOTItem(name, self.player, item_table[name], False, (name in self.nonadvancement_items)) return OOTItem(name, self.player, ('Event', True, None, None), True, False) def make_event_item(self, name, location, item=None): if item is None: item = self.create_item(name) self.world.push_item(location, item, collect=False) location.locked = True location.event = True if name not in item_table: location.internal = True return item def create_regions(self): # create and link regions if self.logic_rules == 'glitchless': world_type = 'World' else: world_type = 'Glitched World' overworld_data_path = data_path(world_type, 'Overworld.json') menu = OOTRegion('Menu', None, None, self.player) start = OOTEntrance(self.player, 'New Game', menu) menu.exits.append(start) self.world.regions.append(menu) self.load_regions_from_json(overworld_data_path) start.connect(self.world.get_region('Root', self.player)) create_dungeons(self) self.parser.create_delayed_rules() if self.shopsanity != 'off': self.random_shop_prices() self.set_scrub_prices() # logger.info('Setting Entrances.') # set_entrances(self) # Enforce vanilla for now for region in self.regions: for exit in region.exits: exit.connect(self.world.get_region(exit.vanilla_connected_region, self.player)) if self.entrance_shuffle: shuffle_random_entrances(self) def create_items(self): # Generate itempool generate_itempool(self) add_dungeon_items(self) junk_pool = get_junk_pool(self) removed_items = [] # Determine starting items for item in self.world.precollected_items[self.player]: if item.name in self.remove_from_start_inventory: self.remove_from_start_inventory.remove(item.name) removed_items.append(item.name) else: self.starting_items[item.name] += 1 if item.type == 'Song': self.starting_songs = True # Call the junk fill and get a replacement if item in self.itempool: self.itempool.remove(item) self.itempool.append(self.create_item(*get_junk_item(pool=junk_pool))) if self.start_with_consumables: self.starting_items['Deku Sticks'] = 30 self.starting_items['Deku Nuts'] = 40 if self.start_with_rupees: self.starting_items['Rupees'] = 999 self.world.itempool += self.itempool self.remove_from_start_inventory.extend(removed_items) def set_rules(self): set_rules(self) set_entrances_based_rules(self) def generate_basic(self): # mostly killing locations that shouldn't exist by settings # Fill boss prizes. needs to happen before killing unreachable locations self.fill_bosses() # Uniquely rename drop locations for each region and erase them from the spoiler set_drop_location_names(self) # Gather items for ice trap appearances self.fake_items = [] if self.ice_trap_appearance in ['major_only', 'anything']: self.fake_items.extend(item for item in self.itempool if item.index and self.is_major_item(item)) if self.ice_trap_appearance in ['junk_only', 'anything']: self.fake_items.extend(item for item in self.itempool if item.index and not self.is_major_item(item) and item.name != 'Ice Trap') # Kill unreachable events that can't be gotten even with all items # Make sure to only kill actual internal events, not in-game "events" all_state = self.world.get_all_state(False) all_locations = self.get_locations() reachable = self.world.get_reachable_locations(all_state, self.player) unreachable = [loc for loc in all_locations if loc.internal and loc.event and loc.locked and loc not in reachable] for loc in unreachable: loc.parent_region.locations.remove(loc) # Exception: Sell Big Poe is an event which is only reachable if Bottle with Big Poe is in the item pool. # We allow it to be removed only if Bottle with Big Poe is not in the itempool. bigpoe = self.world.get_location('Sell Big Poe from Market Guard House', self.player) if not all_state.has('Bottle with Big Poe', self.player) and bigpoe not in reachable: bigpoe.parent_region.locations.remove(bigpoe) self.world.clear_location_cache() # If fast scarecrow then we need to kill the Pierre location as it will be unreachable if self.free_scarecrow: loc = self.world.get_location("Pierre", self.player) loc.parent_region.locations.remove(loc) # If open zora's domain then we need to kill Deliver Rutos Letter if self.zora_fountain == 'open': loc = self.world.get_location("Deliver Rutos Letter", self.player) loc.parent_region.locations.remove(loc) def pre_fill(self): # relevant for both dungeon item fill and song fill dungeon_song_locations = [ "Deku Tree Queen Gohma Heart", "Dodongos Cavern King Dodongo Heart", "Jabu Jabus Belly Barinade Heart", "Forest Temple Phantom Ganon Heart", "Fire Temple Volvagia Heart", "Water Temple Morpha Heart", "Shadow Temple Bongo Bongo Heart", "Spirit Temple Twinrova Heart", "Song from Impa", "Sheik in Ice Cavern", "Bottom of the Well Lens of Truth Chest", "Bottom of the Well MQ Lens of Truth Chest", # only one exists "Gerudo Training Grounds Maze Path Final Chest", "Gerudo Training Grounds MQ Ice Arrows Chest", # only one exists ] # Place/set rules for dungeon items itempools = { 'dungeon': [], 'overworld': [], 'any_dungeon': [], } any_dungeon_locations = [] for dungeon in self.dungeons: itempools['dungeon'] = [] # Put the dungeon items into their appropriate pools. # Build in reverse order since we need to fill boss key first and pop() returns the last element if self.shuffle_mapcompass in itempools: itempools[self.shuffle_mapcompass].extend(dungeon.dungeon_items) if self.shuffle_smallkeys in itempools: itempools[self.shuffle_smallkeys].extend(dungeon.small_keys) shufflebk = self.shuffle_bosskeys if dungeon.name != 'Ganons Castle' else self.shuffle_ganon_bosskey if shufflebk in itempools: itempools[shufflebk].extend(dungeon.boss_key) # We can't put a dungeon item on the end of a dungeon if a song is supposed to go there. Make sure not to include it. dungeon_locations = [loc for region in dungeon.regions for loc in region.locations if loc.item is None and ( self.shuffle_song_items != 'dungeon' or loc.name not in dungeon_song_locations)] if itempools['dungeon']: # only do this if there's anything to shuffle for item in itempools['dungeon']: self.world.itempool.remove(item) self.world.random.shuffle(dungeon_locations) fill_restrictive(self.world, self.world.get_all_state(False), dungeon_locations, itempools['dungeon'], True, True) any_dungeon_locations.extend(dungeon_locations) # adds only the unfilled locations # Now fill items that can go into any dungeon. Retrieve the Gerudo Fortress keys from the pool if necessary if self.shuffle_fortresskeys == 'any_dungeon': fortresskeys = filter(lambda item: item.player == self.player and item.type == 'FortressSmallKey', self.world.itempool) itempools['any_dungeon'].extend(fortresskeys) if itempools['any_dungeon']: for item in itempools['any_dungeon']: self.world.itempool.remove(item) itempools['any_dungeon'].sort(key=lambda item: {'GanonBossKey': 4, 'BossKey': 3, 'SmallKey': 2, 'FortressSmallKey': 1}.get(item.type, 0)) self.world.random.shuffle(any_dungeon_locations) fill_restrictive(self.world, self.world.get_all_state(False), any_dungeon_locations, itempools['any_dungeon'], True, True) # If anything is overworld-only, fill into local non-dungeon locations if self.shuffle_fortresskeys == 'overworld': fortresskeys = filter(lambda item: item.player == self.player and item.type == 'FortressSmallKey', self.world.itempool) itempools['overworld'].extend(fortresskeys) if itempools['overworld']: for item in itempools['overworld']: self.world.itempool.remove(item) itempools['overworld'].sort(key=lambda item: {'GanonBossKey': 4, 'BossKey': 3, 'SmallKey': 2, 'FortressSmallKey': 1}.get(item.type, 0)) non_dungeon_locations = [loc for loc in self.get_locations() if not loc.item and loc not in any_dungeon_locations and loc.type != 'Shop' and (loc.type != 'Song' or self.shuffle_song_items != 'song')] self.world.random.shuffle(non_dungeon_locations) fill_restrictive(self.world, self.world.get_all_state(False), non_dungeon_locations, itempools['overworld'], True, True) # Place songs # 5 built-in retries because this section can fail sometimes if self.shuffle_song_items != 'any': tries = 5 if self.shuffle_song_items == 'song': song_locations = list(filter(lambda location: location.type == 'Song', self.world.get_unfilled_locations(player=self.player))) elif self.shuffle_song_items == 'dungeon': song_locations = list(filter(lambda location: location.name in dungeon_song_locations, self.world.get_unfilled_locations(player=self.player))) else: raise Exception(f"Unknown song shuffle type: {self.shuffle_song_items}") songs = list(filter(lambda item: item.player == self.player and item.type == 'Song', self.world.itempool)) for song in songs: self.world.itempool.remove(song) while tries: try: self.world.random.shuffle(songs) # shuffling songs makes it less likely to fail by placing ZL last self.world.random.shuffle(song_locations) fill_restrictive(self.world, self.world.get_all_state(False), song_locations[:], songs[:], True, True) logger.debug(f"Successfully placed songs for player {self.player} after {6 - tries} attempt(s)") tries = 0 except FillError as e: tries -= 1 if tries == 0: raise e logger.debug(f"Failed placing songs for player {self.player}. Retries left: {tries}") # undo what was done for song in songs: song.location = None song.world = None for location in song_locations: location.item = None location.locked = False location.event = False # Place shop items # fast fill will fail because there is some logic on the shop items. we'll gather them up and place the shop items if self.shopsanity != 'off': shop_items = list(filter(lambda item: item.player == self.player and item.type == 'Shop', self.world.itempool)) shop_locations = list( filter(lambda location: location.type == 'Shop' and location.name not in self.shop_prices, self.world.get_unfilled_locations(player=self.player))) shop_items.sort(key=lambda item: { 'Buy Deku Shield': 3*int(self.open_forest == 'closed'), 'Buy Goron Tunic': 2, 'Buy Zora Tunic': 2 }.get(item.name, int(item.advancement))) # place Deku Shields if needed, then tunics, then other advancement, then junk self.world.random.shuffle(shop_locations) for item in shop_items: self.world.itempool.remove(item) fill_restrictive(self.world, self.world.get_all_state(False), shop_locations, shop_items, True, True) set_shop_rules(self) # sets wallet requirements on shop items, must be done after they are filled # If skip child zelda is active and Song from Impa is unfilled, put a local giveable item into it. impa = self.world.get_location("Song from Impa", self.player) if self.skip_child_zelda: if impa.item is None: from .SaveContext import SaveContext item_to_place = self.world.random.choice(list(item for item in self.world.itempool if item.player == self.player and item.name in SaveContext.giveable_items)) impa.place_locked_item(item_to_place) self.world.itempool.remove(item_to_place) # Give items to startinventory self.world.push_precollected(impa.item) self.world.push_precollected(self.create_item("Zeldas Letter")) # Exclude locations in Ganon's Castle proportional to the number of items required to make the bridge # Check for dungeon ER later if self.logic_rules == 'glitchless': if self.bridge == 'medallions': ganon_junk_fill = self.bridge_medallions / 9 elif self.bridge == 'stones': ganon_junk_fill = self.bridge_stones / 9 elif self.bridge == 'dungeons': ganon_junk_fill = self.bridge_rewards / 9 elif self.bridge == 'vanilla': ganon_junk_fill = 2 / 9 elif self.bridge == 'tokens': ganon_junk_fill = self.bridge_tokens / 100 elif self.bridge == 'open': ganon_junk_fill = 0 else: raise Exception("Unexpected bridge setting") gc = next(filter(lambda dungeon: dungeon.name == 'Ganons Castle', self.dungeons)) locations = [loc.name for region in gc.regions for loc in region.locations if loc.item is None] junk_fill_locations = self.world.random.sample(locations, round(len(locations) * ganon_junk_fill)) exclusion_rules(self.world, self.player, junk_fill_locations) # Locations which are not sendable must be converted to events # This includes all locations for which show_in_spoiler is false, and shuffled shop items. for loc in self.get_locations(): if loc.address is not None and ( not loc.show_in_spoiler or (loc.item is not None and loc.item.type == 'Shop') or (self.skip_child_zelda and loc.name in ['HC Zeldas Letter', 'Song from Impa'])): loc.address = None def generate_output(self, output_directory: str): if self.hints != 'none': self.hint_data_available.wait() with i_o_limiter: # Make ice traps appear as other random items ice_traps = [loc.item for loc in self.get_locations() if loc.item.name == 'Ice Trap'] for trap in ice_traps: trap.looks_like_item = self.create_item(self.world.slot_seeds[self.player].choice(self.fake_items).name) outfile_name = f"AP_{self.world.seed_name}_P{self.player}_{self.world.get_player_name(self.player)}" rom = Rom(file=get_options()['oot_options']['rom_file']) if self.hints != 'none': buildWorldGossipHints(self) patch_rom(self, rom) patch_cosmetics(self, rom) rom.update_header() create_patch_file(rom, output_path(output_directory, outfile_name + '.apz5')) rom.restore() # Gathers hint data for OoT. Loops over all world locations for woth, barren, and major item locations. @classmethod def stage_generate_output(cls, world: MultiWorld, output_directory: str): def hint_type_players(hint_type: str) -> set: return {autoworld.player for autoworld in world.get_game_worlds("Ocarina of Time") if autoworld.hints != 'none' and autoworld.hint_dist_user['distribution'][hint_type]['copies'] > 0} try: item_hint_players = hint_type_players('item') barren_hint_players = hint_type_players('barren') woth_hint_players = hint_type_players('woth') items_by_region = {} for player in barren_hint_players: items_by_region[player] = {} for r in world.worlds[player].regions: items_by_region[player][r.hint_text] = {'dungeon': False, 'weight': 0, 'is_barren': True} for d in world.worlds[player].dungeons: items_by_region[player][d.hint_text] = {'dungeon': True, 'weight': 0, 'is_barren': True} del (items_by_region[player]["Link's Pocket"]) del (items_by_region[player][None]) if item_hint_players: # loop once over all locations to gather major items. Check oot locations for barren/woth if needed for loc in world.get_locations(): player = loc.item.player autoworld = world.worlds[player] if ((player in item_hint_players and (autoworld.is_major_item(loc.item) or loc.item.name in autoworld.item_added_hint_types['item'])) or (loc.player in item_hint_players and loc.name in world.worlds[loc.player].added_hint_types['item'])): autoworld.major_item_locations.append(loc) if loc.game == "Ocarina of Time" and loc.item.code and (not loc.locked or loc.item.type == 'Song'): if loc.player in barren_hint_players: hint_area = get_hint_area(loc) items_by_region[loc.player][hint_area]['weight'] += 1 if loc.item.advancement: items_by_region[loc.player][hint_area]['is_barren'] = False if loc.player in woth_hint_players and loc.item.advancement: # Skip item at location and see if game is still beatable state = CollectionState(world) state.locations_checked.add(loc) if not world.can_beat_game(state): world.worlds[loc.player].required_locations.append(loc) elif barren_hint_players or woth_hint_players: # Check only relevant oot locations for barren/woth for player in (barren_hint_players | woth_hint_players): for loc in world.worlds[player].get_locations(): if loc.item.code and (not loc.locked or loc.item.type == 'Song'): if player in barren_hint_players: hint_area = get_hint_area(loc) items_by_region[player][hint_area]['weight'] += 1 if loc.item.advancement: items_by_region[player][hint_area]['is_barren'] = False if player in woth_hint_players and loc.item.advancement: state = CollectionState(world) state.locations_checked.add(loc) if not world.can_beat_game(state): world.worlds[player].required_locations.append(loc) for player in barren_hint_players: world.worlds[player].empty_areas = {region: info for (region, info) in items_by_region[player].items() if info['is_barren']} except Exception as e: raise e finally: for autoworld in world.get_game_worlds("Ocarina of Time"): autoworld.hint_data_available.set() def modify_multidata(self, multidata: dict): for item_name in self.remove_from_start_inventory: item_id = self.item_name_to_id.get(item_name, None) try: multidata["precollected_items"][self.player].remove(item_id) except ValueError as e: logger.warning(f"Attempted to remove nonexistent item id {item_id} from OoT precollected items ({item_name})") # Helper functions def get_shuffled_entrances(self): return [] # later this will return all entrances modified by ER. patching process needs it now though def get_locations(self): for region in self.regions: for loc in region.locations: yield loc def get_location(self, location): return self.world.get_location(location, self.player) def get_region(self, region): return self.world.get_region(region, self.player) def is_major_item(self, item: OOTItem): if item.type == 'Token': return self.bridge == 'tokens' or self.lacs_condition == 'tokens' if item.name in self.nonadvancement_items: return True if item.type in ('Drop', 'Event', 'Shop', 'DungeonReward') or not item.advancement: return False if item.name.startswith('Bombchus') and not self.bombchus_in_logic: return False if item.type in ['Map', 'Compass']: return False if item.type == 'SmallKey' and self.shuffle_smallkeys in ['dungeon', 'vanilla']: return False if item.type == 'FortressSmallKey' and self.shuffle_fortresskeys == 'vanilla': return False if item.type == 'BossKey' and self.shuffle_bosskeys in ['dungeon', 'vanilla']: return False if item.type == 'GanonBossKey' and self.shuffle_ganon_bosskey in ['dungeon', 'vanilla']: return False return True <file_sep>from collections import namedtuple from itertools import chain from .Items import item_table from .LocationList import location_groups from decimal import Decimal, ROUND_HALF_UP # Generates itempools and places fixed items based on settings. alwaysitems = ([ 'Biggoron Sword', 'Boomerang', 'Lens of Truth', 'Megaton Hammer', 'Iron Boots', 'Goron Tunic', 'Zora Tunic', 'Hover Boots', 'Mirror Shield', 'Stone of Agony', 'Fire Arrows', 'Ice Arrows', 'Light Arrows', 'Dins Fire', 'Farores Wind', 'Nayrus Love', 'Rupee (1)'] + ['Progressive Hookshot'] * 2 + ['Deku Shield'] + ['Hylian Shield'] + ['Progressive Strength Upgrade'] * 3 + ['Progressive Scale'] * 2 + ['Recovery Heart'] * 6 + ['Bow'] * 3 + ['Slingshot'] * 3 + ['Bomb Bag'] * 3 + ['Bombs (5)'] * 2 + ['Bombs (10)'] + ['Bombs (20)'] + ['Arrows (5)'] + ['Arrows (10)'] * 5 + ['Progressive Wallet'] * 2 + ['Magic Meter'] * 2 + ['Double Defense'] + ['Deku Stick Capacity'] * 2 + ['Deku Nut Capacity'] * 2 + ['Piece of Heart (Treasure Chest Game)']) easy_items = ([ 'Biggoron Sword', 'Kokiri Sword', 'Boomerang', 'Lens of Truth', 'Megaton Hammer', 'Iron Boots', 'Goron Tunic', 'Zora Tunic', 'Hover Boots', 'Mirror Shield', 'Fire Arrows', 'Light Arrows', 'Dins Fire', 'Progressive Hookshot', 'Progressive Strength Upgrade', 'Progressive Scale', 'Progressive Wallet', 'Magic Meter', 'Deku Stick Capacity', 'Deku Nut Capacity', 'Bow', 'Slingshot', 'Bomb Bag', 'Double Defense'] + ['Heart Container'] * 16 + ['Piece of Heart'] * 3) normal_items = ( ['Heart Container'] * 8 + ['Piece of Heart'] * 35) item_difficulty_max = { 'plentiful': {}, 'balanced': {}, 'scarce': { 'Bombchus': 3, 'Bombchus (5)': 1, 'Bombchus (10)': 2, 'Bombchus (20)': 0, 'Magic Meter': 1, 'Double Defense': 0, 'Deku Stick Capacity': 1, 'Deku Nut Capacity': 1, 'Bow': 2, 'Slingshot': 2, 'Bomb Bag': 2, 'Heart Container': 0, }, 'minimal': { 'Bombchus': 1, 'Bombchus (5)': 1, 'Bombchus (10)': 0, 'Bombchus (20)': 0, 'Nayrus Love': 0, 'Magic Meter': 1, 'Double Defense': 0, 'Deku Stick Capacity': 0, 'Deku Nut Capacity': 0, 'Bow': 1, 'Slingshot': 1, 'Bomb Bag': 1, 'Heart Container': 0, 'Piece of Heart': 0, }, } DT_vanilla = ( ['Recovery Heart'] * 2) DT_MQ = ( ['Deku Shield'] * 2 + ['Rupees (50)']) DC_vanilla = ( ['Rupees (20)']) DC_MQ = ( ['Hylian Shield'] + ['Rupees (5)']) JB_MQ = ( ['Deku Nuts (5)'] * 4 + ['Recovery Heart'] + ['Deku Shield'] + ['Deku Stick (1)']) FoT_vanilla = ( ['Recovery Heart'] + ['Arrows (10)'] + ['Arrows (30)']) FoT_MQ = ( ['Arrows (5)']) FiT_vanilla = ( ['Rupees (200)']) FiT_MQ = ( ['Bombs (20)'] + ['Hylian Shield']) SpT_vanilla = ( ['Deku Shield'] * 2 + ['Recovery Heart'] + ['Bombs (20)']) SpT_MQ = ( ['Rupees (50)'] * 2 + ['Arrows (30)']) ShT_vanilla = ( ['Arrows (30)']) ShT_MQ = ( ['Arrows (5)'] * 2 + ['Rupees (20)']) BW_vanilla = ( ['Recovery Heart'] + ['Bombs (10)'] + ['Rupees (200)'] + ['Deku Nuts (5)'] + ['Deku Nuts (10)'] + ['Deku Shield'] + ['Hylian Shield']) GTG_vanilla = ( ['Arrows (30)'] * 3 + ['Rupees (200)']) GTG_MQ = ( ['Rupee (Treasure Chest Game)'] * 2 + ['Arrows (10)'] + ['Rupee (1)'] + ['Rupees (50)']) GC_vanilla = ( ['Rupees (5)'] * 3 + ['Arrows (30)']) GC_MQ = ( ['Arrows (10)'] * 2 + ['Bombs (5)'] + ['Rupees (20)'] + ['Recovery Heart']) normal_bottles = [ 'Bottle', 'Bottle with Milk', 'Bottle with Red Potion', 'Bottle with Green Potion', 'Bottle with Blue Potion', 'Bottle with Fairy', 'Bottle with Fish', 'Bottle with Bugs', 'Bottle with Poe', 'Bottle with Big Poe', 'Bottle with Blue Fire'] bottle_count = 4 dungeon_rewards = [ '<NAME>', 'Goron Ruby', 'Zora Sapphire', 'Forest Medallion', 'Fire Medallion', 'Water Medallion', 'Shadow Medallion', 'Spirit Medallion', 'Light Medallion' ] normal_rupees = ( ['Rupees (5)'] * 13 + ['Rupees (20)'] * 5 + ['Rupees (50)'] * 7 + ['Rupees (200)'] * 3) shopsanity_rupees = ( ['Rupees (5)'] * 2 + ['Rupees (20)'] * 10 + ['Rupees (50)'] * 10 + ['Rupees (200)'] * 5 + ['Progressive Wallet']) vanilla_shop_items = { 'KF Shop Item 1': 'Buy Deku Shield', 'KF Shop Item 2': 'Buy Deku Nut (5)', 'KF Shop Item 3': 'Buy Deku Nut (10)', 'KF Shop Item 4': 'Buy Deku Stick (1)', 'KF Shop Item 5': 'Buy Deku Seeds (30)', 'KF Shop Item 6': 'Buy Arrows (10)', 'KF Shop Item 7': 'Buy Arrows (30)', 'KF Shop Item 8': 'Buy Heart', 'Kak Potion Shop Item 1': 'Buy Deku Nut (5)', 'Kak Potion Shop Item 2': 'Buy Fish', 'Kak Potion Shop Item 3': 'Buy Red Potion [30]', 'Kak Potion Shop Item 4': 'Buy Green Potion', 'Kak Potion Shop Item 5': 'Buy Blue Fire', 'Kak Potion Shop Item 6': 'Buy Bottle Bug', 'Kak Potion Shop Item 7': 'Buy Poe', 'Kak Potion Shop Item 8': 'Buy Fairy\'s Spirit', 'Market Bombchu Shop Item 1': 'Buy Bombchu (5)', 'Market Bombchu Shop Item 2': 'Buy Bombchu (10)', 'Market Bombchu Shop Item 3': 'Buy Bombchu (10)', 'Market Bombchu Shop Item 4': 'Buy Bombchu (10)', 'Market Bombchu Shop Item 5': 'Buy Bombchu (20)', 'Market Bombchu Shop Item 6': 'Buy Bombchu (20)', 'Market Bombchu Shop Item 7': 'Buy Bombchu (20)', 'Market Bombchu Shop Item 8': 'Buy Bombchu (20)', 'Market Potion Shop Item 1': 'Buy Green Potion', 'Market Potion Shop Item 2': 'Buy Blue Fire', 'Market Potion Shop Item 3': 'Buy Red Potion [30]', 'Market Potion Shop Item 4': 'Buy Fairy\'s Spirit', 'Market Potion Shop Item 5': 'Buy Deku Nut (5)', 'Market Potion Shop Item 6': 'Buy Bottle Bug', 'Market Potion Shop Item 7': 'Buy Poe', 'Market Potion Shop Item 8': 'Buy Fish', 'Market Bazaar Item 1': 'Buy Hylian Shield', 'Market Bazaar Item 2': 'Buy Bombs (5) [35]', 'Market Bazaar Item 3': 'Buy Deku Nut (5)', 'Market Bazaar Item 4': 'Buy Heart', 'Market Bazaar Item 5': 'Buy Arrows (10)', 'Market Bazaar Item 6': 'Buy Arrows (50)', 'Market Bazaar Item 7': 'Buy Deku Stick (1)', 'Market Bazaar Item 8': 'Buy Arrows (30)', 'Kak Bazaar Item 1': 'Buy Hylian Shield', 'Kak Bazaar Item 2': 'Buy Bombs (5) [35]', 'Kak Bazaar Item 3': 'Buy Deku Nut (5)', 'Kak Bazaar Item 4': 'Buy Heart', 'Kak Bazaar Item 5': 'Buy Arrows (10)', 'Kak Bazaar Item 6': 'Buy Arrows (50)', 'Kak Bazaar Item 7': 'Buy Deku Stick (1)', 'Kak Bazaar Item 8': 'Buy Arrows (30)', 'ZD Shop Item 1': 'Buy Zora Tunic', 'ZD Shop Item 2': 'Buy Arrows (10)', 'ZD Shop Item 3': 'Buy Heart', 'ZD Shop Item 4': 'Buy Arrows (30)', 'ZD Shop Item 5': 'Buy Deku Nut (5)', 'ZD Shop Item 6': 'Buy Arrows (50)', 'ZD Shop Item 7': 'Buy Fish', 'ZD Shop Item 8': 'Buy Red Potion [50]', 'GC Shop Item 1': 'Buy Bombs (5) [25]', 'GC Shop Item 2': 'Buy Bombs (10)', 'GC Shop Item 3': 'Buy Bombs (20)', 'GC Shop Item 4': 'Buy Bombs (30)', 'GC Shop Item 5': 'Buy Goron Tunic', 'GC Shop Item 6': 'Buy Heart', 'GC Shop Item 7': 'Buy Red Potion [40]', 'GC Shop Item 8': 'Buy Heart', } min_shop_items = ( ['Buy Deku Shield'] + ['Buy Hylian Shield'] + ['Buy Goron Tunic'] + ['Buy Zora Tunic'] + ['Buy Deku Nut (5)'] * 2 + ['Buy Deku Nut (10)'] + ['Buy Deku Stick (1)'] * 2 + ['Buy Deku Seeds (30)'] + ['Buy Arrows (10)'] * 2 + ['Buy Arrows (30)'] + ['Buy Arrows (50)'] + ['Buy Bombchu (5)'] + ['Buy Bombchu (10)'] * 2 + ['Buy Bombchu (20)'] + ['Buy Bombs (5) [25]'] + ['Buy Bombs (5) [35]'] + ['Buy Bombs (10)'] + ['Buy Bombs (20)'] + ['Buy Green Potion'] + ['Buy Red Potion [30]'] + ['Buy Blue Fire'] + ['Buy Fairy\'s Spirit'] + ['Buy Bottle Bug'] + ['Buy Fish']) vanilla_deku_scrubs = { 'ZR Deku Scrub Grotto Rear': 'Buy Red Potion [30]', 'ZR Deku Scrub Grotto Front': 'Buy Green Potion', 'SFM Deku Scrub Grotto Rear': 'Buy Red Potion [30]', 'SFM Deku Scrub Grotto Front': 'Buy Green Potion', 'LH Deku Scrub Grotto Left': 'Buy Deku Nut (5)', 'LH Deku Scrub Grotto Right': 'Buy Bombs (5) [35]', 'LH Deku Scrub Grotto Center': 'Buy Arrows (30)', 'GV Deku Scrub Grotto Rear': 'Buy Red Potion [30]', 'GV Deku Scrub Grotto Front': 'Buy Green Potion', 'LW Deku Scrub Near Deku Theater Right': 'Buy Deku Nut (5)', 'LW Deku Scrub Near Deku Theater Left': 'Buy Deku Stick (1)', 'LW Deku Scrub Grotto Rear': 'Buy Arrows (30)', 'Colossus Deku Scrub Grotto Rear': 'Buy Red Potion [30]', 'Colossus Deku Scrub Grotto Front': 'Buy Green Potion', 'DMC Deku Scrub': 'Buy Bombs (5) [35]', 'DMC Deku Scrub Grotto Left': 'Buy Deku Nut (5)', 'DMC Deku Scrub Grotto Right': 'Buy Bombs (5) [35]', 'DMC Deku Scrub Grotto Center': 'Buy Arrows (30)', 'GC Deku Scrub Grotto Left': 'Buy Deku Nut (5)', 'GC Deku Scrub Grotto Right': 'Buy Bombs (5) [35]', 'GC Deku Scrub Grotto Center': 'Buy Arrows (30)', 'LLR Deku Scrub Grotto Left': 'Buy Deku Nut (5)', 'LLR Deku Scrub Grotto Right': 'Buy Bombs (5) [35]', 'LLR Deku Scrub Grotto Center': 'Buy Arrows (30)', } deku_scrubs_items = ( ['Deku Nuts (5)'] * 5 + ['Deku Stick (1)'] + ['Bombs (5)'] * 5 + ['Recovery Heart'] * 4 + ['Rupees (5)'] * 4) # ['Green Potion'] songlist = [ '<NAME>', 'Eponas Song', 'Suns Song', 'Sarias Song', 'Song of Time', 'Song of Storms', 'Minuet of Forest', 'Prelude of Light', 'Bolero of Fire', 'Serenade of Water', 'Nocturne of Shadow', 'Requiem of Spirit'] skulltula_locations = ([ 'KF GS Know It All House', 'KF GS Bean Patch', 'KF GS House of Twins', 'LW GS Bean Patch Near Bridge', 'LW GS Bean Patch Near Theater', 'LW GS Above Theater', 'SFM GS', 'HF GS Near Kak Grotto', 'HF GS Cow Grotto', 'Market GS Guard House', 'HC GS Tree', 'HC GS Storms Grotto', 'OGC GS', 'LLR GS Tree', 'LLR GS Rain Shed', 'LLR GS House Window', 'LLR GS Back Wall', 'Kak GS House Under Construction', 'Kak GS Skulltula House', 'Kak GS Guards House', 'Kak GS Tree', 'Kak GS Watchtower', 'Kak GS Above Impas House', 'Graveyard GS Wall', 'Graveyard GS Bean Patch', 'DMT GS Bean Patch', 'DMT GS Near Kak', 'DMT GS Falling Rocks Path', 'DMT GS Above Dodongos Cavern', 'GC GS Boulder Maze', 'GC GS Center Platform', 'DMC GS Crate', 'DMC GS Bean Patch', 'ZR GS Ladder', 'ZR GS Tree', 'ZR GS Near Raised Grottos', 'ZR GS Above Bridge', 'ZD GS Frozen Waterfall', 'ZF GS Tree', 'ZF GS Above the Log', 'ZF GS Hidden Cave', 'LH GS Bean Patch', 'LH GS Lab Wall', 'LH GS Small Island', 'LH GS Tree', 'LH GS Lab Crate', 'GV GS Small Bridge', 'GV GS Bean Patch', 'GV GS Behind Tent', 'GV GS Pillar', 'GF GS Archery Range', 'GF GS Top Floor', 'Wasteland GS', 'Colossus GS Bean Patch', 'Colossus GS Tree', 'Colossus GS Hill']) tradeitems = ( 'Pocket Egg', 'Pocket Cucco', 'Cojiro', 'Odd Mushroom', 'Poachers Saw', 'Broken Sword', 'Prescription', 'Eyeball Frog', 'Eyedrops', 'Claim Check') tradeitemoptions = ( 'pocket_egg', 'pocket_cucco', 'cojiro', 'odd_mushroom', 'poachers_saw', 'broken_sword', 'prescription', 'eyeball_frog', 'eyedrops', 'claim_check') fixedlocations = { 'Ganon': 'Triforce', 'Pierre': '<NAME>', 'Deliver Rutos Letter': 'Deliver Letter', 'Master Sword Pedestal': 'Time Travel', 'Market Bombchu Bowling Bombchus': 'Bombchu Drop', } droplocations = { 'Deku Baba Sticks': 'Deku Stick Drop', 'Deku Baba Nuts': 'Deku Nut Drop', 'Stick Pot': 'Deku Stick Drop', 'Nut Pot': 'Deku Nut Drop', 'Nut Crate': 'Deku Nut Drop', 'Blue Fire': 'Blue Fire', 'Lone Fish': 'Fish', 'Fish Group': 'Fish', 'Bug Rock': 'Bugs', 'Bug Shrub': 'Bugs', 'Wandering Bugs': 'Bugs', 'Fairy Pot': 'Fairy', 'Free Fairies': 'Fairy', 'Wall Fairy': 'Fairy', 'Butterfly Fairy': 'Fairy', 'Gossip Stone Fairy': 'Fairy', 'Bean Plant Fairy': 'Fairy', 'Fairy Pond': 'Fairy', 'Big Poe Kill': 'Big Poe', } vanillaBK = { 'Fire Temple Boss Key Chest': 'Boss Key (Fire Temple)', 'Shadow Temple Boss Key Chest': 'Boss Key (Shadow Temple)', 'Spirit Temple Boss Key Chest': 'Boss Key (Spirit Temple)', 'Water Temple Boss Key Chest': 'Boss Key (Water Temple)', 'Forest Temple Boss Key Chest': 'Boss Key (Forest Temple)', 'Fire Temple MQ Boss Key Chest': 'Boss Key (Fire Temple)', 'Shadow Temple MQ Boss Key Chest': 'Boss Key (Shadow Temple)', 'Spirit Temple MQ Boss Key Chest': 'Boss Key (Spirit Temple)', 'Water Temple MQ Boss Key Chest': 'Boss Key (Water Temple)', 'Forest Temple MQ Boss Key Chest': 'Boss Key (Forest Temple)', } vanillaMC = { 'Bottom of the Well Compass Chest': 'Compass (Bottom of the Well)', 'Deku Tree Compass Chest': 'Compass (Deku Tree)', 'Dodongos Cavern Compass Chest': 'Compass (Dodongos Cavern)', 'Fire Temple Compass Chest': 'Compass (Fire Temple)', 'Forest Temple Blue Poe Chest': 'Compass (Forest Temple)', 'Ice Cavern Compass Chest': 'Compass (Ice Cavern)', 'Jabu Jabus Belly Compass Chest': 'Compass (Jabu Jabus Belly)', 'Shadow Temple Compass Chest': 'Compass (Shadow Temple)', 'Spirit Temple Compass Chest': 'Compass (Spirit Temple)', 'Water Temple Compass Chest': 'Compass (Water Temple)', 'Bottom of the Well Map Chest': 'Map (Bottom of the Well)', 'Deku Tree Map Chest': 'Map (Deku Tree)', 'Dodongos Cavern Map Chest': 'Map (Dodongos Cavern)', 'Fire Temple Map Chest': 'Map (Fire Temple)', 'Forest Temple Map Chest': 'Map (Forest Temple)', 'Ice Cavern Map Chest': 'Map (Ice Cavern)', 'Jabu Jabus Belly Map Chest': 'Map (Jabu Jabus Belly)', 'Shadow Temple Map Chest': 'Map (Shadow Temple)', 'Spirit Temple Map Chest': 'Map (Spirit Temple)', 'Water Temple Map Chest': 'Map (Water Temple)', 'Bottom of the Well MQ Compass Chest': 'Compass (Bottom of the Well)', 'Deku Tree MQ Compass Chest': 'Compass (Deku Tree)', 'Dodongos Cavern MQ Compass Chest': 'Compass (Dodongos Cavern)', 'Fire Temple MQ Compass Chest': 'Compass (Fire Temple)', 'Forest Temple MQ Compass Chest': 'Compass (Forest Temple)', 'Ice Cavern MQ Compass Chest': 'Compass (Ice Cavern)', 'Jabu Jabus Belly MQ Compass Chest': 'Compass (Jabu Jabus Belly)', 'Shadow Temple MQ Compass Chest': 'Compass (Shadow Temple)', 'Spirit Temple MQ Compass Chest': 'Compass (Spirit Temple)', 'Water Temple MQ Compass Chest': 'Compass (Water Temple)', 'Bottom of the Well MQ Map Chest': 'Map (Bottom of the Well)', 'Deku Tree MQ Map Chest': 'Map (Deku Tree)', 'Dodongos Cavern MQ Map Chest': 'Map (Dodongos Cavern)', 'Fire Temple MQ Map Chest': 'Map (Fire Temple)', 'Forest Temple MQ Map Chest': 'Map (Forest Temple)', 'Ice Cavern MQ Map Chest': 'Map (Ice Cavern)', 'Jabu Jabus Belly MQ Map Chest': 'Map (Jabu Jabus Belly)', 'Shadow Temple MQ Map Chest': 'Map (Shadow Temple)', 'Spirit Temple MQ Map Chest': 'Map (Spirit Temple)', 'Water Temple MQ Map Chest': 'Map (Water Temple)', } vanillaSK = { 'Bottom of the Well Front Left Fake Wall Chest': 'Small Key (Bottom of the Well)', 'Bottom of the Well Right Bottom Fake Wall Chest': 'Small Key (Bottom of the Well)', 'Bottom of the Well Freestanding Key': 'Small Key (Bottom of the Well)', 'Fire Temple Big Lava Room Blocked Door Chest': 'Small Key (Fire Temple)', 'Fire Temple Big Lava Room Lower Open Door Chest': 'Small Key (Fire Temple)', 'Fire Temple Boulder Maze Shortcut Chest': 'Small Key (Fire Temple)', 'Fire Temple Boulder Maze Lower Chest': 'Small Key (Fire Temple)', 'Fire Temple Boulder Maze Side Room Chest': 'Small Key (Fire Temple)', 'Fire Temple Boulder Maze Upper Chest': 'Small Key (Fire Temple)', 'Fire Temple Near Boss Chest': 'Small Key (Fire Temple)', 'Fire Temple Highest Goron Chest': 'Small Key (Fire Temple)', 'Forest Temple First Stalfos Chest': 'Small Key (Forest Temple)', 'Forest Temple First Room Chest': 'Small Key (Forest Temple)', 'Forest Temple Floormaster Chest': 'Small Key (Forest Temple)', 'Forest Temple Red Poe Chest': 'Small Key (Forest Temple)', 'Forest Temple Well Chest': 'Small Key (Forest Temple)', 'Ganons Castle Light Trial Invisible Enemies Chest': 'Small Key (Ganons Castle)', 'Ganons Castle Light Trial Lullaby Chest': 'Small Key (Ganons Castle)', 'Gerudo Training Grounds Beamos Chest': 'Small Key (Gerudo Training Grounds)', 'Gerudo Training Grounds Eye Statue Chest': 'Small Key (Gerudo Training Grounds)', 'Gerudo Training Grounds Hammer Room Switch Chest': 'Small Key (Gerudo Training Grounds)', 'Gerudo Training Grounds Heavy Block Third Chest': 'Small Key (Gerudo Training Grounds)', 'Gerudo Training Grounds Hidden Ceiling Chest': 'Small Key (Gerudo Training Grounds)', 'Gerudo Training Grounds Near Scarecrow Chest': 'Small Key (Gerudo Training Grounds)', 'Gerudo Training Grounds Stalfos Chest': 'Small Key (Gerudo Training Grounds)', 'Gerudo Training Grounds Underwater Silver Rupee Chest': 'Small Key (Gerudo Training Grounds)', 'Gerudo Training Grounds Freestanding Key': 'Small Key (Gerudo Training Grounds)', 'Shadow Temple After Wind Hidden Chest': 'Small Key (Shadow Temple)', 'Shadow Temple Early Silver Rupee Chest': 'Small Key (Shadow Temple)', 'Shadow Temple Falling Spikes Switch Chest': 'Small Key (Shadow Temple)', 'Shadow Temple Invisible Floormaster Chest': 'Small Key (Shadow Temple)', 'Shadow Temple Freestanding Key': 'Small Key (Shadow Temple)', 'Spirit Temple Child Early Torches Chest': 'Small Key (Spirit Temple)', 'Spirit Temple Early Adult Right Chest': 'Small Key (Spirit Temple)', 'Spirit Temple Near Four Armos Chest': 'Small Key (Spirit Temple)', 'Spirit Temple Statue Room Hand Chest': 'Small Key (Spirit Temple)', 'Spirit Temple Sun Block Room Chest': 'Small Key (Spirit Temple)', 'Water Temple Central Bow Target Chest': 'Small Key (Water Temple)', 'Water Temple Central Pillar Chest': 'Small Key (Water Temple)', 'Water Temple Cracked Wall Chest': 'Small Key (Water Temple)', 'Water Temple Dragon Chest': 'Small Key (Water Temple)', 'Water Temple River Chest': 'Small Key (Water Temple)', 'Water Temple Torches Chest': 'Small Key (Water Temple)', 'Bottom of the Well MQ Dead Hand Freestanding Key': 'Small Key (Bottom of the Well)', 'Bottom of the Well MQ East Inner Room Freestanding Key': 'Small Key (Bottom of the Well)', 'Fire Temple MQ Big Lava Room Blocked Door Chest': 'Small Key (Fire Temple)', 'Fire Temple MQ Near Boss Chest': 'Small Key (Fire Temple)', 'Fire Temple MQ Lizalfos Maze Side Room Chest': 'Small Key (Fire Temple)', 'Fire Temple MQ Chest On Fire': 'Small Key (Fire Temple)', 'Fire Temple MQ Freestanding Key': 'Small Key (Fire Temple)', 'Forest Temple MQ Wolfos Chest': 'Small Key (Forest Temple)', 'Forest Temple MQ First Room Chest': 'Small Key (Forest Temple)', 'Forest Temple MQ Raised Island Courtyard Lower Chest': 'Small Key (Forest Temple)', 'Forest Temple MQ Raised Island Courtyard Upper Chest': 'Small Key (Forest Temple)', 'Forest Temple MQ Redead Chest': 'Small Key (Forest Temple)', 'Forest Temple MQ Well Chest': 'Small Key (Forest Temple)', 'Ganons Castle MQ Shadow Trial Eye Switch Chest': 'Small Key (Ganons Castle)', 'Ganons Castle MQ Spirit Trial Sun Back Left Chest': 'Small Key (Ganons Castle)', 'Ganons Castle MQ Forest Trial Freestanding Key': 'Small Key (Ganons Castle)', 'Gerudo Training Grounds MQ Dinolfos Chest': 'Small Key (Gerudo Training Grounds)', 'Gerudo Training Grounds MQ Flame Circle Chest': 'Small Key (Gerudo Training Grounds)', 'Gerudo Training Grounds MQ Underwater Silver Rupee Chest': 'Small Key (Gerudo Training Grounds)', 'Shadow Temple MQ Falling Spikes Switch Chest': 'Small Key (Shadow Temple)', 'Shadow Temple MQ Invisible Blades Invisible Chest': 'Small Key (Shadow Temple)', 'Shadow Temple MQ Early Gibdos Chest': 'Small Key (Shadow Temple)', 'Shadow Temple MQ Near Ship Invisible Chest': 'Small Key (Shadow Temple)', 'Shadow Temple MQ Wind Hint Chest': 'Small Key (Shadow Temple)', 'Shadow Temple MQ Freestanding Key': 'Small Key (Shadow Temple)', 'Spirit Temple MQ Child Hammer Switch Chest': 'Small Key (Spirit Temple)', 'Spirit Temple MQ Child Climb South Chest': 'Small Key (Spirit Temple)', 'Spirit Temple MQ Map Room Enemy Chest': 'Small Key (Spirit Temple)', 'Spirit Temple MQ Entrance Back Left Chest': 'Small Key (Spirit Temple)', 'Spirit Temple MQ Entrance Front Right Chest': 'Small Key (Spirit Temple)', 'Spirit Temple MQ Mirror Puzzle Invisible Chest': 'Small Key (Spirit Temple)', 'Spirit Temple MQ Silver Block Hallway Chest': 'Small Key (Spirit Temple)', 'Water Temple MQ Central Pillar Chest': 'Small Key (Water Temple)', 'Water Temple MQ Freestanding Key': 'Small Key (Water Temple)', } junk_pool_base = [ ('Bombs (5)', 8), ('Bombs (10)', 2), ('Arrows (5)', 8), ('Arrows (10)', 2), ('Deku Stick (1)', 5), ('Deku Nuts (5)', 5), ('Deku Seeds (30)', 5), ('Rupees (5)', 10), ('Rupees (20)', 4), ('Rupees (50)', 1), ] pending_junk_pool = [] junk_pool = [] remove_junk_items = [ 'Bombs (5)', 'Deku Nuts (5)', 'Deku Stick (1)', 'Recovery Heart', 'Arrows (5)', 'Arrows (10)', 'Arrows (30)', 'Rupees (5)', 'Rupees (20)', 'Rupees (50)', 'Rupees (200)', 'Deku Nuts (10)', 'Bombs (10)', 'Bombs (20)', 'Deku Seeds (30)', 'Ice Trap', ] remove_junk_set = set(remove_junk_items) exclude_from_major = [ 'Deliver Letter', 'Sell Big Poe', 'Magic Bean', 'Zeldas Letter', 'Bombchus (5)', 'Bombchus (10)', 'Bombchus (20)', 'Odd Potion', 'Triforce Piece' ] item_groups = { 'Junk': remove_junk_items, 'JunkSong': ('Prelude of Light', 'Serenade of Water'), 'AdultTrade': tradeitems, 'Bottle': normal_bottles, 'Spell': ('Dins Fire', 'Farores Wind', 'Nayrus Love'), 'Shield': ('Deku Shield', 'Hylian Shield'), 'Song': songlist, 'NonWarpSong': songlist[0:6], 'WarpSong': songlist[6:], 'HealthUpgrade': ('Heart Container', 'Piece of Heart'), 'ProgressItem': [name for (name, data) in item_table.items() if data[0] == 'Item' and data[1]], 'MajorItem': [name for (name, data) in item_table.items() if (data[0] == 'Item' or data[0] == 'Song') and data[1] and name not in exclude_from_major], 'DungeonReward': dungeon_rewards, 'ForestFireWater': ('Forest Medallion', 'Fire Medallion', 'Water Medallion'), 'FireWater': ('Fire Medallion', 'Water Medallion'), } random = None def get_junk_pool(ootworld): junk_pool[:] = list(junk_pool_base) if ootworld.junk_ice_traps == 'on': junk_pool.append(('Ice Trap', 10)) elif ootworld.junk_ice_traps in ['mayhem', 'onslaught']: junk_pool[:] = [('Ice Trap', 1)] return junk_pool def get_junk_item(count=1, pool=None, plando_pool=None): global random if count < 1: raise ValueError("get_junk_item argument 'count' must be greater than 0.") return_pool = [] if pending_junk_pool: pending_count = min(len(pending_junk_pool), count) return_pool = [pending_junk_pool.pop() for _ in range(pending_count)] count -= pending_count if pool and plando_pool: jw_list = [(junk, weight) for (junk, weight) in junk_pool if junk not in plando_pool or pool.count(junk) < plando_pool[junk].count] try: junk_items, junk_weights = zip(*jw_list) except ValueError: raise RuntimeError("Not enough junk is available in the item pool to replace removed items.") else: junk_items, junk_weights = zip(*junk_pool) return_pool.extend(random.choices(junk_items, weights=junk_weights, k=count)) return return_pool def replace_max_item(items, item, max): count = 0 for i,val in enumerate(items): if val == item: if count >= max: items[i] = get_junk_item()[0] count += 1 def generate_itempool(ootworld): world = ootworld.world player = ootworld.player global random random = world.random junk_pool = get_junk_pool(ootworld) fixed_locations = filter(lambda loc: loc.name in fixedlocations, ootworld.get_locations()) for location in fixed_locations: item = fixedlocations[location.name] location.place_locked_item(ootworld.create_item(item)) drop_locations = filter(lambda loc: loc.type == 'Drop', ootworld.get_locations()) for drop_location in drop_locations: item = droplocations[drop_location.name] drop_location.place_locked_item(ootworld.create_item(item)) # set up item pool (pool, placed_items, skip_in_spoiler_locations) = get_pool_core(ootworld) ootworld.itempool = [ootworld.create_item(item) for item in pool] for (location_name, item) in placed_items.items(): location = world.get_location(location_name, player) location.place_locked_item(ootworld.create_item(item)) if location_name in skip_in_spoiler_locations: location.show_in_spoiler = False # def try_collect_heart_container(world, pool): # if 'Heart Container' in pool: # pool.remove('Heart Container') # pool.extend(get_junk_item()) # world.state.collect(ItemFactory('Heart Container')) # return True # return False # def try_collect_pieces_of_heart(world, pool): # n = pool.count('Piece of Heart') + pool.count('Piece of Heart (Treasure Chest Game)') # if n >= 4: # for i in range(4): # if 'Piece of Heart' in pool: # pool.remove('Piece of Heart') # world.state.collect(ItemFactory('Piece of Heart')) # else: # pool.remove('Piece of Heart (Treasure Chest Game)') # world.state.collect(ItemFactory('Piece of Heart (Treasure Chest Game)')) # pool.extend(get_junk_item()) # return True # return False # def collect_pieces_of_heart(world, pool): # success = try_collect_pieces_of_heart(world, pool) # if not success: # try_collect_heart_container(world, pool) # def collect_heart_container(world, pool): # success = try_collect_heart_container(world, pool) # if not success: # try_collect_pieces_of_heart(world, pool) def get_pool_core(world): global random pool = [] placed_items = { 'HC Zeldas Letter': 'Zeldas Letter', } skip_in_spoiler_locations = [] if world.shuffle_kokiri_sword: pool.append('Kokiri Sword') else: placed_items['KF Kokiri Sword Chest'] = 'Kokiri Sword' ruto_bottles = 1 if world.zora_fountain == 'open': ruto_bottles = 0 elif world.item_pool_value == 'plentiful': ruto_bottles += 1 if world.skip_child_zelda: placed_items['HC Malon Egg'] = 'Recovery Heart' skip_in_spoiler_locations.append('HC Malon Egg') elif world.shuffle_weird_egg: pool.append('Weird Egg') else: placed_items['HC Malon Egg'] = 'Weird Egg' if world.shuffle_ocarinas: pool.extend(['Ocarina'] * 2) if world.item_pool_value == 'plentiful': pending_junk_pool.append('Ocarina') else: placed_items['LW Gift from Saria'] = 'Ocarina' placed_items['HF Ocarina of Time Item'] = 'Ocarina' if world.shuffle_cows: pool.extend(get_junk_item(10 if world.dungeon_mq['Jabu Jabus Belly'] else 9)) else: cow_locations = ['LLR Stables Left Cow', 'LLR Stables Right Cow', 'LLR Tower Left Cow', 'LLR Tower Right Cow', 'KF Links House Cow', 'Kak Impas House Cow', 'GV Cow', 'DMT Cow Grotto Cow', 'HF Cow Grotto Cow'] if world.dungeon_mq['Jabu Jabus Belly']: cow_locations.append('Jabu Jabus Belly MQ Cow') for loc in cow_locations: placed_items[loc] = 'Milk' skip_in_spoiler_locations.append(loc) if world.shuffle_beans: pool.append('Magic Bean Pack') if world.item_pool_value == 'plentiful': pending_junk_pool.append('Magic Bean Pack') else: placed_items['ZR Magic Bean Salesman'] = 'Magic Bean' skip_in_spoiler_locations.append('ZR Magic Bean Salesman') if world.shuffle_medigoron_carpet_salesman: pool.append('Giants Knife') else: placed_items['GC Medigoron'] = 'Giants Knife' skip_in_spoiler_locations.append('GC Medigoron') if world.dungeon_mq['Deku Tree']: skulltula_locations_final = skulltula_locations + [ 'Deku Tree MQ GS Lobby', 'Deku Tree MQ GS Compass Room', 'Deku Tree MQ GS Basement Graves Room', 'Deku Tree MQ GS Basement Back Room'] else: skulltula_locations_final = skulltula_locations + [ 'Deku Tree GS Compass Room', 'Deku Tree GS Basement Vines', 'Deku Tree GS Basement Gate', 'Deku Tree GS Basement Back Room'] if world.dungeon_mq['Dodongos Cavern']: skulltula_locations_final.extend([ 'Dodongos Cavern MQ GS Scrub Room', 'Dodongos Cavern MQ GS Song of Time Block Room', 'Dodongos Cavern MQ GS Lizalfos Room', 'Dodongos Cavern MQ GS Larvae Room', 'Dodongos Cavern MQ GS Back Area']) else: skulltula_locations_final.extend([ 'Dodongos Cavern GS Side Room Near Lower Lizalfos', 'Dodongos Cavern GS Vines Above Stairs', 'Dodongos Cavern GS Back Room', 'Dodongos Cavern GS Alcove Above Stairs', 'Dodongos Cavern GS Scarecrow']) if world.dungeon_mq['Jabu Jabus Belly']: skulltula_locations_final.extend([ 'Jabu Jabus Belly MQ GS Tailpasaran Room', 'Jabu Jabus Belly MQ GS Invisible Enemies Room', 'Jabu Jabus Belly MQ GS Boomerang Chest Room', 'Jabu Jabus Belly MQ GS Near Boss']) else: skulltula_locations_final.extend([ 'Jabu Jabus Belly GS Water Switch Room', 'Jabu Jabus Belly GS Lobby Basement Lower', 'Jabu Jabus Belly GS Lobby Basement Upper', 'Jabu Jabus Belly GS Near Boss']) if world.dungeon_mq['Forest Temple']: skulltula_locations_final.extend([ 'Forest Temple MQ GS First Hallway', 'Forest Temple MQ GS Block Push Room', 'Forest Temple MQ GS Raised Island Courtyard', 'Forest Temple MQ GS Level Island Courtyard', 'Forest Temple MQ GS Well']) else: skulltula_locations_final.extend([ 'Forest Temple GS First Room', 'Forest Temple GS Lobby', 'Forest Temple GS Raised Island Courtyard', 'Forest Temple GS Level Island Courtyard', 'Forest Temple GS Basement']) if world.dungeon_mq['Fire Temple']: skulltula_locations_final.extend([ 'Fire Temple MQ GS Above Fire Wall Maze', 'Fire Temple MQ GS Fire Wall Maze Center', 'Fire Temple MQ GS Big Lava Room Open Door', 'Fire Temple MQ GS Fire Wall Maze Side Room', 'Fire Temple MQ GS Skull On Fire']) else: skulltula_locations_final.extend([ 'Fire Temple GS Song of Time Room', 'Fire Temple GS Boulder Maze', 'Fire Temple GS Scarecrow Climb', 'Fire Temple GS Scarecrow Top', 'Fire Temple GS Boss Key Loop']) if world.dungeon_mq['Water Temple']: skulltula_locations_final.extend([ 'Water Temple MQ GS Before Upper Water Switch', 'Water Temple MQ GS Freestanding Key Area', 'Water Temple MQ GS Lizalfos Hallway', 'Water Temple MQ GS River', 'Water Temple MQ GS Triple Wall Torch']) else: skulltula_locations_final.extend([ 'Water Temple GS Behind Gate', 'Water Temple GS River', 'Water Temple GS Falling Platform Room', 'Water Temple GS Central Pillar', 'Water Temple GS Near Boss Key Chest']) if world.dungeon_mq['Spirit Temple']: skulltula_locations_final.extend([ 'Spirit Temple MQ GS Symphony Room', 'Spirit Temple MQ GS Leever Room', 'Spirit Temple MQ GS Nine Thrones Room West', 'Spirit Temple MQ GS Nine Thrones Room North', 'Spirit Temple MQ GS Sun Block Room']) else: skulltula_locations_final.extend([ 'Spirit Temple GS Metal Fence', 'Spirit Temple GS Sun on Floor Room', 'Spirit Temple GS Hall After Sun Block Room', 'Spirit Temple GS Boulder Room', 'Spirit Temple GS Lobby']) if world.dungeon_mq['Shadow Temple']: skulltula_locations_final.extend([ 'Shadow Temple MQ GS Falling Spikes Room', 'Shadow Temple MQ GS Wind Hint Room', 'Shadow Temple MQ GS After Wind', 'Shadow Temple MQ GS After Ship', 'Shadow Temple MQ GS Near Boss']) else: skulltula_locations_final.extend([ 'Shadow Temple GS Like Like Room', 'Shadow Temple GS Falling Spikes Room', 'Shadow Temple GS Single Giant Pot', 'Shadow Temple GS Near Ship', 'Shadow Temple GS Triple Giant Pot']) if world.dungeon_mq['Bottom of the Well']: skulltula_locations_final.extend([ 'Bottom of the Well MQ GS Basement', 'Bottom of the Well MQ GS Coffin Room', 'Bottom of the Well MQ GS West Inner Room']) else: skulltula_locations_final.extend([ 'Bottom of the Well GS West Inner Room', 'Bottom of the Well GS East Inner Room', 'Bottom of the Well GS Like Like Cage']) if world.dungeon_mq['Ice Cavern']: skulltula_locations_final.extend([ 'Ice Cavern MQ GS Scarecrow', 'Ice Cavern MQ GS Ice Block', 'Ice Cavern MQ GS Red Ice']) else: skulltula_locations_final.extend([ 'Ice Cavern GS Spinning Scythe Room', 'Ice Cavern GS Heart Piece Room', 'Ice Cavern GS Push Block Room']) if world.tokensanity == 'off': for location in skulltula_locations_final: placed_items[location] = 'Gold Skulltula Token' skip_in_spoiler_locations.append(location) elif world.tokensanity == 'dungeons': for location in skulltula_locations_final: if world.get_location(location).scene >= 0x0A: placed_items[location] = 'Gold Skulltula Token' skip_in_spoiler_locations.append(location) else: pool.append('Gold Skulltula Token') elif world.tokensanity == 'overworld': for location in skulltula_locations_final: if world.get_location(location).scene < 0x0A: placed_items[location] = 'Gold Skulltula Token' skip_in_spoiler_locations.append(location) else: pool.append('Gold Skulltula Token') else: pool.extend(['Gold Skulltula Token'] * 100) if world.bombchus_in_logic: pool.extend(['Bombchus'] * 4) if world.dungeon_mq['Jabu Jabus Belly']: pool.extend(['Bombchus']) if world.dungeon_mq['Spirit Temple']: pool.extend(['Bombchus'] * 2) if not world.dungeon_mq['Bottom of the Well']: pool.extend(['Bombchus']) if world.dungeon_mq['Gerudo Training Grounds']: pool.extend(['Bombchus']) if world.shuffle_medigoron_carpet_salesman: pool.append('Bombchus') else: pool.extend(['Bombchus (5)'] + ['Bombchus (10)'] * 2) if world.dungeon_mq['Jabu Jabus Belly']: pool.extend(['Bombchus (10)']) if world.dungeon_mq['Spirit Temple']: pool.extend(['Bombchus (10)'] * 2) if not world.dungeon_mq['Bottom of the Well']: pool.extend(['Bombchus (10)']) if world.dungeon_mq['Gerudo Training Grounds']: pool.extend(['Bombchus (10)']) if world.dungeon_mq['Ganons Castle']: pool.extend(['Bombchus (10)']) else: pool.extend(['Bombchus (20)']) if world.shuffle_medigoron_carpet_salesman: pool.append('Bombchus (10)') if not world.shuffle_medigoron_carpet_salesman: placed_items['Wasteland Bombchu Salesman'] = 'Bombchus (10)' skip_in_spoiler_locations.append('Wasteland Bombchu Salesman') pool.extend(['Ice Trap']) if not world.dungeon_mq['Gerudo Training Grounds']: pool.extend(['Ice Trap']) if not world.dungeon_mq['Ganons Castle']: pool.extend(['Ice Trap'] * 4) if world.gerudo_fortress == 'open': placed_items['GF North F1 Carpenter'] = 'Recovery Heart' placed_items['GF North F2 Carpenter'] = 'Recovery Heart' placed_items['GF South F1 Carpenter'] = 'Recovery Heart' placed_items['GF South F2 Carpenter'] = 'Recovery Heart' skip_in_spoiler_locations.extend(['GF North F1 Carpenter', 'GF North F2 Carpenter', 'GF South F1 Carpenter', 'GF South F2 Carpenter']) elif world.shuffle_fortresskeys in ['any_dungeon', 'overworld', 'keysanity']: if world.gerudo_fortress == 'fast': pool.append('Small Key (Gerudo Fortress)') placed_items['GF North F2 Carpenter'] = 'Recovery Heart' placed_items['GF South F1 Carpenter'] = 'Recovery Heart' placed_items['GF South F2 Carpenter'] = 'Recovery Heart' skip_in_spoiler_locations.extend(['GF North F2 Carpenter', 'GF South F1 Carpenter', 'GF South F2 Carpenter']) else: pool.extend(['Small Key (Gerudo Fortress)'] * 4) if world.item_pool_value == 'plentiful': pending_junk_pool.append('Small Key (Gerudo Fortress)') else: if world.gerudo_fortress == 'fast': placed_items['GF North F1 Carpenter'] = 'Small Key (Gerudo Fortress)' placed_items['GF North F2 Carpenter'] = 'Recovery Heart' placed_items['GF South F1 Carpenter'] = 'Recovery Heart' placed_items['GF South F2 Carpenter'] = 'Recovery Heart' skip_in_spoiler_locations.extend(['GF North F2 Carpenter', 'GF South F1 Carpenter', 'GF South F2 Carpenter']) else: placed_items['GF North F1 Carpenter'] = 'Small Key (Gerudo Fortress)' placed_items['GF North F2 Carpenter'] = 'Small Key (Gerudo Fortress)' placed_items['GF South F1 Carpenter'] = 'Small Key (Gerudo Fortress)' placed_items['GF South F2 Carpenter'] = 'Small Key (Gerudo Fortress)' if world.shuffle_gerudo_card and world.gerudo_fortress != 'open': pool.append('Gerudo Membership Card') elif world.shuffle_gerudo_card: pending_junk_pool.append('Gerudo Membership Card') placed_items['GF Gerudo Membership Card'] = 'Ice Trap' skip_in_spoiler_locations.append('GF Gerudo Membership Card') else: placed_items['GF Gerudo Membership Card'] = 'Gerudo Membership Card' if world.shuffle_gerudo_card and world.item_pool_value == 'plentiful': pending_junk_pool.append('Gerudo Membership Card') if world.item_pool_value == 'plentiful' and world.shuffle_smallkeys in ['any_dungeon', 'overworld', 'keysanity']: pending_junk_pool.append('Small Key (Bottom of the Well)') pending_junk_pool.append('Small Key (Forest Temple)') pending_junk_pool.append('Small Key (Fire Temple)') pending_junk_pool.append('Small Key (Water Temple)') pending_junk_pool.append('Small Key (Shadow Temple)') pending_junk_pool.append('Small Key (Spirit Temple)') pending_junk_pool.append('Small Key (Gerudo Training Grounds)') pending_junk_pool.append('Small Key (Ganons Castle)') if world.item_pool_value == 'plentiful' and world.shuffle_bosskeys in ['any_dungeon', 'overworld', 'keysanity']: pending_junk_pool.append('Boss Key (Forest Temple)') pending_junk_pool.append('Boss Key (Fire Temple)') pending_junk_pool.append('Boss Key (Water Temple)') pending_junk_pool.append('Boss Key (Shadow Temple)') pending_junk_pool.append('Boss Key (Spirit Temple)') if world.item_pool_value == 'plentiful' and world.shuffle_ganon_bosskey in ['any_dungeon', 'overworld', 'keysanity']: pending_junk_pool.append('Boss Key (Ganons Castle)') if world.shopsanity == 'off': placed_items.update(vanilla_shop_items) if world.bombchus_in_logic: placed_items['KF Shop Item 8'] = 'Buy Bombchu (5)' placed_items['Market Bazaar Item 4'] = 'Buy Bombchu (5)' placed_items['Kak Bazaar Item 4'] = 'Buy Bombchu (5)' pool.extend(normal_rupees) skip_in_spoiler_locations.extend(vanilla_shop_items.keys()) if world.bombchus_in_logic: skip_in_spoiler_locations.remove('KF Shop Item 8') skip_in_spoiler_locations.remove('Market Bazaar Item 4') skip_in_spoiler_locations.remove('Kak Bazaar Item 4') else: remain_shop_items = list(vanilla_shop_items.values()) pool.extend(min_shop_items) for item in min_shop_items: remain_shop_items.remove(item) shop_slots_count = len(remain_shop_items) shop_nonitem_count = len(world.shop_prices) shop_item_count = shop_slots_count - shop_nonitem_count pool.extend(random.sample(remain_shop_items, shop_item_count)) if shop_nonitem_count: pool.extend(get_junk_item(shop_nonitem_count)) if world.shopsanity == '0': pool.extend(normal_rupees) else: pool.extend(shopsanity_rupees) if world.shuffle_scrubs != 'off': if world.dungeon_mq['Deku Tree']: pool.append('Deku Shield') if world.dungeon_mq['Dodongos Cavern']: pool.extend(['Deku Stick (1)', 'Deku Shield', 'Recovery Heart']) else: pool.extend(['Deku Nuts (5)', 'Deku Stick (1)', 'Deku Shield']) if not world.dungeon_mq['Jabu Jabus Belly']: pool.append('Deku Nuts (5)') if world.dungeon_mq['Ganons Castle']: pool.extend(['Bombs (5)', 'Recovery Heart', 'Rupees (5)', 'Deku Nuts (5)']) else: pool.extend(['Bombs (5)', 'Recovery Heart', 'Rupees (5)']) pool.extend(deku_scrubs_items) for _ in range(7): pool.append('Arrows (30)' if random.randint(0,3) > 0 else 'Deku Seeds (30)') else: if world.dungeon_mq['Deku Tree']: placed_items['Deku Tree MQ Deku Scrub'] = 'Buy Deku Shield' skip_in_spoiler_locations.append('Deku Tree MQ Deku Scrub') if world.dungeon_mq['Dodongos Cavern']: placed_items['Dodongos Cavern MQ Deku Scrub Lobby Rear'] = 'Buy Deku Stick (1)' placed_items['Dodongos Cavern MQ Deku Scrub Lobby Front'] = 'Buy Deku Seeds (30)' placed_items['Dodongos Cavern MQ Deku Scrub Staircase'] = 'Buy Deku Shield' placed_items['Dodongos Cavern MQ Deku Scrub Side Room Near Lower Lizalfos'] = 'Buy Red Potion [30]' skip_in_spoiler_locations.extend(['Dodongos Cavern MQ Deku Scrub Lobby Rear', 'Dodongos Cavern MQ Deku Scrub Lobby Front', 'Dodongos Cavern MQ Deku Scrub Staircase', 'Dodongos Cavern MQ Deku Scrub Side Room Near Lower Lizalfos']) else: placed_items['Dodongos Cavern Deku Scrub Near Bomb Bag Left'] = 'Buy Deku Nut (5)' placed_items['Dodongos Cavern Deku Scrub Side Room Near Dodongos'] = 'Buy Deku Stick (1)' placed_items['Dodongos Cavern Deku Scrub Near Bomb Bag Right'] = 'Buy Deku Seeds (30)' placed_items['Dodongos Cavern Deku Scrub Lobby'] = 'Buy Deku Shield' skip_in_spoiler_locations.extend(['Dodongos Cavern Deku Scrub Near Bomb Bag Left', 'Dodongos Cavern Deku Scrub Side Room Near Dodongos', 'Dodongos Cavern Deku Scrub Near Bomb Bag Right', 'Dodongos Cavern Deku Scrub Lobby']) if not world.dungeon_mq['Jabu Jabus Belly']: placed_items['Jabu Jabus Belly Deku Scrub'] = 'Buy Deku Nut (5)' skip_in_spoiler_locations.append('Jabu Jabus Belly Deku Scrub') if world.dungeon_mq['Ganons Castle']: placed_items['Ganons Castle MQ Deku Scrub Right'] = 'Buy Deku Nut (5)' placed_items['Ganons Castle MQ Deku Scrub Center-Left'] = 'Buy Bombs (5) [35]' placed_items['Ganons Castle MQ Deku Scrub Center'] = 'Buy Arrows (30)' placed_items['Ganons Castle MQ Deku Scrub Center-Right'] = 'Buy Red Potion [30]' placed_items['Ganons Castle MQ Deku Scrub Left'] = 'Buy Green Potion' skip_in_spoiler_locations.extend(['Ganons Castle MQ Deku Scrub Right', 'Ganons Castle MQ Deku Scrub Center-Left', 'Ganons Castle MQ Deku Scrub Center', 'Ganons Castle MQ Deku Scrub Center-Right', 'Ganons Castle MQ Deku Scrub Left']) else: placed_items['Ganons Castle Deku Scrub Center-Left'] = 'Buy Bombs (5) [35]' placed_items['Ganons Castle Deku Scrub Center-Right'] = 'Buy Arrows (30)' placed_items['Ganons Castle Deku Scrub Right'] = 'Buy Red Potion [30]' placed_items['Ganons Castle Deku Scrub Left'] = 'Buy Green Potion' skip_in_spoiler_locations.extend(['Ganons Castle Deku Scrub Right', 'Ganons Castle Deku Scrub Center-Left', 'Ganons Castle Deku Scrub Center-Right', 'Ganons Castle Deku Scrub Left']) placed_items.update(vanilla_deku_scrubs) skip_in_spoiler_locations.extend(vanilla_deku_scrubs.keys()) pool.extend(alwaysitems) if world.dungeon_mq['Deku Tree']: pool.extend(DT_MQ) else: pool.extend(DT_vanilla) if world.dungeon_mq['Dodongos Cavern']: pool.extend(DC_MQ) else: pool.extend(DC_vanilla) if world.dungeon_mq['Jabu Jabus Belly']: pool.extend(JB_MQ) if world.dungeon_mq['Forest Temple']: pool.extend(FoT_MQ) else: pool.extend(FoT_vanilla) if world.dungeon_mq['Fire Temple']: pool.extend(FiT_MQ) else: pool.extend(FiT_vanilla) if world.dungeon_mq['Spirit Temple']: pool.extend(SpT_MQ) else: pool.extend(SpT_vanilla) if world.dungeon_mq['Shadow Temple']: pool.extend(ShT_MQ) else: pool.extend(ShT_vanilla) if not world.dungeon_mq['Bottom of the Well']: pool.extend(BW_vanilla) if world.dungeon_mq['Gerudo Training Grounds']: pool.extend(GTG_MQ) else: pool.extend(GTG_vanilla) if world.dungeon_mq['Ganons Castle']: pool.extend(GC_MQ) else: pool.extend(GC_vanilla) for i in range(bottle_count): if i >= ruto_bottles: bottle = random.choice(normal_bottles) pool.append(bottle) else: pool.append('Rutos Letter') earliest_trade = tradeitemoptions.index(world.logic_earliest_adult_trade) latest_trade = tradeitemoptions.index(world.logic_latest_adult_trade) if earliest_trade > latest_trade: earliest_trade, latest_trade = latest_trade, earliest_trade tradeitem = random.choice(tradeitems[earliest_trade:latest_trade+1]) world.selected_adult_trade_item = tradeitem pool.append(tradeitem) pool.extend(songlist) if world.shuffle_song_items == 'any' and world.item_pool_value == 'plentiful': pending_junk_pool.extend(songlist) if world.free_scarecrow: item = world.create_item('Scarecrow Song') world.world.push_precollected(item) world.remove_from_start_inventory.append(item.name) if world.no_epona_race: item = world.create_item('Epona') world.world.push_precollected(item) world.remove_from_start_inventory.append(item.name) if world.shuffle_mapcompass == 'remove' or world.shuffle_mapcompass == 'startwith': for item in [item for dungeon in world.dungeons for item in dungeon.dungeon_items]: world.world.push_precollected(item) world.remove_from_start_inventory.append(item.name) pool.extend(get_junk_item()) if world.shuffle_smallkeys == 'remove': for item in [item for dungeon in world.dungeons for item in dungeon.small_keys]: world.world.push_precollected(item) world.remove_from_start_inventory.append(item.name) pool.extend(get_junk_item()) if world.shuffle_bosskeys == 'remove': for item in [item for dungeon in world.dungeons if dungeon.name != 'Ganons Castle' for item in dungeon.boss_key]: world.world.push_precollected(item) world.remove_from_start_inventory.append(item.name) pool.extend(get_junk_item()) if world.shuffle_ganon_bosskey in ['remove', 'triforce']: for item in [item for dungeon in world.dungeons if dungeon.name == 'Ganons Castle' for item in dungeon.boss_key]: world.world.push_precollected(item) world.remove_from_start_inventory.append(item.name) pool.extend(get_junk_item()) if world.shuffle_mapcompass == 'vanilla': for location, item in vanillaMC.items(): try: world.get_location(location) placed_items[location] = item except KeyError: continue if world.shuffle_smallkeys == 'vanilla': for location, item in vanillaSK.items(): try: world.get_location(location) placed_items[location] = item except KeyError: continue # Logic cannot handle vanilla key layout in some dungeons # this is because vanilla expects the dungeon major item to be # locked behind the keys, which is not always true in rando. # We can resolve this by starting with some extra keys if world.dungeon_mq['Spirit Temple']: # Yes somehow you need 3 keys. This dungeon is bonkers world.world.push_precollected(world.create_item('Small Key (Spirit Temple)')) world.world.push_precollected(world.create_item('Small Key (Spirit Temple)')) world.world.push_precollected(world.create_item('Small Key (Spirit Temple)')) #if not world.dungeon_mq['Fire Temple']: # world.state.collect(ItemFactory('Small Key (Fire Temple)')) if world.shuffle_bosskeys == 'vanilla': for location, item in vanillaBK.items(): try: world.get_location(location) placed_items[location] = item except KeyError: continue if not world.keysanity and not world.dungeon_mq['Fire Temple']: item = world.create_item('Small Key (Fire Temple)') world.world.push_precollected(item) world.remove_from_start_inventory.append(item.name) if world.triforce_hunt: triforce_count = int((Decimal(100 + world.extra_triforce_percentage)/100 * world.triforce_goal).to_integral_value(rounding=ROUND_HALF_UP)) pending_junk_pool.extend(['Triforce Piece'] * triforce_count) if world.shuffle_ganon_bosskey == 'on_lacs': placed_items['ToT Light Arrows Cutscene'] = 'Boss Key (Ganons Castle)' elif world.shuffle_ganon_bosskey == 'vanilla': placed_items['Ganons Tower Boss Key Chest'] = 'Boss Key (Ganons Castle)' if world.item_pool_value == 'plentiful': pool.extend(easy_items) else: pool.extend(normal_items) if not world.shuffle_kokiri_sword: replace_max_item(pool, 'Kokiri Sword', 0) if world.junk_ice_traps == 'off': replace_max_item(pool, 'Ice Trap', 0) elif world.junk_ice_traps == 'onslaught': for item in [item for item, weight in junk_pool_base] + ['Recovery Heart', 'Bombs (20)', 'Arrows (30)']: replace_max_item(pool, item, 0) for item,max in item_difficulty_max[world.item_pool_value].items(): replace_max_item(pool, item, max) if world.damage_multiplier in ['ohko', 'quadruple'] and world.item_pool_value == 'minimal': pending_junk_pool.append('Nayrus Love') # world.distribution.alter_pool(world, pool) # Make sure our pending_junk_pool is empty. If not, remove some random junk here. if pending_junk_pool: remove_junk_pool, _ = zip(*junk_pool_base) # Omits Rupees (200) and Deku Nuts (10) remove_junk_pool = list(remove_junk_pool) + ['Recovery Heart', 'Bombs (20)', 'Arrows (30)', 'Ice Trap'] junk_candidates = [item for item in pool if item in remove_junk_pool] while pending_junk_pool: pending_item = pending_junk_pool.pop() if not junk_candidates: raise RuntimeError("Not enough junk exists in item pool for %s to be added." % pending_item) junk_item = random.choice(junk_candidates) junk_candidates.remove(junk_item) pool.remove(junk_item) pool.append(pending_item) return (pool, placed_items, skip_in_spoiler_locations) def add_dungeon_items(ootworld): """Adds maps, compasses, small keys, boss keys, and Ganon boss key into item pool if they are not placed.""" skip_add_settings = {'remove', 'startwith', 'vanilla', 'on_lacs'} for dungeon in ootworld.dungeons: if ootworld.shuffle_mapcompass not in skip_add_settings: ootworld.itempool.extend(dungeon.dungeon_items) if ootworld.shuffle_smallkeys not in skip_add_settings: ootworld.itempool.extend(dungeon.small_keys) if dungeon.name != 'Ganons Castle' and ootworld.shuffle_bosskeys not in skip_add_settings: ootworld.itempool.extend(dungeon.boss_key) if dungeon.name == 'Ganons Castle' and ootworld.shuffle_ganon_bosskey not in skip_add_settings: ootworld.itempool.extend(dungeon.boss_key) <file_sep>from __future__ import annotations import os import logging import json import string import copy import subprocess import time import factorio_rcon import colorama import asyncio from queue import Queue from CommonClient import CommonContext, server_loop, console_loop, ClientCommandProcessor, logger, gui_enabled, \ init_logging from MultiServer import mark_raw import Utils import random from NetUtils import NetworkItem, ClientStatus, JSONtoTextParser, JSONMessagePart from worlds.factorio import Factorio init_logging("FactorioClient") class FactorioCommandProcessor(ClientCommandProcessor): ctx: FactorioContext @mark_raw def _cmd_factorio(self, text: str) -> bool: """Send the following command to the bound Factorio Server.""" if self.ctx.rcon_client: # TODO: Print the command non-silently only for race seeds, or otherwise block anything but /factorio /save in race seeds. self.ctx.print_to_game(f"/factorio {text}") result = self.ctx.rcon_client.send_command(text) if result: self.output(result) return True return False def _cmd_resync(self): """Manually trigger a resync.""" self.ctx.awaiting_bridge = True class FactorioContext(CommonContext): command_processor = FactorioCommandProcessor game = "Factorio" # updated by spinup server mod_version: Utils.Version = Utils.Version(0, 0, 0) def __init__(self, server_address, password): super(FactorioContext, self).__init__(server_address, password) self.send_index: int = 0 self.rcon_client = None self.awaiting_bridge = False self.write_data_path = None self.death_link_tick: int = 0 # last send death link on Factorio layer self.factorio_json_text_parser = FactorioJSONtoTextParser(self) async def server_auth(self, password_requested: bool = False): if password_requested and not self.password: await super(FactorioContext, self).server_auth(password_requested) if not self.auth: if self.rcon_client: get_info(self, self.rcon_client) # retrieve current auth code else: raise Exception("Cannot connect to a server with unknown own identity, " "bridge to Factorio first.") await self.send_msgs([{ "cmd": 'Connect', 'password': <PASSWORD>, 'name': self.auth, 'version': Utils.version_tuple, 'tags': self.tags, 'uuid': Utils.get_unique_identifier(), 'game': "Factorio" }]) def on_print(self, args: dict): super(FactorioContext, self).on_print(args) if self.rcon_client: self.print_to_game(args['text']) def on_print_json(self, args: dict): if self.rcon_client: text = self.factorio_json_text_parser(copy.deepcopy(args["data"])) self.print_to_game(text) super(FactorioContext, self).on_print_json(args) @property def savegame_name(self) -> str: return f"AP_{self.seed_name}_{self.auth}_Save.zip" def print_to_game(self, text): self.rcon_client.send_command(f"/ap-print [font=default-large-bold]Archipelago:[/font] " f"{text}") def on_deathlink(self, data: dict): if self.rcon_client: self.rcon_client.send_command(f"/ap-deathlink {data['source']}") def on_package(self, cmd: str, args: dict): if cmd in {"Connected", "RoomUpdate"}: # catch up sync anything that is already cleared. if "checked_locations" in args and args["checked_locations"]: self.rcon_client.send_commands({item_name: f'/ap-get-technology ap-{item_name}-\t-1' for item_name in args["checked_locations"]}) async def game_watcher(ctx: FactorioContext): bridge_logger = logging.getLogger("FactorioWatcher") from worlds.factorio.Technologies import lookup_id_to_name next_bridge = time.perf_counter() + 1 try: while not ctx.exit_event.is_set(): if ctx.awaiting_bridge and ctx.rcon_client and time.perf_counter() > next_bridge: next_bridge = time.perf_counter() + 1 ctx.awaiting_bridge = False data = json.loads(ctx.rcon_client.send_command("/ap-sync")) if data["slot_name"] != ctx.auth: bridge_logger.warning(f"Connected World is not the expected one {data['slot_name']} != {ctx.auth}") elif data["seed_name"] != ctx.seed_name: bridge_logger.warning( f"Connected Multiworld is not the expected one {data['seed_name']} != {ctx.seed_name}") else: data = data["info"] research_data = data["research_done"] research_data = {int(tech_name.split("-")[1]) for tech_name in research_data} victory = data["victory"] if not ctx.finished_game and victory: await ctx.send_msgs([{"cmd": "StatusUpdate", "status": ClientStatus.CLIENT_GOAL}]) ctx.finished_game = True if ctx.locations_checked != research_data: bridge_logger.info( f"New researches done: " f"{[lookup_id_to_name[rid] for rid in research_data - ctx.locations_checked]}") ctx.locations_checked = research_data await ctx.send_msgs([{"cmd": 'LocationChecks', "locations": tuple(research_data)}]) death_link_tick = data.get("death_link_tick", 0) if death_link_tick != ctx.death_link_tick: ctx.death_link_tick = death_link_tick await ctx.send_death() await asyncio.sleep(0.1) except Exception as e: logging.exception(e) logging.error("Aborted Factorio Server Bridge") def stream_factorio_output(pipe, queue, process): def queuer(): while process.poll() is None: text = pipe.readline().strip() if text: queue.put_nowait(text) from threading import Thread thread = Thread(target=queuer, name="Factorio Output Queue", daemon=True) thread.start() return thread async def factorio_server_watcher(ctx: FactorioContext): savegame_name = os.path.abspath(ctx.savegame_name) if not os.path.exists(savegame_name): logger.info(f"Creating savegame {savegame_name}") subprocess.run(( executable, "--create", savegame_name, "--preset", "archipelago" )) factorio_process = subprocess.Popen((executable, "--start-server", ctx.savegame_name, *(str(elem) for elem in server_args)), stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, encoding="utf-8") factorio_server_logger.info("Started Factorio Server") factorio_queue = Queue() stream_factorio_output(factorio_process.stdout, factorio_queue, factorio_process) stream_factorio_output(factorio_process.stderr, factorio_queue, factorio_process) try: while not ctx.exit_event.is_set(): if factorio_process.poll(): factorio_server_logger.info("Factorio server has exited.") ctx.exit_event.set() while not factorio_queue.empty(): msg = factorio_queue.get() factorio_server_logger.info(msg) if not ctx.rcon_client and "Starting RCON interface at IP ADDR:" in msg: ctx.rcon_client = factorio_rcon.RCONClient("localhost", rcon_port, rcon_password) if not ctx.server: logger.info("Established bridge to Factorio Server. " "Ready to connect to Archipelago via /connect") if not ctx.awaiting_bridge and "Archipelago Bridge Data available for game tick " in msg: ctx.awaiting_bridge = True if ctx.rcon_client: commands = {} while ctx.send_index < len(ctx.items_received): transfer_item: NetworkItem = ctx.items_received[ctx.send_index] item_id = transfer_item.item player_name = ctx.player_names[transfer_item.player] if item_id not in Factorio.item_id_to_name: factorio_server_logger.error(f"Cannot send unknown item ID: {item_id}") else: item_name = Factorio.item_id_to_name[item_id] factorio_server_logger.info(f"Sending {item_name} to Nauvis from {player_name}.") commands[ctx.send_index] = f'/ap-get-technology {item_name}\t{ctx.send_index}\t{player_name}' ctx.send_index += 1 if commands: ctx.rcon_client.send_commands(commands) await asyncio.sleep(0.1) except Exception as e: logging.exception(e) logging.error("Aborted Factorio Server Bridge") ctx.rcon_client = None ctx.exit_event.set() finally: factorio_process.terminate() factorio_process.wait(5) def get_info(ctx, rcon_client): info = json.loads(rcon_client.send_command("/ap-rcon-info")) ctx.auth = info["slot_name"] ctx.seed_name = info["seed_name"] # 0.2.0 addition, not present earlier death_link = bool(info.get("death_link", False)) if death_link: ctx.tags.add("DeathLink") async def factorio_spinup_server(ctx: FactorioContext) -> bool: savegame_name = os.path.abspath("Archipelago.zip") if not os.path.exists(savegame_name): logger.info(f"Creating savegame {savegame_name}") subprocess.run(( executable, "--create", savegame_name )) factorio_process = subprocess.Popen( (executable, "--start-server", savegame_name, *(str(elem) for elem in server_args)), stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, encoding="utf-8") factorio_server_logger.info("Started Information Exchange Factorio Server") factorio_queue = Queue() stream_factorio_output(factorio_process.stdout, factorio_queue, factorio_process) stream_factorio_output(factorio_process.stderr, factorio_queue, factorio_process) rcon_client = None try: while not ctx.auth: while not factorio_queue.empty(): msg = factorio_queue.get() factorio_server_logger.info(msg) if "Loading mod AP-" in msg and msg.endswith("(data.lua)"): parts = msg.split() ctx.mod_version = Utils.Version(*(int(number) for number in parts[-2].split("."))) elif "Write data path: " in msg: ctx.write_data_path = Utils.get_text_between(msg, "Write data path: ", " [") if "AppData" in ctx.write_data_path: logger.warning("It appears your mods are loaded from Appdata, " "this can lead to problems with multiple Factorio instances. " "If this is the case, you will get a file locked error running Factorio.") if not rcon_client and "Starting RCON interface at IP ADDR:" in msg: rcon_client = factorio_rcon.RCONClient("localhost", rcon_port, rcon_password) if ctx.mod_version == ctx.__class__.mod_version: raise Exception("No Archipelago mod was loaded. Aborting.") get_info(ctx, rcon_client) await asyncio.sleep(0.01) except Exception as e: logger.exception(e) logger.error("Aborted Factorio Server Bridge") ctx.exit_event.set() else: logger.info( f"Got World Information from AP Mod {tuple(ctx.mod_version)} for seed {ctx.seed_name} in slot {ctx.auth}") return True finally: factorio_process.terminate() factorio_process.wait(5) return False async def main(args): ctx = FactorioContext(args.connect, args.password) ctx.server_task = asyncio.create_task(server_loop(ctx), name="ServerLoop") if gui_enabled: input_task = None from kvui import FactorioManager ctx.ui = FactorioManager(ctx) ui_task = asyncio.create_task(ctx.ui.async_run(), name="UI") else: input_task = asyncio.create_task(console_loop(ctx), name="Input") ui_task = None factorio_server_task = asyncio.create_task(factorio_spinup_server(ctx), name="FactorioSpinupServer") succesful_launch = await factorio_server_task if succesful_launch: factorio_server_task = asyncio.create_task(factorio_server_watcher(ctx), name="FactorioServer") progression_watcher = asyncio.create_task( game_watcher(ctx), name="FactorioProgressionWatcher") await ctx.exit_event.wait() ctx.server_address = None await progression_watcher await factorio_server_task if ctx.server and not ctx.server.socket.closed: await ctx.server.socket.close() if ctx.server_task: await ctx.server_task while ctx.input_requests > 0: ctx.input_queue.put_nowait(None) ctx.input_requests -= 1 if ui_task: await ui_task if input_task: input_task.cancel() class FactorioJSONtoTextParser(JSONtoTextParser): def _handle_color(self, node: JSONMessagePart): colors = node["color"].split(";") for color in colors: if color in {"red", "green", "blue", "orange", "yellow", "pink", "purple", "white", "black", "gray", "brown", "cyan", "acid"}: node["text"] = f"[color={color}]{node['text']}[/color]" return self._handle_text(node) elif color == "magenta": node["text"] = f"[color=pink]{node['text']}[/color]" return self._handle_text(node) return self._handle_text(node) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description="Optional arguments to FactorioClient follow. " "Remaining arguments get passed into bound Factorio instance." "Refer to Factorio --help for those.") parser.add_argument('--rcon-port', default='24242', type=int, help='Port to use to communicate with Factorio') parser.add_argument('--rcon-password', help='Password to authenticate with RCON.') parser.add_argument('--connect', default=None, help='Address of the multiworld host.') parser.add_argument('--password', default=None, help='Password of the multiworld host.') if not Utils.is_frozen(): # Frozen state has no cmd window in the first place parser.add_argument('--nogui', default=False, action='store_true', help="Turns off Client GUI.") args, rest = parser.parse_known_args() colorama.init() rcon_port = args.rcon_port rcon_password = args.rcon_password if args.rcon_password else ''.join( random.choice(string.ascii_letters) for x in range(32)) factorio_server_logger = logging.getLogger("FactorioServer") options = Utils.get_options() executable = options["factorio_options"]["executable"] if not os.path.exists(os.path.dirname(executable)): raise FileNotFoundError(f"Path {os.path.dirname(executable)} does not exist or could not be accessed.") if os.path.isdir(executable): # user entered a path to a directory, let's find the executable therein executable = os.path.join(executable, "factorio") if not os.path.isfile(executable): if os.path.isfile(executable + ".exe"): executable = executable + ".exe" else: raise FileNotFoundError(f"Path {executable} is not an executable file.") server_args = ("--rcon-port", rcon_port, "--rcon-password", rcon_password, *rest) loop = asyncio.get_event_loop() loop.run_until_complete(main(args)) loop.close() colorama.deinit() <file_sep>import typing from Options import Option, DefaultOnToggle, Toggle hollow_knight_randomize_options: typing.Dict[str, type(Option)] = { "RandomizeDreamers": DefaultOnToggle, "RandomizeSkills": DefaultOnToggle, "RandomizeCharms": DefaultOnToggle, "RandomizeKeys": DefaultOnToggle, "RandomizeGeoChests": Toggle, "RandomizeMaskShards": DefaultOnToggle, "RandomizeVesselFragments": DefaultOnToggle, "RandomizeCharmNotches": Toggle, "RandomizePaleOre": DefaultOnToggle, "RandomizeRancidEggs": Toggle, "RandomizeRelics": DefaultOnToggle, "RandomizeMaps": Toggle, "RandomizeStags": Toggle, "RandomizeGrubs": Toggle, "RandomizeWhisperingRoots": Toggle, "RandomizeRocks": Toggle, "RandomizeSoulTotems": Toggle, "RandomizePalaceTotems": Toggle, "RandomizeLoreTablets": Toggle, "RandomizeLifebloodCocoons": Toggle, "RandomizeFlames": Toggle } hollow_knight_skip_options: typing.Dict[str, type(Option)] = { "MILDSKIPS": Toggle, "SPICYSKIPS": Toggle, "FIREBALLSKIPS": Toggle, "ACIDSKIPS": Toggle, "SPIKETUNNELS": Toggle, "DARKROOMS": Toggle, "CURSED": Toggle, "SHADESKIPS": Toggle, } hollow_knight_options: typing.Dict[str, type(Option)] = {**hollow_knight_randomize_options, **hollow_knight_skip_options}<file_sep>from BaseClasses import Location import typing class AdvData(typing.NamedTuple): id: typing.Optional[int] region: str class MinecraftAdvancement(Location): game: str = "Minecraft" def __init__(self, player: int, name: str, address: typing.Optional[int], parent): super().__init__(player, name, address, parent) self.event = not address advancement_table = { "Who is Cutting Onions?": AdvData(42000, 'Overworld'), "Oh Shiny": AdvData(42001, 'Overworld'), "Suit Up": AdvData(42002, 'Overworld'), "Very Very Frightening": AdvData(42003, 'Overworld'), "Hot Stuff": AdvData(42004, 'Overworld'), "Free the End": AdvData(42005, 'The End'), "A Furious Cocktail": AdvData(42006, 'Nether Fortress'), "Best Friends Forever": AdvData(42007, 'Overworld'), "Bring Home the Beacon": AdvData(42008, 'Nether Fortress'), "Not Today, Thank You": AdvData(42009, 'Overworld'), "Isn't It Iron Pick": AdvData(42010, 'Overworld'), "Local Brewery": AdvData(42011, 'Nether Fortress'), "The Next Generation": AdvData(42012, 'The End'), "Fishy Business": AdvData(42013, 'Overworld'), "Hot Tourist Destinations": AdvData(42014, 'The Nether'), "This Boat Has Legs": AdvData(42015, 'The Nether'), "Sniper Duel": AdvData(42016, 'Overworld'), "Nether": AdvData(42017, 'The Nether'), "Great View From Up Here": AdvData(42018, 'End City'), "How Did We Get Here?": AdvData(42019, 'Nether Fortress'), "Bullseye": AdvData(42020, 'Overworld'), "Spooky Scary Skeleton": AdvData(42021, 'Nether Fortress'), "Two by Two": AdvData(42022, 'The Nether'), "Stone Age": AdvData(42023, 'Overworld'), "Two Birds, One Arrow": AdvData(42024, 'Overworld'), "We Need to Go Deeper": AdvData(42025, 'The Nether'), "Who's the Pillager Now?": AdvData(42026, 'Pillager Outpost'), "Getting an Upgrade": AdvData(42027, 'Overworld'), "Tactical Fishing": AdvData(42028, 'Overworld'), "Zombie Doctor": AdvData(42029, 'Overworld'), "The City at the End of the Game": AdvData(42030, 'End City'), "Ice Bucket Challenge": AdvData(42031, 'Overworld'), "Remote Getaway": AdvData(42032, 'The End'), "Into Fire": AdvData(42033, 'Nether Fortress'), "War Pigs": AdvData(42034, 'Bastion Remnant'), "Take Aim": AdvData(42035, 'Overworld'), "Total Beelocation": AdvData(42036, 'Overworld'), "Arbalistic": AdvData(42037, 'Overworld'), "The End... Again...": AdvData(42038, 'The End'), "Acquire Hardware": AdvData(42039, 'Overworld'), "Not Quite \"Nine\" Lives": AdvData(42040, 'The Nether'), "Cover Me With Diamonds": AdvData(42041, 'Overworld'), "Sky's the Limit": AdvData(42042, 'End City'), "Hired Help": AdvData(42043, 'Overworld'), "Return to Sender": AdvData(42044, 'The Nether'), "Sweet Dreams": AdvData(42045, 'Overworld'), "You Need a Mint": AdvData(42046, 'The End'), "Adventure": AdvData(42047, 'Overworld'), "Monsters Hunted": AdvData(42048, 'Overworld'), "Enchanter": AdvData(42049, 'Overworld'), "Voluntary Exile": AdvData(42050, 'Pillager Outpost'), "Eye Spy": AdvData(42051, 'Overworld'), "The End": AdvData(42052, 'The End'), "Serious Dedication": AdvData(42053, 'The Nether'), "Postmortal": AdvData(42054, 'Village'), "Monster Hunter": AdvData(42055, 'Overworld'), "Adventuring Time": AdvData(42056, 'Overworld'), "A Seedy Place": AdvData(42057, 'Overworld'), "Those Were the Days": AdvData(42058, 'Bastion Remnant'), "Hero of the Village": AdvData(42059, 'Village'), "Hidden in the Depths": AdvData(42060, 'The Nether'), "Beaconator": AdvData(42061, 'Nether Fortress'), "Withering Heights": AdvData(42062, 'Nether Fortress'), "A Balanced Diet": AdvData(42063, 'Village'), "Subspace Bubble": AdvData(42064, 'The Nether'), "Husbandry": AdvData(42065, 'Overworld'), "Country Lode, Take Me Home": AdvData(42066, 'The Nether'), "Bee Our Guest": AdvData(42067, 'Overworld'), "What a Deal!": AdvData(42068, 'Village'), "Uneasy Alliance": AdvData(42069, 'The Nether'), "Diamonds!": AdvData(42070, 'Overworld'), "A Terrible Fortress": AdvData(42071, 'Nether Fortress'), "A Throwaway Joke": AdvData(42072, 'Overworld'), "Minecraft": AdvData(42073, 'Overworld'), "Sticky Situation": AdvData(42074, 'Overworld'), "Ol' Betsy": AdvData(42075, 'Overworld'), "Cover Me in Debris": AdvData(42076, 'The Nether'), "The End?": AdvData(42077, 'The End'), "The Parrots and the Bats": AdvData(42078, 'Overworld'), "A Complete Catalogue": AdvData(42079, 'Village'), "Getting Wood": AdvData(42080, 'Overworld'), "Time to Mine!": AdvData(42081, 'Overworld'), "Hot Topic": AdvData(42082, 'Overworld'), "Bake Bread": AdvData(42083, 'Overworld'), "The Lie": AdvData(42084, 'Overworld'), "On a Rail": AdvData(42085, 'Overworld'), "Time to Strike!": AdvData(42086, 'Overworld'), "Cow Tipper": AdvData(42087, 'Overworld'), "When Pigs Fly": AdvData(42088, 'Overworld'), "Overkill": AdvData(42089, 'Nether Fortress'), "Librarian": AdvData(42090, 'Overworld'), "Overpowered": AdvData(42091, 'Overworld'), "Blaze Spawner": AdvData(None, 'Nether Fortress'), "Ender Dragon": AdvData(None, 'The End') } exclusion_table = { "hard": { "Very Very Frightening", "A Furious Cocktail", "Two by Two", "Two Birds, One Arrow", "Arbalistic", "Monsters Hunted", "Beaconator", "A Balanced Diet", "Uneasy Alliance", "Cover Me in Debris", "A Complete Catalogue", "Overpowered", }, "insane": { "How Did We Get Here?", "Adventuring Time", }, "postgame": { "Free the End", "The Next Generation", "The End... Again...", "You Need a Mint", "Monsters Hunted", } } events_table = { "Ender Dragon": "Victory" } lookup_id_to_name: typing.Dict[int, str] = {loc_data.id: loc_name for loc_name, loc_data in advancement_table.items() if loc_data.id} <file_sep>from typing import Dict, List, Set from BaseClasses import Item, MultiWorld, Location from ..AutoWorld import World from .LogicMixin import TimespinnerLogic from .Items import get_item_names_per_category, item_table, starter_melee_weapons, starter_spells, starter_progression_items, filler_items from .Locations import get_locations, starter_progression_locations, EventId from .Regions import create_regions from .Options import is_option_enabled, timespinner_options from .PyramidKeys import get_pyramid_keys_unlock class TimespinnerWorld(World): """ Timespinner is a beautiful metroidvania inspired by classic 90s action-platformers. Travel back in time to change fate itself. Join timekeeper Lunais on her quest for revenge against the empire that killed her family. """ options = timespinner_options game = "Timespinner" topology_present = True remote_items = False data_version = 3 item_name_to_id = {name: data.code for name, data in item_table.items()} location_name_to_id = {location.name: location.code for location in get_locations(None, None)} item_name_groups = get_item_names_per_category() locked_locations: Dict[int, List[str]] = {} pyramid_keys_unlock: Dict[int, str] = {} location_cache: Dict[int, List[Location]] = {} def generate_early(self): self.locked_locations[self.player] = [] self.location_cache[self.player] = [] self.pyramid_keys_unlock[self.player] = get_pyramid_keys_unlock(self.world, self.player) def create_regions(self): create_regions(self.world, self.player, get_locations(self.world, self.player), self.location_cache[self.player], self.pyramid_keys_unlock[self.player]) def create_item(self, name: str) -> Item: return create_item_with_correct_settings(self.world, self.player, name) def set_rules(self): setup_events(self.world, self.player, self.locked_locations[self.player], self.location_cache[self.player]) self.world.completion_condition[self.player] = lambda state: state.has('Killed Nightmare', self.player) def generate_basic(self): excluded_items = get_excluded_items_based_on_options(self.world, self.player) assign_starter_items(self.world, self.player, excluded_items, self.locked_locations[self.player]) if not is_option_enabled(self.world, self.player, "QuickSeed") and not is_option_enabled(self.world, self.player, "Inverted"): place_first_progression_item(self.world, self.player, excluded_items, self.locked_locations[self.player]) pool = get_item_pool(self.world, self.player, excluded_items) fill_item_pool_with_dummy_items(self.world, self.player, self.locked_locations[self.player], self.location_cache[self.player], pool) self.world.itempool += pool def fill_slot_data(self) -> Dict[str, object]: slot_data: Dict[str, object] = {} for option_name in timespinner_options: slot_data[option_name] = is_option_enabled(self.world, self.player, option_name) slot_data["StinkyMaw"] = True slot_data["ProgressiveVerticalMovement"] = False slot_data["ProgressiveKeycards"] = False slot_data["PyramidKeysGate"] = self.pyramid_keys_unlock[self.player] slot_data["PersonalItems"] = get_personal_items(self.player, self.location_cache[self.player]) return slot_data def get_excluded_items_based_on_options(world: MultiWorld, player: int) -> Set[str]: excluded_items: Set[str] = set() if is_option_enabled(world, player, "StartWithJewelryBox"): excluded_items.add('Jewelry Box') if is_option_enabled(world, player, "StartWithMeyef"): excluded_items.add('Meyef') if is_option_enabled(world, player, "QuickSeed"): excluded_items.add('Talaria Attachment') return excluded_items def assign_starter_items(world: MultiWorld, player: int, excluded_items: Set[str], locked_locations: List[str]): melee_weapon = world.random.choice(starter_melee_weapons) spell = world.random.choice(starter_spells) excluded_items.add(melee_weapon) excluded_items.add(spell) melee_weapon_item = create_item_with_correct_settings(world, player, melee_weapon) spell_item = create_item_with_correct_settings(world, player, spell) world.get_location('Yo Momma 1', player).place_locked_item(melee_weapon_item) world.get_location('Yo Momma 2', player).place_locked_item(spell_item) locked_locations.append('Yo Momma 1') locked_locations.append('Yo Momma 2') def get_item_pool(world: MultiWorld, player: int, excluded_items: Set[str]) -> List[Item]: pool: List[Item] = [] for name, data in item_table.items(): if not name in excluded_items: for _ in range(data.count): item = create_item_with_correct_settings(world, player, name) pool.append(item) return pool def fill_item_pool_with_dummy_items(world: MultiWorld, player: int, locked_locations: List[str], location_cache: List[Location], pool: List[Item]): for _ in range(len(location_cache) - len(locked_locations) - len(pool)): item = create_item_with_correct_settings(world, player, world.random.choice(filler_items)) pool.append(item) def place_first_progression_item(world: MultiWorld, player: int, excluded_items: Set[str], locked_locations: List[str]): progression_item = world.random.choice(starter_progression_items) location = world.random.choice(starter_progression_locations) excluded_items.add(progression_item) locked_locations.append(location) item = create_item_with_correct_settings(world, player, progression_item) world.get_location(location, player).place_locked_item(item) def create_item_with_correct_settings(world: MultiWorld, player: int, name: str) -> Item: data = item_table[name] item = Item(name, data.progression, data.code, player) item.never_exclude = data.never_exclude if not item.advancement: return item if (name == 'Tablet' or name == 'Library Keycard V') and not is_option_enabled(world, player, "DownloadableItems"): item.advancement = False if name == 'Oculus Ring' and not is_option_enabled(world, player, "FacebookMode"): item.advancement = False return item def setup_events(world: MultiWorld, player: int, locked_locations: List[str], location_cache: List[Location]): for location in location_cache: if location.address == EventId: item = Item(location.name, True, EventId, player) locked_locations.append(location.name) location.place_locked_item(item) def get_personal_items(player: int, locations: List[Location]) -> Dict[int, int]: personal_items: Dict[int, int] = {} for location in locations: if location.address and location.item and location.item.code and location.item.player == player: personal_items[location.address] = location.item.code return personal_items<file_sep># Archipelago General Client ## Archipelago Connection Handshake These steps should be followed in order to establish a gameplay connection with an Archipelago session. 1. Client establishes WebSocket connection to Archipelago server. 2. Server accepts connection and responds with a [RoomInfo](#RoomInfo) packet. 3. Client may send a [GetDataPackage](#GetDataPackage) packet. 4. Server sends a [DataPackage](#DataPackage) packet in return. (If the client sent GetDataPackage.) 5. Client sends [Connect](#Connect) packet in order to authenticate with the server. 6. Server validates the client's packet and responds with [Connected](#Connected) or [ConnectionRefused](#ConnectionRefused). 7. Server may send [ReceivedItems](#ReceivedItems) to the client, in the case that the client is missing items that are queued up for it. 8. Server sends [Print](#Print) to all players to notify them of the new client connection. In the case that the client does not authenticate properly and receives a [ConnectionRefused](#ConnectionRefused) then the server will maintain the connection and allow for follow-up [Connect](#Connect) packet. ## Synchronizing Items When the client receives a [ReceivedItems](#ReceivedItems) packet, if the `index` argument does not match the next index that the client expects then it is expected that the client will re-sync items with the server. This can be accomplished by sending the server a [Sync](#Sync) packet and then a [LocationChecks](#LocationChecks) packet. Even if the client detects a desync, it can still accept the items provided in this packet to prevent gameplay interruption. When the client receives a [ReceivedItems](#ReceivedItems) packet and the `index` arg is `0` (zero) then the client should accept the provided `items` list as its full inventory. (Abandon previous inventory.) # Archipelago Protocol Packets Packets are sent between the multiworld server and client in order to sync information between them. Below is a directory of each packet. Packets are simple JSON lists in which any number of ordered network commands can be sent, which are objects. Each command has a "cmd" key, indicating its purpose. All packet argument types documented here refer to JSON types, unless otherwise specified. An object can contain the "class" key, which will tell the content data type, such as "Version" in the following example. Example: ```javascript [{"cmd": "RoomInfo", "version": {"major": 0, "minor": 1, "build": 3, "class": "Version"}, "tags": ["WebHost"], ... }] ``` ## (Server -> Client) These packets are are sent from the multiworld server to the client. They are not messages which the server accepts. * [RoomInfo](#RoomInfo) * [ConnectionRefused](#ConnectionRefused) * [Connected](#Connected) * [ReceivedItems](#ReceivedItems) * [LocationInfo](#LocationInfo) * [RoomUpdate](#RoomUpdate) * [Print](#Print) * [PrintJSON](#PrintJSON) * [DataPackage](#DataPackage) * [Bounced](#Bounced) ### RoomInfo Sent to clients when they connect to an Archipelago server. #### Arguments | Name | Type | Notes | | ---- | ---- | ----- | | version | NetworkVersion | Object denoting the version of Archipelago which the server is running. See [NetworkVersion](#NetworkVersion) for more details. | | tags | list\[str\] | Denotes special features or capabilities that the sender is capable of. Example: `WebHost` | | password | bool | Denoted whether a password is required to join this room.| | permissions | dict\[str, Permission\[int\]\] | Mapping of permission name to [Permission](#Permission), keys are: "forfeit", "collect" and "remaining". | | hint_cost | int | The amount of points it costs to receive a hint from the server. | | location_check_points | int | The amount of hint points you receive per item/location check completed. || | players | list\[NetworkPlayer\] | Sent only if the client is properly authenticated (see [Archipelago Connection Handshake](#Archipelago-Connection-Handshake)). Information on the players currently connected to the server. See [NetworkPlayer](#NetworkPlayer) for more details. | | games | list\[str\] | sorted list of game names for the players, so first player's game will be games\[0\]. Matches game names in datapackage. | | datapackage_version | int | Data version of the [data package](#Data-Package-Contents) the server will send. Used to update the client's (optional) local cache. | | datapackage_versions | dict\[str, int\] | Data versions of the individual games' data packages the server will send. | | seed_name | str | uniquely identifying name of this generation | #### forfeit Dictates what is allowed when it comes to a player forfeiting their run. A forfeit is an action which distributes the rest of the items in a player's run to those other players awaiting them. * `auto`: Distributes a player's items to other players when they complete their goal. * `enabled`: Denotes that players may forfeit at any time in the game. * `auto-enabled`: Both of the above options together. * `disabled`: All forfeit modes disabled. * `goal`: Allows for manual use of forfeit command once a player completes their goal. (Disabled until goal completion) #### collect Dictates what is allowed when it comes to a player collecting their run. A collect is an action which sends the rest of the items in a player's run. * `auto`: Automatically when they complete their goal. * `enabled`: Denotes that players may !collect at any time in the game. * `auto-enabled`: Both of the above options together. * `disabled`: All collect modes disabled. * `goal`: Allows for manual use of collect command once a player completes their goal. (Disabled until goal completion) #### remaining Dictates what is allowed when it comes to a player querying the items remaining in their run. * `goal`: Allows a player to query for items remaining in their run but only after they completed their own goal. * `enabled`: Denotes that players may query for any items remaining in their run (even those belonging to other players). * `disabled`: All remaining item query modes disabled. ### ConnectionRefused Sent to clients when the server refuses connection. This is sent during the initial connection handshake. #### Arguments | Name | Type | Notes | | ---- | ---- | ----- | | errors | list\[str\] | Optional. When provided, should contain any one of: `InvalidSlot`, `InvalidGame`, `SlotAlreadyTaken`, `IncompatibleVersion`, or `InvalidPassword`. | InvalidSlot indicates that the sent 'name' field did not match any auth entry on the server. InvalidGame indicates that a correctly named slot was found, but the game for it mismatched. SlotAlreadyTaken indicates a connection with a different uuid is already established. IncompatibleVersion indicates a version mismatch. InvalidPassword indicates the wrong, or no password when it was required, was sent. ### Connected Sent to clients when the connection handshake is successfully completed. #### Arguments | Name | Type | Notes | | ---- | ---- | ----- | | team | int | Your team number. See [NetworkPlayer](#NetworkPlayer) for more info on team number. | | slot | int | Your slot number on your team. See [NetworkPlayer](#NetworkPlayer) for more info on the slot number. | | players | list\[NetworkPlayer\] | List denoting other players in the multiworld, whether connected or not. See [NetworkPlayer](#NetworkPlayer) for info on the format. | | missing_locations | list\[int\] | Contains ids of remaining locations that need to be checked. Useful for trackers, among other things. | | checked_locations | list\[int\] | Contains ids of all locations that have been checked. Useful for trackers, among other things. | | slot_data | dict | Contains a json object for slot related data, differs per game. Empty if not required. | ### ReceivedItems Sent to clients when they receive an item. #### Arguments | Name | Type | Notes | | ---- | ---- | ----- | | index | int | The next empty slot in the list of items for the receiving client. | | items | list\[NetworkItem\] | The items which the client is receiving. See [NetworkItem](#NetworkItem) for more details. | ### LocationInfo Sent to clients to acknowledge a received [LocationScouts](#LocationScouts) packet and responds with the item in the location(s) being scouted. #### Arguments | Name | Type | Notes | | ---- | ---- | ----- | | locations | list\[NetworkItem\] | Contains list of item(s) in the location(s) scouted. See [NetworkItem](#NetworkItem) for more details. | ### RoomUpdate Sent when there is a need to update information about the present game session. Generally useful for async games. Once authenticated (received Connected), this may also contain data from Connected. #### Arguments The arguments for RoomUpdate are identical to [RoomInfo](#RoomInfo) barring: | Name | Type | Notes | | ---- | ---- | ----- | | hint_points | int | New argument. The client's current hint points. | | players | list\[NetworkPlayer\] | Changed argument. Always sends all players, whether connected or not. | | checked_locations | May be a partial update, containing new locations that were checked. | | missing_locations | Should never be sent as an update, if needed is the inverse of checked_locations. | All arguments for this packet are optional, only changes are sent. ### Print Sent to clients purely to display a message to the player. #### Arguments | Name | Type | Notes | | ---- | ---- | ----- | | text | str | Message to display to player. | ### PrintJSON Sent to clients purely to display a message to the player. This packet differs from [Print](#Print) in that the data being sent with this packet allows for more configurable or specific messaging. #### Arguments | Name | Type | Notes | | ---- | ---- | ----- | | data | list\[JSONMessagePart\] | See [JSONMessagePart](#JSONMessagePart) for more details on this type. | | type | str | May be present to indicate the nature of this message. Known types are Hint and ItemSend. | receiving | int | Is present if type is Hint or ItemSend and marks the destination player's ID. | item | NetworkItem | Is present if type is Hint or ItemSend and marks the source player id, location id and item id. ### DataPackage Sent to clients to provide what is known as a 'data package' which contains information to enable a client to most easily communicate with the Archipelago server. Contents include things like location id to name mappings, among others; see [Data Package Contents](#Data-Package-Contents) for more info. #### Arguments | Name | Type | Notes | | ---- | ---- | ----- | | data | DataPackageObject | The data package as a JSON object. More details on its contents may be found at [Data Package Contents](#Data-Package-Contents) | ### Bounced Sent to clients after a client requested this message be sent to them, more info in the Bounce package. #### Arguments | Name | Type | Notes | | ---- | ---- | ----- | | data | dict | The data in the Bounce package copied | ## (Client -> Server) These packets are sent purely from client to server. They are not accepted by clients. * [Connect](#Connect) * [Sync](#Sync) * [LocationChecks](#LocationChecks) * [LocationScouts](#LocationScouts) * [StatusUpdate](#StatusUpdate) * [Say](#Say) * [GetDataPackage](#GetDataPackage) * [Bounce](#Bounce) ### Connect Sent by the client to initiate a connection to an Archipelago game session. #### Arguments | Name | Type | Notes | | ---- | ---- | ----- | | password | str | If the game session requires a password, it should be passed here. | | game | str | The name of the game the client is playing. Example: `A Link to the Past` | | name | str | The player name for this client. | | uuid | str | Unique identifier for player client. | | version | NetworkVersion | An object representing the Archipelago version this client supports. | | tags | list\[str\] | Denotes special features or capabilities that the sender is capable of. | #### Authentication Many, if not all, other packets require a successfully authenticated client. This is described in more detail in [Archipelago Connection Handshake](#Archipelago-Connection-Handshake). ### Sync Sent to server to request a [ReceivedItems](#ReceivedItems) packet to synchronize items. #### Arguments No arguments necessary. ### LocationChecks Sent to server to inform it of locations that the client has checked. Used to inform the server of new checks that are made, as well as to sync state. #### Arguments | Name | Type | Notes | | ---- | ---- | ----- | | locations | list\[int\] | The ids of the locations checked by the client. May contain any number of checks, even ones sent before; duplicates do not cause issues with the Archipelago server. | ### LocationScouts Sent to the server to inform it of locations the client has seen, but not checked. Useful in cases in which the item may appear in the game world, such as 'ledge items' in A Link to the Past. The server will always respond with a [LocationInfo](#LocationInfo) packet with the items located in the scouted location. #### Arguments | Name | Type | Notes | | ---- | ---- | ----- | | locations | list\[int\] | The ids of the locations seen by the client. May contain any number of locations, even ones sent before; duplicates do not cause issues with the Archipelago server. | ### StatusUpdate Sent to the server to update on the sender's status. Examples include readiness or goal completion. (Example: defeated Ganon in A Link to the Past) #### Arguments | Name | Type | Notes | | ---- | ---- | ----- | | status | ClientStatus\[int\] | One of [Client States](#Client-States). Send as int. Follow the link for more information. | ### Say Basic chat command which sends text to the server to be distributed to other clients. #### Arguments | Name | Type | Notes | | ------ | ----- | ------ | | text | str | Text to send to others. | ### GetDataPackage Requests the data package from the server. Does not require client authentication. #### Arguments | Name | Type | Notes | | ------ | ----- | ------ | | exclusions | list\[str\] | Optional. If specified, will not send back the specified data. Such as, \["Factorio"\] -> Datapackage without Factorio data.| ### Bounce Send this message to the server, tell it which clients should receive the message and the server will forward the message to all those targets to which any one requirement applies. #### Arguments | Name | Type | Notes | | ------ | ----- | ------ | | games | list\[str\] | Optional. Game names that should receive this message | | slots | list\[int\] | Optional. Player IDs that should receive this message | | tags | list\[str\] | Optional. Client tags that should receive this message | | data | dict | Any data you want to send | ## Appendix ### Coop Coop in Archipelago is automatically facilitated by the server, however some of the default behaviour may not be what you desire. If the game in question is a remote-items game (attribute on AutoWorld), then all items will always be sent and received. If the game in question is not a remote-items game, then any items that are placed within the same world will not be send by the server. To manually react to others in the same player slot doing checks, listen to [RoomUpdate](#RoomUpdate) -> checked_locations. ### NetworkPlayer A list of objects. Each object denotes one player. Each object has four fields about the player, in this order: `team`, `slot`, `alias`, and `name`. `team` and `slot` are ints, `alias` and `name` are strs. Each player belongs to a `team` and has a `slot`. Team numbers start at `0`. Slot numbers are unique per team and start at `1`. Slot number `0` refers to the Archipelago server; this may appear in instances where the server grants the player an item. `alias` represents the player's name in current time. `name` is the original name used when the session was generated. This is typically distinct in games which require baking names into ROMs or for async games. ```python from typing import NamedTuple class NetworkPlayer(NamedTuple): team: int slot: int alias: str name: str ``` Example: ```js [ {"team": 0, "slot": 1, "alias": "Lord MeowsiePuss", "name": "Meow"}, {"team": 0, "slot": 2, "alias": "Doggo", "name": "Bork"}, {"team": 1, "slot": 1, "alias": "Angry Duck", "name": "<NAME>"}, {"team": 1, "slot": 2, "alias": "Mountain Duck", "name": "Honk"} ] ``` ### NetworkItem Items that are sent over the net (in packets) use the following data structure and are sent as objects: ```python from typing import NamedTuple class NetworkItem(NamedTuple): item: int location: int player: int ``` In JSON this may look like: ```js [ {"item": 1, "location": 1, "player": 0}, {"item": 2, "location": 2, "player": 0}, {"item": 3, "location": 3, "player": 0} ] ``` ### JSONMessagePart Message nodes sent along with [PrintJSON](#PrintJSON) packet to be reconstructed into a legible message. The nodes are intended to be read in the order they are listed in the packet. ```python from typing import TypedDict, Optional class JSONMessagePart(TypedDict): type: Optional[str] color: Optional[str] text: Optional[str] ``` `type` is used to denote the intent of the message part. This can be used to indicate special information which may be rendered differently depending on client. How these types are displayed in Archipelago's ALttP client is not the end-all be-all. Other clients may choose to interpret and display these messages differently. Possible values for `type` include: * player_id * item_id * location_id `color` is used to denote a console color to display the message part with. This is limited to console colors due to backwards compatibility needs with games such as ALttP. Although background colors as well as foreground colors are listed, only one may be applied to a [JSONMessagePart](#JSONMessagePart) at a time. Color options: * bold * underline * black * red * green * yellow * blue * magenta * cyan * white * black_bg * red_bg * green_bg * yellow_bg * blue_bg * purple_bg * cyan_bg * white_bg `text` is the content of the message part to be displayed. ### Client States An enumeration containing the possible client states that may be used to inform the server in [StatusUpdate](#StatusUpdate). ```python import enum class ClientStatus(enum.IntEnum): CLIENT_UNKNOWN = 0 CLIENT_READY = 10 CLIENT_PLAYING = 20 CLIENT_GOAL = 30 ``` ### NetworkVersion An object representing software versioning. Used in the [Connect](#Connect) packet to allow the client to inform the server of the Archipelago version it supports. ```python from typing import NamedTuple class Version(NamedTuple): major: int minor: int build: int ``` ### Permission An enumeration containing the possible command permission, for commands that may be restricted. ```python import enum class Permission(enum.IntEnum): disabled = 0b000 # 0, completely disables access enabled = 0b001 # 1, allows manual use goal = 0b010 # 2, allows manual use after goal completion auto = 0b110 # 6, forces use after goal completion, only works for forfeit and collect auto_enabled = 0b111 # 7, forces use after goal completion, allows manual use any time ``` ### Data Package Contents A data package is a JSON object which may contain arbitrary metadata to enable a client to interact with the Archipelago server most easily. Currently, this package is used to send ID to name mappings so that clients need not maintain their own mappings. We encourage clients to cache the data package they receive on disk, or otherwise not tied to a session. You will know when your cache is outdated if the [RoomInfo](#RoomInfo) packet or the datapackage itself denote a different version. A special case is datapackage version 0, where it is expected the package is custom and should not be cached. Note: * Any ID is unique to its type across AP: Item 56 only exists once and Location 56 only exists once. * Any Name is unique to its type across its own Game only: Single Arrow can exist in two games. #### Contents | Name | Type | Notes | | ------ | ----- | ------ | | games | dict[str, GameData] | Mapping of all Games and their respective data | | version | int | Sum of all per-game version numbers, for clients that don't bother with per-game caching/updating. | #### GameData GameData is a **dict** but contains these keys and values. It's broken out into another "type" for ease of documentation. | Name | Type | Notes | | ---- | ---- | ----- | | item_name_to_id | dict[str, int] | Mapping of all item names to their respective ID. | | location_name_to_id | dict[str, int] | Mapping of all location names to their respective ID. | | version | int | Version number of this game's data | <file_sep>import random import logging import os import threading import typing from BaseClasses import Item, CollectionState from .SubClasses import ALttPItem from ..AutoWorld import World, LogicMixin from .Options import alttp_options, smallkey_shuffle from .Items import as_dict_item_table, item_name_groups, item_table from .Regions import lookup_name_to_id, create_regions, mark_light_world_regions from .Rules import set_rules from .ItemPool import generate_itempool, difficulties from .Shops import create_shops, ShopSlotFill from .Dungeons import create_dungeons from .Rom import LocalRom, patch_rom, patch_race_rom, patch_enemizer, apply_rom_settings, get_hash_string, \ get_base_rom_path import Patch from .InvertedRegions import create_inverted_regions, mark_dark_world_regions from .EntranceShuffle import link_entrances, link_inverted_entrances, plando_connect lttp_logger = logging.getLogger("A Link to the Past") class ALTTPWorld(World): """ The Legend of Zelda: A Link to the Past is an action/adventure game. Take on the role of Link, a boy who is destined to save the land of Hyrule. Delve through three palaces and nine dungeons on your quest to rescue the descendents of the seven wise men and defeat the evil Ganon! """ game: str = "A Link to the Past" options = alttp_options topology_present = True item_name_groups = item_name_groups hint_blacklist = {"Triforce"} item_name_to_id = {name: data.item_code for name, data in item_table.items() if type(data.item_code) == int} location_name_to_id = lookup_name_to_id data_version = 8 remote_items: bool = False remote_start_inventory: bool = False set_rules = set_rules create_items = generate_itempool def __init__(self, *args, **kwargs): self.dungeon_local_item_names = set() self.dungeon_specific_item_names = set() self.rom_name_available_event = threading.Event() self.has_progressive_bows = False super(ALTTPWorld, self).__init__(*args, **kwargs) def generate_early(self): player = self.player world = self.world # system for sharing ER layouts self.er_seed = str(world.random.randint(0, 2 ** 64)) if "-" in world.shuffle[player]: shuffle, seed = world.shuffle[player].split("-", 1) world.shuffle[player] = shuffle if shuffle == "vanilla": self.er_seed = "vanilla" elif seed.startswith("group-") or world.is_race: self.er_seed = get_same_seed(world, ( shuffle, seed, world.retro[player], world.mode[player], world.logic[player])) else: # not a race or group seed, use set seed as is. self.er_seed = seed elif world.shuffle[player] == "vanilla": self.er_seed = "vanilla" for dungeon_item in ["smallkey_shuffle", "bigkey_shuffle", "compass_shuffle", "map_shuffle"]: option = getattr(world, dungeon_item)[player] if option == "own_world": world.local_items[player].value |= self.item_name_groups[option.item_name_group] elif option == "different_world": world.non_local_items[player].value |= self.item_name_groups[option.item_name_group] elif option.in_dungeon: self.dungeon_local_item_names |= self.item_name_groups[option.item_name_group] if option == "original_dungeon": self.dungeon_specific_item_names |= self.item_name_groups[option.item_name_group] world.difficulty_requirements[player] = difficulties[world.difficulty[player]] def create_regions(self): player = self.player world = self.world if world.open_pyramid[player] == 'goal': world.open_pyramid[player] = world.goal[player] in {'crystals', 'ganontriforcehunt', 'localganontriforcehunt', 'ganonpedestal'} elif world.open_pyramid[player] == 'auto': world.open_pyramid[player] = world.goal[player] in {'crystals', 'ganontriforcehunt', 'localganontriforcehunt', 'ganonpedestal'} and \ (world.shuffle[player] in {'vanilla', 'dungeonssimple', 'dungeonsfull', 'dungeonscrossed'} or not world.shuffle_ganon) else: world.open_pyramid[player] = {'on': True, 'off': False, 'yes': True, 'no': False}.get( world.open_pyramid[player], 'auto') world.triforce_pieces_available[player] = max(world.triforce_pieces_available[player], world.triforce_pieces_required[player]) if world.mode[player] != 'inverted': create_regions(world, player) else: create_inverted_regions(world, player) create_shops(world, player) create_dungeons(world, player) if world.logic[player] not in ["noglitches", "minorglitches"] and world.shuffle[player] in \ {"vanilla", "dungeonssimple", "dungeonsfull", "simple", "restricted", "full"}: world.fix_fake_world[player] = False # seeded entrance shuffle old_random = world.random world.random = random.Random(self.er_seed) if world.mode[player] != 'inverted': link_entrances(world, player) mark_light_world_regions(world, player) else: link_inverted_entrances(world, player) mark_dark_world_regions(world, player) world.random = old_random plando_connect(world, player) def collect_item(self, state: CollectionState, item: Item, remove=False): item_name = item.name if item_name.startswith('Progressive '): if remove: if 'Sword' in item_name: if state.has('Golden Sword', item.player): return 'Golden Sword' elif state.has('Tempered Sword', item.player): return 'Tempered Sword' elif state.has('Master Sword', item.player): return 'Master Sword' elif state.has('Fighter Sword', item.player): return 'Fighter Sword' else: return None elif 'Glove' in item.name: if state.has('Titans Mitts', item.player): return 'Titans Mitts' elif state.has('Power Glove', item.player): return 'Power Glove' else: return None elif 'Shield' in item_name: if state.has('Mirror Shield', item.player): return 'Mirror Shield' elif state.has('Red Shield', item.player): return 'Red Shield' elif state.has('Blue Shield', item.player): return 'Blue Shield' else: return None elif 'Bow' in item_name: if state.has('Silver Bow', item.player): return 'Silver Bow' elif state.has('Bow', item.player): return 'Bow' else: return None else: if 'Sword' in item_name: if state.has('Golden Sword', item.player): pass elif state.has('Tempered Sword', item.player) and self.world.difficulty_requirements[ item.player].progressive_sword_limit >= 4: return 'Golden Sword' elif state.has('Master Sword', item.player) and self.world.difficulty_requirements[ item.player].progressive_sword_limit >= 3: return 'Tempered Sword' elif state.has('Fighter Sword', item.player) and self.world.difficulty_requirements[item.player].progressive_sword_limit >= 2: return 'Master Sword' elif self.world.difficulty_requirements[item.player].progressive_sword_limit >= 1: return 'Fighter Sword' elif 'Glove' in item_name: if state.has('Titans Mitts', item.player): return elif state.has('Power Glove', item.player): return 'Titans Mitts' else: return 'Power Glove' elif 'Shield' in item_name: if state.has('Mirror Shield', item.player): return elif state.has('Red Shield', item.player) and self.world.difficulty_requirements[item.player].progressive_shield_limit >= 3: return 'Mirror Shield' elif state.has('Blue Shield', item.player) and self.world.difficulty_requirements[item.player].progressive_shield_limit >= 2: return 'Red Shield' elif self.world.difficulty_requirements[item.player].progressive_shield_limit >= 1: return 'Blue Shield' elif 'Bow' in item_name: if state.has('Silver Bow', item.player): return elif state.has('Bow', item.player) and (self.world.difficulty_requirements[item.player].progressive_bow_limit >= 2 or self.world.logic[item.player] == 'noglitches' or self.world.swordless[item.player]): # modes where silver bow is always required for ganon return 'Silver Bow' elif self.world.difficulty_requirements[item.player].progressive_bow_limit >= 1: return 'Bow' elif item.advancement: return item_name def pre_fill(self): from Fill import fill_restrictive, FillError attempts = 5 world = self.world player = self.player all_state = world.get_all_state(use_cache=True) crystals = [self.create_item(name) for name in ['Red Pendant', 'Blue Pendant', 'Green Pendant', 'Crystal 1', 'Crystal 2', 'Crystal 3', 'Crystal 4', 'Crystal 7', 'Crystal 5', 'Crystal 6']] crystal_locations = [world.get_location('Turtle Rock - Prize', player), world.get_location('Eastern Palace - Prize', player), world.get_location('Desert Palace - Prize', player), world.get_location('Tower of Hera - Prize', player), world.get_location('Palace of Darkness - Prize', player), world.get_location('Thieves\' Town - Prize', player), world.get_location('Skull Woods - Prize', player), world.get_location('Swamp Palace - Prize', player), world.get_location('Ice Palace - Prize', player), world.get_location('Misery Mire - Prize', player)] placed_prizes = {loc.item.name for loc in crystal_locations if loc.item} unplaced_prizes = [crystal for crystal in crystals if crystal.name not in placed_prizes] empty_crystal_locations = [loc for loc in crystal_locations if not loc.item] for attempt in range(attempts): try: prizepool = unplaced_prizes.copy() prize_locs = empty_crystal_locations.copy() world.random.shuffle(prize_locs) fill_restrictive(world, all_state, prize_locs, prizepool, True, lock=True) except FillError as e: lttp_logger.exception("Failed to place dungeon prizes (%s). Will retry %s more times", e, attempts - attempt) for location in empty_crystal_locations: location.item = None continue break else: raise FillError('Unable to place dungeon prizes') @classmethod def stage_pre_fill(cls, world): from .Dungeons import fill_dungeons_restrictive fill_dungeons_restrictive(cls, world) @classmethod def stage_post_fill(cls, world): ShopSlotFill(world) def generate_output(self, output_directory: str): world = self.world player = self.player try: use_enemizer = (world.boss_shuffle[player] != 'none' or world.enemy_shuffle[player] or world.enemy_health[player] != 'default' or world.enemy_damage[player] != 'default' or world.pot_shuffle[player] or world.bush_shuffle[player] or world.killable_thieves[player]) rom = LocalRom(get_base_rom_path()) patch_rom(world, rom, player, use_enemizer) if use_enemizer: patch_enemizer(world, player, rom, world.enemizer, output_directory) if world.is_race: patch_race_rom(rom, world, player) world.spoiler.hashes[player] = get_hash_string(rom.hash) palettes_options = { 'dungeon': world.uw_palettes[player], 'overworld': world.ow_palettes[player], 'hud': world.hud_palettes[player], 'sword': world.sword_palettes[player], 'shield': world.shield_palettes[player], 'link': world.link_palettes[player] } palettes_options = {key: option.current_key for key, option in palettes_options.items()} apply_rom_settings(rom, world.heartbeep[player].current_key, world.heartcolor[player].current_key, world.quickswap[player], world.menuspeed[player].current_key, world.music[player], world.sprite[player], palettes_options, world, player, True, reduceflashing=world.reduceflashing[player] or world.is_race, triforcehud=world.triforcehud[player].current_key) outfilepname = f'_P{player}' outfilepname += f"_{world.player_name[player].replace(' ', '_')}" \ if world.player_name[player] != 'Player%d' % player else '' rompath = os.path.join(output_directory, f'AP_{world.seed_name}{outfilepname}.sfc') rom.write_to_file(rompath) Patch.create_patch_file(rompath, player=player, player_name=world.player_name[player]) os.unlink(rompath) self.rom_name = rom.name except: raise finally: self.rom_name_available_event.set() # make sure threading continues and errors are collected def modify_multidata(self, multidata: dict): import base64 # wait for self.rom_name to be available. self.rom_name_available_event.wait() rom_name = getattr(self, "rom_name", None) # we skip in case of error, so that the original error in the output thread is the one that gets raised if rom_name: new_name = base64.b64encode(bytes(self.rom_name)).decode() payload = multidata["connect_names"][self.world.player_name[self.player]] multidata["connect_names"][new_name] = payload del (multidata["connect_names"][self.world.player_name[self.player]]) def get_required_client_version(self) -> tuple: return max((0, 1, 4), super(ALTTPWorld, self).get_required_client_version()) def create_item(self, name: str) -> Item: return ALttPItem(name, self.player, **as_dict_item_table[name]) @classmethod def stage_fill_hook(cls, world, progitempool, nonexcludeditempool, localrestitempool, nonlocalrestitempool, restitempool, fill_locations): trash_counts = {} standard_keyshuffle_players = set() for player in world.get_game_players("A Link to the Past"): if world.mode[player] == 'standard' and world.smallkey_shuffle[player] \ and world.smallkey_shuffle[player] != smallkey_shuffle.option_universal: standard_keyshuffle_players.add(player) if not world.ganonstower_vanilla[player] or \ world.logic[player] in {'owglitches', 'hybridglitches', "nologic"}: pass elif 'triforcehunt' in world.goal[player] and ('local' in world.goal[player] or world.players == 1): trash_counts[player] = world.random.randint(world.crystals_needed_for_gt[player] * 2, world.crystals_needed_for_gt[player] * 4) else: trash_counts[player] = world.random.randint(0, world.crystals_needed_for_gt[player] * 2) # Make sure the escape small key is placed first in standard with key shuffle to prevent running out of spots # TODO: this might be worthwhile to introduce as generic option for various games and then optimize it if standard_keyshuffle_players: viable = [] for location in world.get_locations(): if location.player in standard_keyshuffle_players \ and location.item is None \ and location.can_reach(world.state): viable.append(location) world.random.shuffle(viable) for player in standard_keyshuffle_players: key = world.create_item("Small Key (Hyrule Castle)", player) loc = viable.pop() loc.place_locked_item(key) fill_locations.remove(loc) world.random.shuffle(fill_locations) # TODO: investigate not creating the key in the first place progitempool[:] = [item for item in progitempool if item.player not in standard_keyshuffle_players or item.name != "Small Key (Hyrule Castle)"] if trash_counts: locations_mapping = {player: [] for player in trash_counts} for location in fill_locations: if 'Ganons Tower' in location.name and location.player in locations_mapping: locations_mapping[location.player].append(location) for player, trash_count in trash_counts.items(): gtower_locations = locations_mapping[player] world.random.shuffle(gtower_locations) localrest = localrestitempool[player] if localrest: gt_item_pool = restitempool + localrest world.random.shuffle(gt_item_pool) else: gt_item_pool = restitempool.copy() while gtower_locations and gt_item_pool and trash_count > 0: spot_to_fill = gtower_locations.pop() item_to_place = gt_item_pool.pop() if item_to_place in localrest: localrest.remove(item_to_place) else: restitempool.remove(item_to_place) world.push_item(spot_to_fill, item_to_place, False) fill_locations.remove(spot_to_fill) # very slow, unfortunately trash_count -= 1 def get_same_seed(world, seed_def: tuple) -> str: seeds: typing.Dict[tuple, str] = getattr(world, "__named_seeds", {}) if seed_def in seeds: return seeds[seed_def] seeds[seed_def] = str(world.random.randint(0, 2 ** 64)) world.__named_seeds = seeds return seeds[seed_def] class ALttPLogic(LogicMixin): def _lttp_has_key(self, item, player, count: int = 1): if self.world.logic[player] == 'nologic': return True if self.world.smallkey_shuffle[player] == smallkey_shuffle.option_universal: return self.can_buy_unlimited('Small Key (Universal)', player) return self.prog_items[item, player] >= count <file_sep>import unittest from BaseClasses import CollectionState from worlds.AutoWorld import AutoWorldRegister from . import setup_default_world class TestBase(unittest.TestCase): _state_cache = {} gen_steps = ["generate_early", "create_regions", "create_items", "set_rules", "generate_basic", "pre_fill"] def testAllStateCanReachEverything(self): for game_name, world_type in AutoWorldRegister.world_types.items(): if game_name != "Ori and the Blind Forest": # TODO: fix Ori Logic with self.subTest("Game", game=game_name): world = setup_default_world(world_type) state = world.get_all_state(False) for location in world.get_locations(): with self.subTest("Location should be reached", location=location): self.assertTrue(location.can_reach(state)) def testEmptyStateCanReachSomething(self): for game_name, world_type in AutoWorldRegister.world_types.items(): if game_name != "Archipelago": with self.subTest("Game", game=game_name): world = setup_default_world(world_type) state = CollectionState(world) locations = set() for location in world.get_locations(): if location.can_reach(state): locations.add(location) self.assertGreater(len(locations), 0, msg="Need to be able to reach at least one location to get started.")<file_sep>flask>=2.0.2 pony>=0.7.14 waitress>=2.0.0 flask-caching>=1.10.1 Flask-Compress>=1.10.1 Flask-Limiter>=1.4 <file_sep>from argparse import Namespace from BaseClasses import MultiWorld from worlds.AutoWorld import call_all gen_steps = ["generate_early", "create_regions", "create_items", "set_rules", "generate_basic", "pre_fill"] def setup_default_world(world_type): world = MultiWorld(1) world.game[1] = world_type.game world.player_name = {1: "Tester"} world.set_seed() args = Namespace() for name, option in world_type.options.items(): setattr(args, name, {1: option.from_any(option.default)}) world.set_options(args) world.set_default_common_options() for step in gen_steps: call_all(world, step) return world<file_sep>from typing import Set from ..AutoWorld import World, LogicMixin from .Items import item_table, default_pool from .Locations import lookup_name_to_id from .Rules import set_rules, location_rules from .Regions import locations_by_region, connectors from .Options import options from BaseClasses import Region, Item, Location, RegionType, Entrance class OriBlindForest(World): game: str = "Ori and the Blind Forest" topology_present = True item_name_to_id = item_table location_name_to_id = lookup_name_to_id options = options hidden = True def generate_early(self): logic_sets = {"casual-core"} for logic_set in location_rules: if logic_set != "casual-core" and getattr(self.world, logic_set.replace("-", "_")): logic_sets.add(logic_set) self.logic_sets = logic_sets set_rules = set_rules def create_region(self, name: str): return Region(name, RegionType.Generic, name, self.player, self.world) def create_regions(self): world = self.world menu = self.create_region("Menu") world.regions.append(menu) start = Entrance(self.player, "Start Game", menu) menu.exits.append(start) # workaround for now, remove duplicate locations already_placed_locations = set() for region_name, locations in locations_by_region.items(): locations -= already_placed_locations already_placed_locations |= locations region = self.create_region(region_name) if region_name == "SunkenGladesRunaway": # starting point start.connect(region) region.locations = {Location(self.player, location, lookup_name_to_id[location], region) for location in locations} world.regions.append(region) for region_name, exits in connectors.items(): parent = world.get_region(region_name, self.player) for exit in exits: connection = Entrance(self.player, exit, parent) connection.connect(world.get_region(exit, self.player)) parent.exits.append(connection) def generate_basic(self): for item_name, count in default_pool.items(): self.world.itempool.extend([self.create_item(item_name)] * count) def create_item(self, name: str) -> Item: return Item(name, not name.startswith("EX"), item_table[name], self.player) class OriBlindForestLogic(LogicMixin): def _oribf_has_all(self, items: Set[str], player:int): return all(self.prog_items[item, player] if type(item) == str else self.prog_items[item[0], player] >= item[1] for item in items)<file_sep># [Archipelago](https://archipelago.gg) ![Discord Shield](https://discordapp.com/api/guilds/731205301247803413/widget.png?style=shield) | [Install](https://github.com/ArchipelagoMW/Archipelago/releases) Archipelago provides a generic framework for developing multiworld capability for game randomizers. In all cases, presently, Archipelago is also the randomizer itself. Currently, the following games are supported: * The Legend of Zelda: A Link to the Past * Factorio * Minecraft * Subnautica * Slay the Spire * Risk of Rain 2 * The Legend of Zelda: Ocarina of Time * Timespinner For setup and instructions check out our [tutorials page](https://archipelago.gg/tutorial/). Downloads can be found at [Releases](https://github.com/ArchipelagoMW/Archipelago/releases), including compiled windows binaries. ## History Archipelago is built upon a strong legacy of brilliant hobbyists. We want to honor that legacy by showing it here. The repositories which Archipelago is built upon, inspired by, or otherwise owes its gratitude to are: * [bonta0's MultiWorld](https://github.com/Bonta0/ALttPEntranceRandomizer/tree/multiworld_31) * [AmazingAmpharos' Entrance Randomizer](https://github.com/AmazingAmpharos/ALttPEntranceRandomizer) * [VT Web Randomizer](https://github.com/sporchia/alttp_vt_randomizer) * [Dessyreqt's alttprandomizer](https://github.com/Dessyreqt/alttprandomizer) * [Zarby89's](https://github.com/Ijwu/Enemizer/commits?author=Zarby89) and [sosuke3's](https://github.com/Ijwu/Enemizer/commits?author=sosuke3) contributions to Enemizer, which make the vast majority of Enemizer contributions. We recognize that there is a strong community of incredibly smart people that have come before us and helped pave the path. Just because one person's name may be in a repository title does not mean that only one person made that project happen. We can't hope to perfectly cover every single contribution that lead up to Archipelago but we hope to honor them fairly. ### Path to the Archipelago Archipelago was directly forked from bonta0's `multiworld_31` branch of ALttPEntranceRandomizer (this project has a long legacy of its own, please check it out linked above) on January 12, 2020. The repository was then named to _MultiWorld-Utilities_ to better encompass its intended function. As Archipelago matured, then known as "Berserker's MultiWorld" by some, we found it necessary to transform our repository into a root level repository (as opposed to a 'forked repo') and change the name (which came later) to better reflect our project. ## Running Archipelago For most people all you need to do is head over to the [releases](https://github.com/ArchipelagoMW/Archipelago/releases) page then download and run the appropriate installer. The installers function on Windows only. If you are running Archipelago from a non-Windows system then the likely scenario is that you are comfortable running source code directly. Please see our wiki page on [running Archipelago from source](https://github.com/Berserker66/MultiWorld-Utilities/wiki/Running-from-source). ## Related Repositories This project makes use of multiple other projects. We wouldn't be here without these other repositories and the contributions of their developers, past and present. * [z3randomizer](https://github.com/ArchipelagoMW/z3randomizer) * [Enemizer](https://github.com/Ijwu/Enemizer) * [Ocarina of Time Randomizer](https://github.com/TestRunnerSRL/OoT-Randomizer) ## Contributing Contributions are welcome. We have a few asks of any new contributors. * Ensure that all changes which affect logic are covered by unit tests. * Do not introduce any unit test failures/regressions. Otherwise, we tend to judge code on a case to case basis. It is a generally good idea to stick to PEP-8 guidelines to ensure consistency with existing code. (And to make the linter happy.) ## Code of Conduct We conduct ourselves openly and inclusively here. Please do not contribute to an environment which makes other people uncomfortable. This means that we expect all contributors or participants here to: * Be welcoming and inclusive in tone and language. * Be respectful of others and their abilities. * Show empathy when speaking with others. * Be gracious and accept feedback and constructive criticism. These guidelines apply to all channels of communication within this GitHub repository. Please be respectful in both public channels, such as issues, and private, such as private messaging or emails. Any incidents of abuse may be reported directly to Ijwu at <EMAIL>. <file_sep>{% from "macros.lua" import dict_to_recipe %} -- this file gets written automatically by the Archipelago Randomizer and is in its raw form a Jinja2 Template require('lib') {%- for recipe_name, recipe in custom_recipes.items() %} data.raw["recipe"]["{{recipe_name}}"].ingredients = {{ dict_to_recipe(recipe.ingredients) }} {%- endfor %} local technologies = data.raw["technology"] local original_tech local new_tree_copy allowed_ingredients = {} {%- for tech_name, technology in custom_technologies.items() %} allowed_ingredients["{{ tech_name }}"] = { {%- for ingredient in technology.ingredients %} ["{{ingredient}}"] = 1, {%- endfor %} } {% endfor %} local template_tech = table.deepcopy(technologies["automation"]) {#- ensure the copy unlocks nothing #} template_tech.unlocks = {} template_tech.upgrade = false template_tech.effects = {} template_tech.prerequisites = {} function prep_copy(new_copy, old_tech) old_tech.hidden = true new_copy.unit = table.deepcopy(old_tech.unit) local ingredient_filter = allowed_ingredients[old_tech.name] if ingredient_filter ~= nil then new_copy.unit.ingredients = filter_ingredients(new_copy.unit.ingredients, ingredient_filter) new_copy.unit.ingredients = add_ingredients(new_copy.unit.ingredients, ingredient_filter) end end function set_ap_icon(tech) tech.icon = "__{{ mod_name }}__/graphics/icons/ap.png" tech.icons = nil tech.icon_size = 128 end function set_ap_unimportant_icon(tech) tech.icon = "__{{ mod_name }}__/graphics/icons/ap_unimportant.png" tech.icons = nil tech.icon_size = 128 end function copy_factorio_icon(tech, tech_source) tech.icon = table.deepcopy(technologies[tech_source].icon) tech.icons = table.deepcopy(technologies[tech_source].icons) tech.icon_size = table.deepcopy(technologies[tech_source].icon_size) end {# This got complex, but seems to be required to hit all corner cases #} function adjust_energy(recipe_name, factor) local recipe = data.raw.recipe[recipe_name] local energy = recipe.energy_required if (recipe.normal ~= nil) then if (recipe.normal.energy_required == nil) then energy = 0.5 else energy = recipe.normal.energy_required end recipe.normal.energy_required = energy * factor end if (recipe.expensive ~= nil) then if (recipe.expensive.energy_required == nil) then energy = 0.5 else energy = recipe.expensive.energy_required end recipe.expensive.energy_required = energy * factor end if (energy ~= nil) then data.raw.recipe[recipe_name].energy_required = energy * factor elseif (recipe.expensive == nil and recipe.normal == nil) then data.raw.recipe[recipe_name].energy_required = 0.5 * factor end end data.raw["assembling-machine"]["assembling-machine-1"].crafting_categories = table.deepcopy(data.raw["assembling-machine"]["assembling-machine-3"].crafting_categories) data.raw["assembling-machine"]["assembling-machine-2"].crafting_categories = table.deepcopy(data.raw["assembling-machine"]["assembling-machine-3"].crafting_categories) data.raw["assembling-machine"]["assembling-machine-1"].fluid_boxes = table.deepcopy(data.raw["assembling-machine"]["assembling-machine-2"].fluid_boxes) data.raw["ammo"]["artillery-shell"].stack_size = 10 {# each randomized tech gets set to be invisible, with new nodes added that trigger those #} {%- for original_tech_name, item_name, receiving_player, advancement in locations %} original_tech = technologies["{{original_tech_name}}"] {#- the tech researched by the local player #} new_tree_copy = table.deepcopy(template_tech) new_tree_copy.name = "ap-{{ tech_table[original_tech_name] }}-"{# use AP ID #} prep_copy(new_tree_copy, original_tech) {% if tech_cost_scale != 1 %} new_tree_copy.unit.count = math.max(1, math.floor(new_tree_copy.unit.count * {{ tech_cost_scale }})) {% endif %} {%- if (tech_tree_information == 2 or original_tech_name in static_nodes) and item_name in base_tech_table -%} {#- copy Factorio Technology Icon -#} copy_factorio_icon(new_tree_copy, "{{ item_name }}") {%- if original_tech_name == "rocket-silo" and original_tech_name in static_nodes %} {%- for ingredient in custom_recipes["rocket-part"].ingredients %} table.insert(new_tree_copy.effects, {type = "nothing", effect_description = "Ingredient {{ loop.index }}: {{ ingredient }}"}) {% endfor -%} {% endif -%} {%- elif (tech_tree_information == 2 or original_tech_name in static_nodes) and item_name in progressive_technology_table -%} copy_factorio_icon(new_tree_copy, "{{ progressive_technology_table[item_name][0] }}") {%- else -%} {#- use default AP icon if no Factorio graphics exist -#} {% if advancement or not tech_tree_information %}set_ap_icon(new_tree_copy){% else %}set_ap_unimportant_icon(new_tree_copy){% endif %} {%- endif -%} {#- connect Technology #} {%- if original_tech_name in tech_tree_layout_prerequisites %} {%- for prerequesite in tech_tree_layout_prerequisites[original_tech_name] %} table.insert(new_tree_copy.prerequisites, "ap-{{ tech_table[prerequesite] }}-") {% endfor %} {% endif -%} {#- add new Technology to game #} data:extend{new_tree_copy} {% endfor %} {% if recipe_time_scale %} {%- for recipe_name, recipe in recipes.items() %} {%- if recipe.category != "mining" %} adjust_energy("{{ recipe_name }}", {{ flop_random(*recipe_time_scale) }}) {%- endif %} {%- endfor -%} {% endif %} {%- if silo==2 %} -- disable silo research for pre-placed silo technologies["rocket-silo"].enabled = false technologies["rocket-silo"].visible_when_disabled = false {%- endif %} <file_sep>from BaseClasses import Item import typing class ItemData(typing.NamedTuple): code: typing.Optional[int] progression: bool class MinecraftItem(Item): game: str = "Minecraft" item_table = { "Archery": ItemData(45000, True), "Progressive Resource Crafting": ItemData(45001, True), # "Resource Blocks": ItemData(45002, True), "Brewing": ItemData(45003, True), "Enchanting": ItemData(45004, True), "Bucket": ItemData(45005, True), "Flint and Steel": ItemData(45006, True), "Bed": ItemData(45007, True), "Bottles": ItemData(45008, True), "Shield": ItemData(45009, True), "Fishing Rod": ItemData(45010, True), "Campfire": ItemData(45011, True), "Progressive Weapons": ItemData(45012, True), "Progressive Tools": ItemData(45013, True), "Progressive Armor": ItemData(45014, True), "8 Netherite Scrap": ItemData(45015, True), "8 Emeralds": ItemData(45016, False), "4 Emeralds": ItemData(45017, False), "Channeling Book": ItemData(45018, True), "Silk Touch Book": ItemData(45019, True), "Sharpness III Book": ItemData(45020, False), "Piercing IV Book": ItemData(45021, True), "Looting III Book": ItemData(45022, False), "Infinity Book": ItemData(45023, False), "4 Diamond Ore": ItemData(45024, False), "16 Iron Ore": ItemData(45025, False), "500 XP": ItemData(45026, False), "100 XP": ItemData(45027, False), "50 XP": ItemData(45028, False), "3 Ender Pearls": ItemData(45029, True), "4 Lapis Lazuli": ItemData(45030, False), "16 Porkchops": ItemData(45031, False), "8 Gold Ore": ItemData(45032, False), "Rotten Flesh": ItemData(45033, False), "Single Arrow": ItemData(45034, False), "32 Arrows": ItemData(45035, False), "Saddle": ItemData(45036, True), "Structure Compass (Village)": ItemData(45037, True), "Structure Compass (Pillager Outpost)": ItemData(45038, True), "Structure Compass (Nether Fortress)": ItemData(45039, True), "Structure Compass (Bastion Remnant)": ItemData(45040, True), "Structure Compass (End City)": ItemData(45041, True), "Shulker Box": ItemData(45042, False), "Dragon Egg Shard": ItemData(45043, True), "Bee Trap (Minecraft)": ItemData(45100, False), "Blaze Rods": ItemData(None, True), "Victory": ItemData(None, True) } # 33 required items required_items = { "Archery": 1, "Progressive Resource Crafting": 2, "Brewing": 1, "Enchanting": 1, "Bucket": 1, "Flint and Steel": 1, "Bed": 1, "Bottles": 1, "Shield": 1, "Fishing Rod": 1, "Campfire": 1, "Progressive Weapons": 3, "Progressive Tools": 3, "Progressive Armor": 2, "8 Netherite Scrap": 2, "Channeling Book": 1, "Silk Touch Book": 1, "Sharpness III Book": 1, "Piercing IV Book": 1, "Looting III Book": 1, "Infinity Book": 1, "3 Ender Pearls": 4, "Saddle": 1, } junk_weights = { "4 Emeralds": 2, "4 Diamond Ore": 1, "16 Iron Ore": 1, "50 XP": 4, "16 Porkchops": 2, "8 Gold Ore": 1, "Rotten Flesh": 1, "32 Arrows": 1, } lookup_id_to_name: typing.Dict[int, str] = {data.code: item_name for item_name, data in item_table.items() if data.code} <file_sep>import os import logging import typing import asyncio import sys os.environ["KIVY_NO_CONSOLELOG"] = "1" os.environ["KIVY_NO_FILELOG"] = "1" os.environ["KIVY_NO_ARGS"] = "1" from kivy.app import App from kivy.core.window import Window from kivy.base import ExceptionHandler, ExceptionManager, Config, Clock from kivy.factory import Factory from kivy.properties import BooleanProperty, ObjectProperty from kivy.uix.button import Button from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.uix.recycleview import RecycleView from kivy.uix.tabbedpanel import TabbedPanel, TabbedPanelItem from kivy.uix.boxlayout import BoxLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.label import Label from kivy.uix.progressbar import ProgressBar from kivy.utils import escape_markup from kivy.lang import Builder import Utils from NetUtils import JSONtoTextParser, JSONMessagePart if typing.TYPE_CHECKING: import CommonClient context_type = CommonClient.CommonContext else: context_type = object # I was surprised to find this didn't already exist in kivy :( class HoverBehavior(object): """from https://stackoverflow.com/a/605348110""" hovered = BooleanProperty(False) border_point = ObjectProperty(None) def __init__(self, **kwargs): self.register_event_type('on_enter') self.register_event_type('on_leave') Window.bind(mouse_pos=self.on_mouse_pos) Window.bind(on_cursor_leave=self.on_cursor_leave) super(HoverBehavior, self).__init__(**kwargs) def on_mouse_pos(self, *args): if not self.get_root_window(): return # do proceed if I'm not displayed <=> If have no parent pos = args[1] # Next line to_widget allow to compensate for relative layout inside = self.collide_point(*self.to_widget(*pos)) if self.hovered == inside: return # We have already done what was needed self.border_point = pos self.hovered = inside if inside: self.dispatch("on_enter") else: self.dispatch("on_leave") def on_cursor_leave(self, *args): # if the mouse left the window, it is obviously no longer inside the hover label. self.hovered = BooleanProperty(False) self.border_point = ObjectProperty(None) self.dispatch("on_leave") Factory.register('HoverBehavior', HoverBehavior) class ServerToolTip(Label): pass class ServerLabel(HoverBehavior, Label): def __init__(self, *args, **kwargs): super(ServerLabel, self).__init__(*args, **kwargs) self.layout = FloatLayout() self.popuplabel = ServerToolTip(text="Test") self.layout.add_widget(self.popuplabel) def on_enter(self): self.popuplabel.text = self.get_text() App.get_running_app().root.add_widget(self.layout) def on_leave(self): App.get_running_app().root.remove_widget(self.layout) def get_text(self): if self.ctx.server: ctx = self.ctx text = f"Connected to: {ctx.server_address}." if ctx.slot is not None: text += f"\nYou are Slot Number {ctx.slot} in Team Number {ctx.team}, " \ f"named {ctx.player_names[ctx.slot]}." if ctx.items_received: text += f"\nYou have received {len(ctx.items_received)} items. " \ f"You can list them in order with /received." if ctx.total_locations: text += f"\nYou have checked {len(ctx.checked_locations)} " \ f"out of {ctx.total_locations} locations. " \ f"You can get more info on missing checks with /missing." if ctx.permissions: text += "\nPermissions:" for permission_name, permission_data in ctx.permissions.items(): text += f"\n {permission_name}: {permission_data}" if ctx.hint_cost is not None: text += f"\nA new !hint <itemname> costs {ctx.hint_cost}% of checks made. " \ f"For you this means every {max(0, int(ctx.hint_cost * 0.01 * ctx.total_locations))} " \ "location checks." elif ctx.hint_cost == 0: text += "\n!hint is free to use." else: text += f"\nYou are not authenticated yet." return text else: return "No current server connection. \nPlease connect to an Archipelago server." @property def ctx(self) -> context_type: return App.get_running_app().ctx class MainLayout(GridLayout): pass class ContainerLayout(FloatLayout): pass class GameManager(App): logging_pairs = [ ("Client", "Archipelago"), ] base_title = "Archipelago Client" def __init__(self, ctx: context_type): self.title = self.base_title self.ctx = ctx self.commandprocessor = ctx.command_processor(ctx) self.icon = r"data/icon.png" self.json_to_kivy_parser = KivyJSONtoTextParser(ctx) self.log_panels = {} super(GameManager, self).__init__() def build(self): self.container = ContainerLayout() self.grid = MainLayout() self.grid.cols = 1 connect_layout = BoxLayout(orientation="horizontal", size_hint_y=None, height=30) # top part server_label = ServerLabel() connect_layout.add_widget(server_label) self.server_connect_bar = TextInput(text="archipelago.gg", size_hint_y=None, height=30, multiline=False) self.server_connect_bar.bind(on_text_validate=self.connect_button_action) connect_layout.add_widget(self.server_connect_bar) self.server_connect_button = Button(text="Connect", size=(100, 30), size_hint_y=None, size_hint_x=None) self.server_connect_button.bind(on_press=self.connect_button_action) connect_layout.add_widget(self.server_connect_button) self.grid.add_widget(connect_layout) self.progressbar = ProgressBar(size_hint_y=None, height=3) self.grid.add_widget(self.progressbar) # middle part self.tabs = TabbedPanel(size_hint_y=1) self.tabs.default_tab_text = "All" self.log_panels["All"] = self.tabs.default_tab_content = UILog(*(logging.getLogger(logger_name) for logger_name, name in self.logging_pairs)) for logger_name, display_name in self.logging_pairs: bridge_logger = logging.getLogger(logger_name) panel = TabbedPanelItem(text=display_name) self.log_panels[display_name] = panel.content = UILog(bridge_logger) self.tabs.add_widget(panel) self.grid.add_widget(self.tabs) if len(self.logging_pairs) == 1: # Hide Tab selection if only one tab self.tabs.clear_tabs() self.tabs.do_default_tab = False self.tabs.current_tab.height = 0 self.tabs.tab_height = 0 # bottom part bottom_layout = BoxLayout(orientation="horizontal", size_hint_y=None, height=30) info_button = Button(height=30, text="Command:", size_hint_x=None) info_button.bind(on_release=self.command_button_action) bottom_layout.add_widget(info_button) textinput = TextInput(size_hint_y=None, height=30, multiline=False) textinput.bind(on_text_validate=self.on_message) bottom_layout.add_widget(textinput) self.grid.add_widget(bottom_layout) self.commandprocessor("/help") Clock.schedule_interval(self.update_texts, 1 / 30) self.container.add_widget(self.grid) self.catch_unhandled_exceptions() return self.container def catch_unhandled_exceptions(self): """Relay unhandled exceptions to UI logger.""" if not getattr(sys.excepthook, "_wrapped", False): # skip if already modified orig_hook = sys.excepthook def handle_exception(exc_type, exc_value, exc_traceback): if issubclass(exc_type, KeyboardInterrupt): sys.__excepthook__(exc_type, exc_value, exc_traceback) return logging.getLogger("Client").exception("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback)) return orig_hook(exc_type, exc_value, exc_traceback) handle_exception._wrapped = True sys.excepthook = handle_exception def update_texts(self, dt): if self.ctx.server: self.title = self.base_title + " " + Utils.__version__ + \ f" | Connected to: {self.ctx.server_address} " \ f"{'.'.join(str(e) for e in self.ctx.server_version)}" self.server_connect_button.text = "Disconnect" self.progressbar.max = len(self.ctx.checked_locations) + len(self.ctx.missing_locations) self.progressbar.value = len(self.ctx.checked_locations) else: self.server_connect_button.text = "Connect" self.title = self.base_title + " " + Utils.__version__ self.progressbar.value = 0 def command_button_action(self, button): logging.getLogger("Client").info("/help for client commands and !help for server commands.") def connect_button_action(self, button): if self.ctx.server: self.ctx.server_address = None asyncio.create_task(self.ctx.disconnect()) else: asyncio.create_task(self.ctx.connect(self.server_connect_bar.text.replace("/connect ", ""))) def on_stop(self): # "kill" input tasks for x in range(self.ctx.input_requests): self.ctx.input_queue.put_nowait("") self.ctx.input_requests = 0 self.ctx.exit_event.set() def on_message(self, textinput: TextInput): try: input_text = textinput.text.strip() textinput.text = "" if self.ctx.input_requests > 0: self.ctx.input_requests -= 1 self.ctx.input_queue.put_nowait(input_text) elif input_text: self.commandprocessor(input_text) except Exception as e: logging.getLogger("Client").exception(e) def print_json(self, data): text = self.json_to_kivy_parser(data) self.log_panels["Archipelago"].on_message_markup(text) self.log_panels["All"].on_message_markup(text) class FactorioManager(GameManager): logging_pairs = [ ("Client", "Archipelago"), ("FactorioServer", "Factorio Server Log"), ("FactorioWatcher", "Bridge Data Log"), ] base_title = "Archipelago Factorio Client" class LttPManager(GameManager): logging_pairs = [ ("Client", "Archipelago"), ("SNES", "SNES"), ] base_title = "Archipelago LttP Client" class TextManager(GameManager): logging_pairs = [ ("Client", "Archipelago") ] base_title = "Archipelago Text Client" class LogtoUI(logging.Handler): def __init__(self, on_log): super(LogtoUI, self).__init__(logging.DEBUG) self.on_log = on_log def handle(self, record: logging.LogRecord) -> None: self.on_log(self.format(record)) class UILog(RecycleView): cols = 1 def __init__(self, *loggers_to_handle, **kwargs): super(UILog, self).__init__(**kwargs) self.data = [] for logger in loggers_to_handle: logger.addHandler(LogtoUI(self.on_log)) def on_log(self, record: str) -> None: self.data.append({"text": escape_markup(record)}) def on_message_markup(self, text): self.data.append({"text": text}) class E(ExceptionHandler): logger = logging.getLogger("Client") def handle_exception(self, inst): self.logger.exception("Uncaught Exception:", exc_info=inst) return ExceptionManager.PASS class KivyJSONtoTextParser(JSONtoTextParser): color_codes = { # not exact color names, close enough but decent looking "black": "000000", "red": "EE0000", "green": "00FF7F", "yellow": "FAFAD2", "blue": "6495ED", "magenta": "EE00EE", "cyan": "00EEEE", "white": "FFFFFF" } def _handle_color(self, node: JSONMessagePart): colors = node["color"].split(";") node["text"] = escape_markup(node["text"]) for color in colors: color_code = self.color_codes.get(color, None) if color_code: node["text"] = f"[color={color_code}]{node['text']}[/color]" return self._handle_text(node) return self._handle_text(node) ExceptionManager.add_handler(E()) Config.set("input", "mouse", "mouse,disable_multitouch") Config.set('kivy', 'exit_on_escape', '0') Builder.load_file(Utils.local_path("data", "client.kv")) <file_sep># Archipelago API This document tries to explain some internals required to implement a game for Archipelago's generation and server. Once a seed is generated, a client or mod is required to send and receive items between the game and server. Client implementation is out of scope of this document. Please refer to an existing game that provides a similar API to yours. Refer to the following documents as well: * [network protocol.md](https://github.com/ArchipelagoMW/Archipelago/blob/main/docs/network%20protocol.md) * [adding games.md](https://github.com/ArchipelagoMW/Archipelago/blob/main/docs/adding%20games.md) Archipelago will be abbreviated as "AP" from now on. ## Language AP worlds are written in python3. Clients that connect to the server to sync items can be in any language that allows using WebSockets. ## Coding style AP follows all the PEPs. When in doubt use an IDE with coding style linter, for example PyCharm Community Edition. ## Docstrings Docstrings are strings attached to an object in Python that describe what the object is supposed to be. Certain docstrings will be picked up and used by AP. They are assigned by writing a string without any assignment right below a definition. The string must be a triple-quoted string. Example: ```python class MyGameWorld(World): """This is the description of My Game that will be displayed on the AP website.""" ``` ## Definitions ### World Class A `World` class is the class with all the specifics of a certain game to be included. It will be instantiated for each player that rolls a seed for that game. ### MultiWorld Object The `MultiWorld` object references the whole multiworld (all items and locations for all players) and is accessible through `self.world` inside a `World` object. ### Player The player is just an integer in AP and is accessible through `self.player` inside a World object. ### Player Options Players provide customized settings for their World in the form of yamls. Those are accessible through `self.world.<option_name>[self.player]`. A dict of valid options has to be provided in `self.options`. Options are automatically added to the `World` object for easy access. ### World Options Any AP installation can provide settings for a world, for example a ROM file, accessible through `Utils.get_options()['<world>_options']['<option>']`. Users can set those in their `host.yaml` file. ### Locations Locations are places where items can be located in your game. This may be chests or boss drops for RPG-like games but could also be progress in a research tree. Each location has a `name` and an `id` (a.k.a. "code" or "address"), is placed in a Region and has access rules. The name needs to be unique in each game, the ID needs to be unique across all games and is best in the same range as the item IDs. Special locations with ID `None` can hold events. ### Items Items are all things that can "drop" for your game. This may be RPG items like weapons, could as well be technologies you normally research in a research tree. Each item has a `name`, an `id` (can be known as "code"), and an `advancement` flag. An advancement item is an item which a player may require to advance in their world. Advancement items will be assigned to locations with higher priority and moved around to meet defined rules and accomplish progression balancing. Special items with ID `None` can mark events (read below). ### Events Events will mark some progress. You define an event location, an event item, strap some rules to the location (i.e. hold certain items) and manually place the event item at the event location. Events can be used to either simplify the logic or to get better spoiler logs. Events will show up in the spoiler playthrough but they do not represent actual items or locations within the game. There is one special case for events: Victory. To get the win condition to show up in the spoiler log, you create an event item and place it at an event location with the `access_rules` for game completion. Once that's done, the world's win condition can be as simple as checking for that item. By convention the victory event is called `"Victory"`. It can be placed at one or more event locations based on player options. ### Regions Regions are logical groups of locations that share some common access rules. If location logic is written from scratch, using regions greatly simplifies the definition and allow to somewhat easily implement things like entrance randomizer in logic. Regions have a list called `exits` which are `Entrance` objects representing transitions to other regions. There has to be one special region "Menu" from which the logic unfolds. AP assumes that a player will always be able to return to the "Menu" region by resetting the game ("Save and quit"). ### Entrances An `Entrance` connects to a region, is assigned to region's exits and has rules to define if it and thus the connected region is accessible. They can be static (regular logic) or be defined/connected during generation (entrance randomizer). ### Access Rules An access rule is a function that returns `True` or `False` for a `Location` or `Entrance` based on the the current `state` (items that can be collected). ### Item Rules An item rule is a function that returns `True` or `False` for a `Location` based on a single item. It can be used to reject placement of an item there. ## Implementation ### Your World All code for your world implementation should be placed in a python package in the `/worlds` directory. The starting point for the package is `__init.py__`. Conventionally, your world class is placed in that file. World classes must inherit from the `World` class in `/worlds/AutoWorld.py`, which can be imported as `..AutoWorld.World` from your package. AP will pick up your world automatically due to the `AutoWorld` implementation. ### Requirements If your world needs specific python packages, they can be listed in `world/[world_name]/requirements.txt`. See [pip documentation](https://pip.pypa.io/en/stable/cli/pip_install/#requirements-file-format) ### Relative Imports AP will only import the `__init__.py`. Depending on code size it makes sense to use multiple files and use relative imports to access them. e.g. `from .Options import mygame_options` from your `__init__.py` will load `world/[world_name]/Options.py` and make its `mygame_options` accesible. When imported names pile up it may be easier to use `from . import Options` and access the variable as `Options.mygame_options`. ### Your Item Type Each world uses its own subclass of `BaseClasses.Item`. The constuctor can be overridden to attach additional data to it, e.g. "price in shop". Since the constructor is only ever called from your code, you can add whatever arguments you like to the constructor. In its simplest form we only set the game name and use the default constuctor ```python from BaseClasses import Item class MyGameItem(Item): game: str = "My Game" ``` By convention this class definition will either be placed in your `__init__.py` or your `Items.py`. For a more elaborate example see `worlds/oot/Items.py`. ### Your location type The same we have done for items above, we will do for locations ```python from BasClasses import Location class MyGameLocation(Location): game: str = "My Game" # override constructor to automatically mark event locations as such def __init__(self, player: int, name = '', code = None, parent = None): super(MyGameLocation, self).__init__(player, name, code, parent) self.event = code is None ``` in your `__init__.py` or your `Locations.py`. ### Options By convention options are defined in `Options.py` and will be used when parsing the players' yaml files. Each option has its own class, inherits from a base option type, has a docstring to describe it and a `displayname` property for display on the website and in spoiler logs. The actual name as used in the yaml is defined in a `dict[str, Option]`, that is assigned to the world under `self.options`. Common option types are `Toggle`, `DefaultOnToggle`, `Choice`, `Range`. For more see `Options.py` in AP's base directory. #### Toggle, DefaultOnToggle Those don't need any additional properties defined. After parsing the option, its `value` will either be True or False. #### Range Define properties `range_start`, `range_end` and `default`. Ranges will be displayed as sliders on the website and can be set to random in the yaml. #### Choice Choices are like toggles, but have more options than just True and False. Define a property `option_<name> = <number>` per selectable value and `default = <number>` to set the default selection. Aliases can be set by defining a property `alias_<name> = <same number>`. One special case where aliases are required is when option name is `yes`, `no`, `on` or `off` because they parse to `True` or `False`: ```python option_off = 0 option_on = 1 option_some = 2 alias_false = 0 alias_true = 1 default = 0 ``` #### Sample ```python # Options.py from Options import Toggle, Range, Choice import typing class Difficulty(Choice): """Sets overall game difficulty.""" displayname = "Difficulty" option_easy = 0 option_normal = 1 option_hard = 2 alias_beginner = 0 # same as easy alias_expert = 2 # same as hard default = 1 # default to normal class FinalBossHP(Range): """Sets the HP of the final boss""" displayname = "Final Boss HP" range_start = 100 range_end = 10000 default = 2000 class FixXYZGlitch(Toggle): """Fixes ABC when you do XYZ""" displayname = "Fix XYZ Glitch" # By convention we call the options dict variable `<world>_options`. mygame_options: typing.Dict[str, type(Option)] = { "difficulty": Difficulty, "final_boss_hp": FinalBossHP, "fix_xyz_glitch": FixXYZGlitch } ``` ```python # __init__.py from ..AutoWorld import World from .Options import mygame_options # import the options dict class MyGameWorld(World): #... options = mygame_options # assign the options dict to the world #... ``` ### Local or Remote A world with `remote_items` set to `True` gets all items items from the server and no item from the local game. So for an RPG opening a chest would not add any item to your inventory, instead the server will send you what was in that chest. The advantage is that a generic mod can be used that does not need to know anything about the seed. A world with `remote_items` set to `False` will locally reward its local items. For console games this can remove delay and make script/animation/dialog flow more natural. These games typically have been edited to 'bake in' the items. ### A World Class Skeleton ```python # world/mygame/__init__.py from .Options import mygame_options # the options we defined earlier from .Items import mygame_items # data used below to add items to the World from .Locations import mygame_locations # same as above from ..AutoWorld import World from BaseClasses import Region, Location, Entrance, Item from Utils import get_options, output_path class MyGameItem(Item): # or from Items import MyGameItem game = "My Game" # name of the game/world this item is from class MyGameLocation(Location): # or from Locations import MyGameLocation game = "My Game" # name of the game/world this location is in class MyGameWorld(World): """Insert description of the world/game here.""" game: str = "My Game" # name of the game/world options = mygame_options # options the player can set topology_present: bool = True # show path to required location checks in spoiler remote_items: bool = False # True if all items come from the server remote_start_inventory: bool = False # True if start inventory comes from the server # data_version is used to signal that items, locations or their names # changed. Set this to 0 during development so other games' clients do not # cache any texts, then increase by 1 for each release that makes changes. data_version = 0 # ID of first item and location, could be hard-coded but code may be easier # to read with this as a propery. base_id = 1234 # Instead of dynamic numbering, IDs could be part of data. # The following two dicts are required for the generation to know which # items exist. They could be generated from json or something else. They can # include events, but don't have to since events will be placed manually. item_name_to_id = {name: id for id, name in enumerate(mygame_items, base_id)} location_name_to_id = {name: id for id, name in enumerate(mygame_locations, base_id)} # Items can be grouped using their names to allow easy checking if any item # from that group has been collected. Group names can also be used for !hint item_name_groups = { "weapons": {"sword", "lance"} } ``` ### Generation The world has to provide the following things for generation * the properties mentioned above * additions to the item pool * additions to the regions list: at least one called "Menu" * locations placed inside those regions * a `def create_item(self, item: str) -> MyGameItem` for plando/manual placing * applying `self.world.precollected_items` for plando/start inventory if not using a `remote_start_inventory` * a `def generate_output(self, output_directory: str)` that creates the output if there is output to be generated. If only items are randomized and `remote_items = True` it is possible to have a generic mod and output generation can be skipped. In all other cases this is required. When this is called, `self.world.get_locations()` has all locations for all players, with properties `item` pointing to the item and `player` identifying the player. `self.world.get_filled_locations(self.player)` will filter for this world. `item.player` can be used to see if it's a local item. In addition the following methods can be implemented * `def generate_early(self)` called per player before any items or locations are created. You can set properties on your world here. Already has access to player options and RNG. * `def create_regions(self)` called to place player's regions into the MultiWorld's regions list. If it's hard to separate, this can be done during `generate_early` or `basic` as well. * `def create_items(self)` called to place player's items into the MultiWorld's itempool. * `def set_rules(self)` called to set access and item rules on locations and entrances. * `def generate_basic(self)` called after the previous steps. Some placement and player specific randomizations can be done here. After this step all regions and items have to be in the MultiWorld's regions and itempool. * `pre_fill`, `fill_hook` and `post_fill` are called to modify item placement before, during and after the regular fill process, before `generate_output`. * `fill_slot_data` and `modify_multidata` can be used to modify the data that will be used by the server to host the MultiWorld. * `def get_required_client_version(self)` can return a tuple of 3 ints to make sure the client is compatible to this world (e.g. item IDs) when connecting. #### generate_early ```python def generate_early(self): # read player settings to world instance self.final_boss_hp = self.world.final_boss_hp[self.player].value ``` #### create_item ```python # we need a way to know if an item provides progress in the game ("key item") # this can be part of the items definition, or depend on recipe randomization from .Items import is_progression # this is just a dummy def create_item(self, item: str): # This is called when AP wants to create an item by name (for plando) or # when you call it from your own code. return MyGameItem(item, is_progression(item), self.item_name_to_id[item], self.player) def create_event(self, event: str): # while we are at it, we can also add a helper to create events return MyGameItem(event, True, None, self.player) ``` #### create_items ```python def create_items(self): # Add items to the Multiworld. # If there are two of the same item, the item has to be twice in the pool. # Which items are added to the pool may depend on player settings, # e.g. custom win condition like triforce hunt. # Having an item in the start inventory won't remove it from the pool. # If an item can't have duplicates it has to be excluded manually. # List of items to exclude, as a copy since it will be destroyed below exclude = [item for item in self.world.precollected_items[self.player]] for item in map(self.create_item, mygame_items): if item in exclude: exclude.remove(item) # this is destructive. create unique list above self.world.itempool.append(self.create_item('nothing')) else: self.world.itempool.append(item) # itempool and number of locations should match up. # If this is not the case we want to fill the itempool with junk. junk = 0 # calculate this based on player settings self.world.itempool += [self.create_item('nothing') for _ in range(junk)] ``` #### create_regions ```python def create_regions(self): # Add regions to the multiworld. "Menu" is the required starting point. # Arguments to Region() are name, type, human_readable_name, player, world r = Region("Menu", None, "Menu", self.player, self.world) # Set Region.exits to a list of entrances that are reachable from region r.exits = [Entrance(self.player, "New game", r)] # or use r.exits.append # Append region to MultiWorld's regions self.world.regions.append(r) # or use += [r...] r = Region("Main Area", None, "Main Area", self.player, self.world) # Add main area's locations to main area (all but final boss) r.locations = [MyGameLocation(self.player, location.name, self.location_name_to_id[location.name], r)] r.exits = [Entrance(self.player, "Boss Door", r)] self.world.regions.append(r) r = Region("Boss Room", None, "Boss Room", self.player, self.world) # add event to Boss Room r.locations = [MyGameLocation(self.player, "Final Boss", None, r)] self.world.regions.append(r) # If entrances are not randomized, they should be connected here, otherwise # they can also be connected at a later stage. self.world.get_entrance("New Game", self.player)\ .connect(self.world.get_region("Main Area", self.player)) self.world.get_entrance("Boss Door", self.player)\ .connect(self.world.get_region("Boss Room", self.player)) # If setting location access rules from data is easier here, set_rules can # possibly omitted. ``` #### generate_basic ```python def generate_basic(self): # place "Victory" at "Final Boss" and set collection as win condition self.world.get_location("Final Boss", self.player)\ .place_locked_item(self.create_event("Victory")) self.world.completion_condition[self.player] = \ lambda state: state.has("Victory", self.player) # place item Herb into location Chest1 for some reason item = self.create_item("Herb") self.world.get_location("Chest1", self.player).place_locked_item(item) # in most cases it's better to do this at the same time the itempool is # filled to avoid accidental duplicates: # manually placed and still in the itempool ``` ### Setting Rules ```python from ..generic.Rules import add_rule, set_rule, forbid_item from Items import get_item_type def set_rules(self): # For some worlds this step can be omitted if either a Logic mixin # (see below) is used, it's easier to apply the rules from data during # location generation or everything is in generate_basic # set a simple rule for an region set_rule(self.world.get_entrance("Boss Door", self.player), lambda state: state.has("Boss Key", self.player)) # combine rules to require two items add_rule(self.world.get_location("Chest2", self.player), lambda state: state.has("Sword", self.player)) add_rule(self.world.get_location("Chest2", self.player), lambda state: state.has("Shield", self.player)) # or simply combine yourself set_rule(self.world.get_location("Chest2", self.player), lambda state: state.has("Sword", self.player) and state.has("Shield", self.player)) # require two of an item set_rule(self.world.get_location("Chest3", self.player), lambda state: state.has("Key", self.player, 2)) # require one item from an item group add_rule(self.world.get_location("Chest3", self.player), lambda state: state.has_group("weapons", self.player)) # state also has .item_count() for items, .has_any() and.has_all() for sets # and .count_group() for groups # set_rule is likely to be a bit faster than add_rule # disallow placing a specific local item at a specific location forbid_item(self.world.get_location("Chest4", self.player), "Sword") # disallow placing items with a specific property add_item_rule(self.world.get_location("Chest5", self.player), lambda item: get_item_type(item) == "weapon") # get_item_type needs to take player/world into account # if MyGameItem has a type property, a more direct implementation would be add_item_rule(self.world.get_location("Chest5", self.player), lambda item: item.player != self.player or\ item.my_type == "weapon") # location.item_rule = ... is likely to be a bit faster ``` ### Logic Mixin While lambdas and events could do pretty much anything, by convention we implement more complex logic in logic mixins, even if there is no need to add properties to the `BaseClasses.CollectionState` state object. When importing a file that defines a class that inherits from `..AutoWorld.LogicMixin` the state object's class is automatically extended by the mixin's members. These members should be prefixed with underscore following the name of the implementing world. This is due to sharing a namespace with all other logic mixins. Typical uses are defining methods that are used instead of `state.has` in lambdas, e.g.`state._mygame_has(custom, world, player)` or recurring checks like `state._mygame_can_do_something(world, player)` to simplify lambdas. More advanced uses could be to add additional variables to the state object, override `World.collect(self, state, item)` and `remove(self, state, item)` to update the state object, and check those added variables in added methods. Please do this with caution and only when neccessary. #### Sample ```python # Logic.py from ..AutoWorld import LogicMixin class MyGameLogic(LogicMixin): def _mygame_has_key(self, world: MultiWorld, player: int): # Arguments above are free to choose # it may make sense to use World as argument instead of MultiWorld return self.has('key', player) # or whatever ``` ```python # __init__.py from ..generic.Rules import set_rule import .Logic # apply the mixin by importing its file class MyGameWorld(World): # ... def set_rules(self): set_rule(self.world.get_location("A Door", self.player), lamda state: state._myworld_has_key(self.world, self.player)) ``` ### Generate Output ```python from .Mod import generate_mod def generate_output(self, output_directory: str): # How to generate the mod or ROM highly depends on the game # if the mod is written in Lua, Jinja can be used to fill a template # if the mod reads a json file, `json.dump()` can be used to generate that # code below is a dummy data = { "seed": self.world.seed_name, # to verify the server's multiworld "slot": self.world.player_name[self.player], # to connect to server "items": {location.name: location.item.name if location.item.player == self.player else "Remote" for location in self.world.get_filled_locations(self.player)}, # store start_inventory from player's .yaml "starter_items": [item.name for item in self.world.precollected_items[self.player]], "final_boss_hp": self.final_boss_hp, # store option name "easy", "normal" or "hard" for difficuly "difficulty": self.world.difficulty[self.player].current_key, # store option value True or False for fixing a glitch "fix_xyz_glitch": self.world.fix_xyz_glitch[self.player].value } # point to a ROM specified by the installation src = Utils.get_options()["mygame_options"]["rom_file"] # or point to worlds/mygame/data/mod_template src = os.path.join(os.path.dirname(__file__), "data", "mod_template") # generate output path mod_name = f"AP-{self.world.seed_name}-P{self.player}-{self.world.player_name[self.player]}" out_file = os.path.join(output_directory, mod_name + ".zip") # generate the file generate_mod(src, out_file, data) ``` <file_sep>kivy>=2.0.0 factorio-rcon-py>=1.2.1 schema>=0.7.4 <file_sep>from flask import send_file, Response, render_template from pony.orm import select from Patch import update_patch_data from WebHostLib import app, Slot, Room, Seed, cache import zipfile @app.route("/dl_patch/<suuid:room_id>/<int:patch_id>") def download_patch(room_id, patch_id): patch = Slot.get(id=patch_id) if not patch: return "Patch not found" else: import io room = Room.get(id=room_id) last_port = room.last_port patch_data = update_patch_data(patch.data, server=f"{app.config['PATCH_TARGET']}:{last_port}") patch_data = io.BytesIO(patch_data) fname = f"P{patch.player_id}_{patch.player_name}_{app.jinja_env.filters['suuid'](room_id)}.apbp" return send_file(patch_data, as_attachment=True, attachment_filename=fname) @app.route("/dl_spoiler/<suuid:seed_id>") def download_spoiler(seed_id): return Response(Seed.get(id=seed_id).spoiler, mimetype="text/plain") @app.route("/dl_raw_patch/<suuid:seed_id>/<int:player_id>") def download_raw_patch(seed_id, player_id: int): seed = Seed.get(id=seed_id) patch = select(patch for patch in seed.slots if patch.player_id == player_id).first() if not patch: return "Patch not found" else: import io patch_data = update_patch_data(patch.data, server="") patch_data = io.BytesIO(patch_data) fname = f"P{patch.player_id}_{patch.player_name}_{app.jinja_env.filters['suuid'](seed_id)}.apbp" return send_file(patch_data, as_attachment=True, attachment_filename=fname) @app.route("/slot_file/<suuid:room_id>/<int:player_id>") def download_slot_file(room_id, player_id: int): room = Room.get(id=room_id) slot_data: Slot = select(patch for patch in room.seed.slots if patch.player_id == player_id).first() if not slot_data: return "Slot Data not found" else: import io if slot_data.game == "Minecraft": from worlds.minecraft import mc_update_output fname = f"AP_{app.jinja_env.filters['suuid'](room_id)}_P{slot_data.player_id}_{slot_data.player_name}.apmc" data = mc_update_output(slot_data.data, server=app.config['PATCH_TARGET'], port=room.last_port) return send_file(io.BytesIO(data), as_attachment=True, attachment_filename=fname) elif slot_data.game == "Factorio": with zipfile.ZipFile(io.BytesIO(slot_data.data)) as zf: for name in zf.namelist(): if name.endswith("info.json"): fname = name.rsplit("/", 1)[0]+".zip" elif slot_data.game == "Ocarina of Time": fname = f"AP_{app.jinja_env.filters['suuid'](room_id)}_P{slot_data.player_id}_{slot_data.player_name}.apz5" else: return "Game download not supported." return send_file(io.BytesIO(slot_data.data), as_attachment=True, attachment_filename=fname) @app.route("/templates") @cache.cached() def list_yaml_templates(): files = [] from worlds.AutoWorld import AutoWorldRegister for world_name, world in AutoWorldRegister.world_types.items(): if not world.hidden: files.append(world_name) return render_template("templates.html", files=files)
a8fc7cc0f64571ddcb4d78278f9aa166a74038e5
[ "HTML", "Lua", "Markdown", "JavaScript", "Python", "Text" ]
104
Python
adampziegler/Archipelago
6b0b78d8e07d275aceead3f5a1890eac5f153bf0
8d10ad309e8e3e71fc008d692b3fb1efc6f6ce6a
refs/heads/main
<file_sep>import os def edit_file(text_path): with open(text_path, 'a', encoding='utf-8') as f: f.write('hello diaa')
6bff2aac43f507e0c0b78b4e8fd70e2cb25b2785
[ "Python" ]
1
Python
naderessam110/bla-bla
2fff8dba6e5d4fa4c31765a1b52c3a1f1a1fbf7d
1de71d75f44accda7be459899668f69d66cbe0ea
refs/heads/main
<file_sep># SPM Code and models discussed in the paper "Stringer-Panel Model for Analysis of Building Diaphragms" Code folder - Includes all of the files and information related to the code of the StringPanelLin Model folder - Includes all of the files for the creation of the model discussed in the paper referenced above Please, if using this code or element, give proper credit where it's due. Should any comments or questions arise, send them to the following emails: - <EMAIL> - <EMAIL> <file_sep>/* ****************************************************************** ** ** OpenSees - Open System for Earthquake Engineering Simulation ** ** Pacific Earthquake Engineering Research Center ** ** ** ** ** ** (C) Copyright 1999, The Regents of the University of California ** ** All Rights Reserved. ** ** ** ** Commercial use of this program without express permission of the ** ** University of California, Berkeley, is strictly prohibited. See ** ** file 'COPYRIGHT' in main directory for information on usage and ** ** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** ** ** ** Developed by: ** ** <NAME> (<EMAIL>) ** ** <NAME> (<EMAIL>) ** ** <NAME> (<EMAIL>) ** ** ** ** ****************************************************************** */ // $Revision: 1.12 $ // $Date: 04/05/2022 $ // Description: This file contains the implementation for the StringPanel class. // It contains both the formulations of the panel (a linear-elastic // shear panel with a quadrilateral shape) and the stringers (which // are similar to a truss member). Both panel and stringer act as // one element and do not consider any geometric nonlinearity. // // Ref: Hoogenboom, <NAME>., & <NAME>. (2000). // Quadrilateral shear panel. // Engineering structures, 22(12), 1690-1698. // // Ref: Hoogenboom, <NAME>. (1998). // Discrete elements and nonlinearity in design of structural concrete walls. // Dissertation, Delft University of Technology. ISBN 90-9011843-8 // // Ref: <NAME>., & <NAME>. (1996). // Stringer panel model for structural concrete design. // ACI Structural Journal, 93(3), 295-305 /*********************************************************************** * * $lNode $kNode * * __________________________________ * * | $strSecTag3 | * * | | * * | | * * | | * * | | * * | | * * |$strSecTag4 $strSecTag2 | * * | | * * | | * * | | * * | | * * | | * * |___________$strSecTag1____________| * * $iNode $jNode * * * * ********************************************************************** * */ #ifndef StringPanelLin_h #define StringPanelLin_h #include <Element.h> #include <Matrix.h> #include <Vector.h> #include <Node.h> #include <Channel.h> #include <ID.h> #include <SectionForceDeformation.h> class StringPanelLin : public Element { public: // full constructor StringPanelLin(int tag, int dimension, int Nd1, int Nd2, int Nd3, int Nd4, SectionForceDeformation& theSect1_1, SectionForceDeformation& theSect1_2, SectionForceDeformation& theSect1_3, SectionForceDeformation& theSect2_1, SectionForceDeformation& theSect2_2, SectionForceDeformation& theSect2_3, SectionForceDeformation& theSect3_1, SectionForceDeformation& theSect3_2, SectionForceDeformation& theSect3_3, SectionForceDeformation& theSect4_1, SectionForceDeformation& theSect4_2, SectionForceDeformation& theSect4_3, double Ep, double poisson, double t, double rho = 0.0); // null constructor StringPanelLin(); // destructor ~StringPanelLin(); // Get the number of external nodes, dof and connectivity int getNumExternalNodes(void) const; const ID &getExternalNodes(void); Node** getNodePtrs(void); int getNumDOF(void); void setDomain(Domain* theDomain); // public methods to set the state of the element int commitState(void); int revertToLastCommit(void); int revertToStart(void); int update(void); // public methods to obtain stiffness matrix const Matrix &getInitialStiff(void); const Matrix &getTangentStiff(void); // Lumped mass matrix const Matrix &getMass(void); // methods for applying loads void zeroLoad(void); int addLoad(ElementalLoad* theLoad, double loadFactor); int addInertiaLoadToUnbalance(const Vector &accel); // get residual force const Vector &getResistingForce(void); const Vector &getResistingForceIncInertia(void); // public methods for element output int sendSelf(int commitTag, Channel &theChannel); int recvSelf(int commitTag, Channel &theChannel, FEM_ObjectBroker &theBroker); int displaySelf(Renderer&, int mode, float fact, const char** displayModes = 0, int numModes = 0); void Print(OPS_Stream& s, int flag = 0); Response* setResponse(const char** argv, int argc, OPS_Stream &output); int getResponse(int responseID, Information &eleInfo); private: // Compute strain at two integration points of each stringer Vector computeCurrentStrain(); // Compute panel stiffness matrix in local coordinates const Matrix& getPanelStiff(void); // Transform StringPanel stiffness matrix into global coordinates and assemble const Matrix& assembleK(const Matrix& kStringer1, const Matrix& kStringer2, const Matrix& kStringer3, const Matrix& kStringer4); // Obtain coordinate transformation matrix const Matrix& transformMatrix(void); // Get local force vector for stringers const Vector& getLocalForce(void); // Get displacement at midpoints const Vector& getMidDisp(const Vector& Un); // Get panel area double getPanelArea(void); // Static data static Matrix stiff8; static Matrix stiff12; static Matrix stiff24; static Vector resid8; static Vector resid12; static Vector resid24; // Material properties and section input double E_p; // Young's modulus of panel double nu; // Poisson's ratio of panel double thickness; // Thickness of panel double rho = 0.0; // Mass per unit area (optional) // Sections information, 4 section are asked as input, the _2 is a copy of _1. SectionForceDeformation* theSection1_1; SectionForceDeformation* theSection1_2; SectionForceDeformation* theSection1_3; SectionForceDeformation* theSection2_1; SectionForceDeformation* theSection2_2; SectionForceDeformation* theSection2_3; SectionForceDeformation* theSection3_1; SectionForceDeformation* theSection3_2; SectionForceDeformation* theSection3_3; SectionForceDeformation* theSection4_1; SectionForceDeformation* theSection4_2; SectionForceDeformation* theSection4_3; // Node and dimension information ID connectedExternalNodes; Node* theNodes[4]; double *initialDisp; // Geometry information double L[4] = { 0 }; // vector with stringers length double dx[4] = { 0 }; double dy[4] = { 0 }; double dz[4] = { 0 }; int dimension; // Element can work in 2d and 3d domains int numDOF; // Number of DOF of macro-element //int flagInitial; // Auxiliary flag Vector* theLoad; Matrix* theMatrix; Vector* theVector; }; #endif<file_sep>/* ****************************************************************** ** ** OpenSees - Open System for Earthquake Engineering Simulation ** ** Pacific Earthquake Engineering Research Center ** ** ** ** ** ** (C) Copyright 1999, The Regents of the University of California ** ** All Rights Reserved. ** ** ** ** Commercial use of this program without express permission of the ** ** University of California, Berkeley, is strictly prohibited. See ** ** file 'COPYRIGHT' in main directory for information on usage and ** ** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** ** ** ** Developed by: ** ** <NAME> (<EMAIL>) ** ** <NAME> (<EMAIL>) ** ** <NAME> (<EMAIL>) ** ** ** ** ****************************************************************** */ // $Revision: 1.12 $ // $Date: 05/03/2022 $ // Description: This file contains the implementation for the StringPanel class. // It contains both the formulations of the panel (a linear-elastic // shear panel with a quadrilateral shape) and the stringers (which // are similar to a truss member). Both panel and stringer act as // one element and do not consider any geometric nonlinearity. // // Ref: Hoogenboom, P. C., & Blaauwendraad, J. (2000). // Quadrilateral shear panel. // Engineering structures, 22(12), 1690-1698. // // Ref: Hoogenboom, P. C. (1998). // Discrete elements and nonlinearity in design of structural concrete walls. // Dissertation, Delft University of Technology. ISBN 90-9011843-8 // // Ref: Blaauwendraad, J., & Hoogenboom, P. C. (1996). // Stringer panel model for structural concrete design. // ACI Structural Journal, 93(3), 295-305 /*********************************************************************** * * $lNode $kNode * * __________________________________ * * | $strSecTag3 | * * | | * * | | * * | | * * | | * * | | * * |$strSecTag4 $strSecTag2| * * | | * * | | * * | | * * | | * * | | * * |___________$strSecTag1____________| * * $iNode $jNode * * * * ********************************************************************** * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <StringPanelLin.h> #include <ID.h> #include <Element.h> #include <Node.h> #include <Domain.h> #include <Renderer.h> #include <ErrorHandler.h> #include <ElementResponse.h> #include <R3vectors.h> #include <SectionForceDeformation.h> #include <ElementalLoad.h> #include <Vector.h> #include <Matrix.h> #include <Channel.h> #include <FEM_ObjectBroker.h> #include <elementAPI.h> // initialize the class wide variables Matrix StringPanelLin::stiff8(8, 8); Matrix StringPanelLin::stiff12(12, 12); Matrix StringPanelLin::stiff24(24, 24); Vector StringPanelLin::resid8(8); Vector StringPanelLin::resid12(12); Vector StringPanelLin::resid24(24); void* OPS_StringPanelLin(void) { Element* theElement = 0; int ndm = OPS_GetNDM(); if (ndm < 2) { opserr << "WARNING -- model dimensions are not compatible with StringPanel element"; return 0; } int numArgs = OPS_GetNumRemainingInputArgs(); if (numArgs < 12) { opserr << "WARNING, insufficient arguments.\n"; opserr << "Want: element StringPanelLin $tag $iNode $jNode $kNode $lNode "; opserr << "$strSecTag1 $strSecTag2 $strSecTag3 $strSecTag4 $Ep $nu $t <-rho $rho> \n"; return 0; } int iData[9]; // $tag $iNode $jNode $kNode $lNode $strSecTag1 $strSecTag2 $strSecTag3 $strSecTag4 int numData = 9; if (OPS_GetInt(&numData, iData) != 0) { opserr << "WARNING: invalid integer (tag, Nodes, SecTags) in element StringPanelLin " << iData[0] << "\n"; return 0; } double data[3]; // $E_p $nu $t numData = 3; if (OPS_GetDoubleInput(&numData, data) != 0) { opserr << "WARNING: invalid double arguments (Ep, nu, t) in element StringPanelLin " << iData[0] << "\n"; return 0; } // options double dens = 0.0; numData = 1; if (OPS_GetNumRemainingInputArgs() > 0) { const char* type = OPS_GetString(); if (strcmp(type, "-rho") == 0) { if (OPS_GetNumRemainingInputArgs() > 0) { if (OPS_GetDoubleInput(&numData, &dens) < 0) { opserr << "WARNING: invalid rho in element StringPanelLin " << iData[0] << "\n"; return 0; } } } else { opserr << "WARNING: Invalid option " << type << " in element StringPanelLin " << iData[0] << "\n"; return 0; } } SectionForceDeformation* theSection1_1 = OPS_getSectionForceDeformation(iData[5]); SectionForceDeformation* theSection1_2 = OPS_getSectionForceDeformation(iData[5]); SectionForceDeformation* theSection1_3 = OPS_getSectionForceDeformation(iData[5]); SectionForceDeformation* theSection2_1 = OPS_getSectionForceDeformation(iData[6]); SectionForceDeformation* theSection2_2 = OPS_getSectionForceDeformation(iData[6]); SectionForceDeformation* theSection2_3 = OPS_getSectionForceDeformation(iData[6]); SectionForceDeformation* theSection3_1 = OPS_getSectionForceDeformation(iData[7]); SectionForceDeformation* theSection3_2 = OPS_getSectionForceDeformation(iData[7]); SectionForceDeformation* theSection3_3 = OPS_getSectionForceDeformation(iData[7]); SectionForceDeformation* theSection4_1 = OPS_getSectionForceDeformation(iData[8]); SectionForceDeformation* theSection4_2 = OPS_getSectionForceDeformation(iData[8]); SectionForceDeformation* theSection4_3 = OPS_getSectionForceDeformation(iData[8]); if (theSection1_1 == 0) { opserr << "ERROR: element StringPanelLin " << iData[0] << " section " << iData[5] << " for stringer 1 not found\n"; return 0; } if (theSection2_1 == 0) { opserr << "ERROR: element StringPanelLin " << iData[0] << " section " << iData[6] << " for stringer 2 not found\n"; return 0; } if (theSection3_1 == 0) { opserr << "ERROR: element StringPanelLin " << iData[0] << " section " << iData[7] << " for stringer 3 not found\n"; return 0; } if (theSection4_1 == 0) { opserr << "ERROR: element StringPanelLin " << iData[0] << " section " << iData[8] << " for stringer 4 not found\n"; return 0; } // Create Stringer Panel element theElement = new StringPanelLin(iData[0], ndm, iData[1], iData[2], iData[3], iData[4], *theSection1_1, *theSection1_2, *theSection1_3, *theSection2_1, *theSection2_2, *theSection2_3, *theSection3_1, *theSection3_2, *theSection3_3, *theSection4_1, *theSection4_2, *theSection4_3, data[0], data[1], data[2], dens); return theElement; } // Full constructor StringPanelLin::StringPanelLin(int tag, int dim, int Nd1, int Nd2, int Nd3, int Nd4, SectionForceDeformation& theSect1_1, SectionForceDeformation& theSect1_2, SectionForceDeformation& theSect1_3, SectionForceDeformation& theSect2_1, SectionForceDeformation& theSect2_2, SectionForceDeformation& theSect2_3, SectionForceDeformation& theSect3_1, SectionForceDeformation& theSect3_2, SectionForceDeformation& theSect3_3, SectionForceDeformation& theSect4_1, SectionForceDeformation& theSect4_2, SectionForceDeformation& theSect4_3, double Ep, double poisson, double t, double r) :Element(tag, ELE_TAG_StringPanelLin), dimension(dim), connectedExternalNodes(4), numDOF(0), theLoad(0), theMatrix(0), theVector(0), E_p(Ep), nu(poisson), thickness(t), rho(r), theSection1_1(0), theSection1_2(0), theSection1_3(0), theSection2_1(0), theSection2_2(0), theSection2_3(0), theSection3_1(0), theSection3_2(0), theSection3_3(0), theSection4_1(0), theSection4_2(0), theSection4_3(0), initialDisp(0) { // get a copy of the material and check we obtained a valid copy // First stringer theSection1_1 = theSect1_1.getCopy(); if (theSection1_1 == 0) { opserr << "FATAL StringPanelLin::StringPanelLin - failed to get a copy of material for first stringer " << theSect1_1.getTag() << endln; exit(-1); } int order1 = theSection1_1->getOrder(); const ID& code1 = theSection1_1->getType(); int j; for (j = 0; j < order1; j++) if (code1(j) == SECTION_RESPONSE_P) break; if (j == order1) opserr << "StringPanelLin::StringPanelLin - section of first stringer does not provide axial response\n"; theSection1_2 = theSect1_2.getCopy(); theSection1_3 = theSect1_3.getCopy(); // Second stringer theSection2_1 = theSect2_1.getCopy(); if (theSection2_1 == 0) { opserr << "FATAL StringPanelLin::StringPanelLin - failed to get a copy of material for second stringer " << theSect2_1.getTag() << endln; exit(-1); } int order2 = theSection2_1->getOrder(); const ID& code2 = theSection2_1->getType(); for (j = 0; j < order2; j++) if (code1(j) == SECTION_RESPONSE_P) break; if (j == order2) opserr << "StringPanelLin::StringPanelLin - section of second stringer does not provide axial response\n"; theSection2_2 = theSect2_2.getCopy(); theSection2_3 = theSect2_3.getCopy(); // Third stringer theSection3_1 = theSect3_1.getCopy(); if (theSection3_1 == 0) { opserr << "FATAL StringPanelLin::StringPanelLin - failed to get a copy of material for third stringer " << theSect3_1.getTag() << endln; exit(-1); } int order3 = theSection3_1->getOrder(); const ID& code3 = theSection3_1->getType(); for (j = 0; j < order3; j++) if (code3(j) == SECTION_RESPONSE_P) break; if (j == order3) opserr << "StringPanelLin::StringPanelLin - section of third stringer does not provide axial response\n"; theSection3_2 = theSect3_2.getCopy(); theSection3_3 = theSect3_3.getCopy(); // Fourth stringer theSection4_1 = theSect4_1.getCopy(); if (theSection4_1 == 0) { opserr << "FATAL StringPanelLin::StringPanelLin - failed to get a copy of material for fourth stringer " << theSect4_1.getTag() << endln; exit(-1); } int order4 = theSection4_1->getOrder(); const ID& code4 = theSection4_1->getType(); for (j = 0; j < order4; j++) if (code4(j) == SECTION_RESPONSE_P) break; if (j == order4) opserr << "StringPanelLin::StringPanelLin - section of fourth stringer does not provide axial response\n"; theSection4_2 = theSect4_2.getCopy(); theSection4_3 = theSect4_3.getCopy(); connectedExternalNodes(0) = Nd1; connectedExternalNodes(1) = Nd2; connectedExternalNodes(2) = Nd3; connectedExternalNodes(3) = Nd4; for (int i = 0; i < 4; i++) { theNodes[i] = 0; dx[i] = 0.0; dy[i] = 0.0; dz[i] = 0.0; L[i] = 0.0; } //flagInitial = 0; // initialize flag for midpoint calculation purposess } // Null constructor StringPanelLin::StringPanelLin() :Element(0, ELE_TAG_StringPanelLin), dimension(0), connectedExternalNodes(4), numDOF(0), theLoad(0), theMatrix(0), theVector(0), E_p(0.0), nu(0.0), thickness(0.0), rho (0.0), theSection1_1(0), theSection1_2(0), theSection1_3(0), theSection2_1(0), theSection2_2(0), theSection2_3(0), theSection3_1(0), theSection3_2(0), theSection3_3(0), theSection4_1(0), theSection4_2(0), theSection4_3(0), initialDisp(0) { // ensure the connectedExternalNode ID is of correct size if (connectedExternalNodes.Size() != 4) { opserr << "FATAL StringPanelLin::StringPanelLin - failed to create an ID of correct size\n"; exit(-1); } for (int i = 0; i < 4; i++) theNodes[i] = 0; } // Destructor StringPanelLin::~StringPanelLin() { if (theSection1_1 != 0) delete theSection1_1; if (theSection1_2 != 0) delete theSection1_2; if (theSection1_3 != 0) delete theSection1_3; if (theSection2_1 != 0) delete theSection2_1; if (theSection2_2 != 0) delete theSection2_2; if (theSection2_3 != 0) delete theSection2_3; if (theSection3_1 != 0) delete theSection3_1; if (theSection3_2 != 0) delete theSection3_2; if (theSection3_3 != 0) delete theSection3_3; if (theSection4_1 != 0) delete theSection4_1; if (theSection4_2 != 0) delete theSection4_2; if (theSection4_3 != 0) delete theSection4_3; if (theLoad != 0) delete theLoad; if (initialDisp != 0) delete[] initialDisp; } int StringPanelLin::getNumExternalNodes(void) const { return 4; } const ID& StringPanelLin::getExternalNodes(void) { return connectedExternalNodes; } Node ** StringPanelLin::getNodePtrs(void) { return theNodes; } int StringPanelLin::getNumDOF(void) { return numDOF; } void StringPanelLin::setDomain(Domain* theDomain) { int Nd1 = connectedExternalNodes(0); int Nd2 = connectedExternalNodes(1); int Nd3 = connectedExternalNodes(2); int Nd4 = connectedExternalNodes(3); theNodes[0] = theDomain->getNode(Nd1); theNodes[1] = theDomain->getNode(Nd2); theNodes[2] = theDomain->getNode(Nd3); theNodes[3] = theDomain->getNode(Nd4); // If nodes can't be found, send a message if ((theNodes[0] == 0) || (theNodes[1] == 0) || (theNodes[2] == 0) || (theNodes[3] == 0)) { if (theNodes[0] == 0) opserr << "StringPanelLin::setDomain() - StringPanel" << this->getTag() << " node " << Nd1 << "does not exist in the model\n"; else if (theNodes[1] == 0) opserr << "StringPanelLin::setDomain() - StringPanel" << this->getTag() << " node " << Nd2 << "does not exist in the model\n"; else if (theNodes[2] == 0) opserr << "StringPanelLin::setDomain() - StringPanel" << this->getTag() << " node " << Nd3 << "does not exist in the model\n"; else opserr << "StringPanelLin::setDomain() - StringPanel" << this->getTag() << " node " << Nd4 << "does not exist in the model\n"; return; } // Get number of DOF and the dimension int dofNd1 = theNodes[0]->getNumberDOF(); int dofNd2 = theNodes[1]->getNumberDOF(); int dofNd3 = theNodes[2]->getNumberDOF(); int dofNd4 = theNodes[3]->getNumberDOF(); // If differing DOF at the nodes - print a warning message if ((dofNd1 != dofNd2) || (dofNd2 != dofNd3) || (dofNd3 != dofNd4)) opserr << "WARNING StringPanelLin::setDomain(): nodes have differing DOF" << endln; // Call the base class method this->DomainComponent::setDomain(theDomain); // Set the number of dof for element and matrix and vector pointers if (dimension == 2 && dofNd1 == 2) { numDOF = 8; theMatrix = &stiff8; theVector = &resid8; } else if (dimension == 2 && dofNd1 == 3) { numDOF = 12; theMatrix = &stiff12; theVector = &resid12; } else if (dimension == 3 && dofNd1 == 6) { numDOF = 24; theMatrix = &stiff24; theVector = &resid24; } else { opserr << "WARNING StringPanelLin::setDomain cannot handle " << dofNd1 << " dofs at nodes in " << dimension << " dimension problem\n"; return; } // Get length of 4 edges and end displacements const Vector& end1Crd = theNodes[0]->getCrds(); const Vector& end2Crd = theNodes[1]->getCrds(); const Vector& end3Crd = theNodes[2]->getCrds(); const Vector& end4Crd = theNodes[3]->getCrds(); // Vertices (counterclockwise) const Vector& end1Disp = theNodes[0]->getDisp(); const Vector& end2Disp = theNodes[1]->getDisp(); const Vector& end3Disp = theNodes[2]->getDisp(); const Vector& end4Disp = theNodes[3]->getDisp(); // 2 dimension case if (dimension == 2) { dx[0] = end2Crd(0) - end1Crd(0); dx[1] = end3Crd(0) - end2Crd(0); dx[2] = end4Crd(0) - end3Crd(0); dx[3] = end1Crd(0) - end4Crd(0); dy[0] = end2Crd(1) - end1Crd(1); dy[1] = end3Crd(1) - end2Crd(1); dy[2] = end4Crd(1) - end3Crd(1); dy[3] = end1Crd(1) - end4Crd(1); dz[0] = 0.0; dz[1] = 0.0; dz[2] = 0.0; dz[3] = 0.0; for (int i = 0; i < 4; i++) L[i] = sqrt(dx[i] * dx[i] + dy[i] * dy[i]); if (initialDisp == 0) { double iDispX[4]; double iDispY[4]; iDispX[0] = end2Disp(0) - end1Disp(0); iDispX[1] = end3Disp(0) - end2Disp(0); iDispX[2] = end4Disp(0) - end3Disp(0); iDispX[3] = end1Disp(0) - end4Disp(0); iDispY[0] = end2Disp(1) - end1Disp(1); iDispY[1] = end3Disp(1) - end2Disp(1); iDispY[2] = end4Disp(1) - end3Disp(1); iDispY[3] = end1Disp(1) - end4Disp(1); for (int i = 0; i < 4; i++) { if (iDispX[i] != 0 || iDispY[i] != 0) { initialDisp = new double[8]; for (int j = 0; j < 4; j++) { initialDisp[j * 2] = iDispX[j]; initialDisp[j * 2 + 1] = iDispY[j]; } break; } } } } // 3 dimension case if (dimension == 3) { dx[0] = end2Crd(0) - end1Crd(0); dx[1] = end3Crd(0) - end2Crd(0); dx[2] = end4Crd(0) - end3Crd(0); dx[3] = end1Crd(0) - end4Crd(0); dy[0] = end2Crd(1) - end1Crd(1); dy[1] = end3Crd(1) - end2Crd(1); dy[2] = end4Crd(1) - end3Crd(1); dy[3] = end1Crd(1) - end4Crd(1); dz[0] = end2Crd(2) - end1Crd(2); dz[1] = end3Crd(2) - end2Crd(2); dz[2] = end4Crd(2) - end3Crd(2); dz[3] = end1Crd(2) - end4Crd(2); for (int i = 0; i < 4; i++) L[i] = sqrt(dx[i] * dx[i] + dy[i] * dy[i] + dz[i] * dz[i]); if (initialDisp == 0) { double iDispX[8]; double iDispY[8]; double iDispZ[8]; iDispX[0] = end2Disp(0) - end1Disp(0); iDispX[1] = end3Disp(0) - end2Disp(0); iDispX[2] = end4Disp(0) - end3Disp(0); iDispX[3] = end1Disp(0) - end4Disp(0); iDispY[0] = end2Disp(1) - end1Disp(1); iDispY[1] = end3Disp(1) - end2Disp(1); iDispY[2] = end4Disp(1) - end3Disp(1); iDispY[3] = end1Disp(1) - end4Disp(1); iDispZ[0] = end2Disp(2) - end1Disp(2); iDispZ[1] = end3Disp(2) - end2Disp(2); iDispZ[2] = end4Disp(2) - end3Disp(2); iDispZ[3] = end1Disp(2) - end4Disp(2); for (int i = 0; i < 4; i++) { if (iDispX[i] != 0 || iDispY[i] != 0 || iDispZ[i] != 0) { initialDisp = new double[12]; for (int j = 0; j < 4; j++) { initialDisp[j * 3] = iDispX[j]; initialDisp[j * 3 + 1] = iDispY[j]; initialDisp[j * 3 + 2] = iDispZ[j]; } break; } } } // Verify the nodes are coplanar static Vector AB(3); static Vector AD(3); static Vector AC(3); static Vector temp(3); AB = end2Crd; AB -= end1Crd; AD = end4Crd; AD -= end1Crd; AC = end3Crd; AC -= end1Crd; temp = LovelyCrossProduct(AB, AD); double val = LovelyInnerProduct(temp, AC); double temp2 = LovelyNorm(temp); if (fabs(val) > 0.0001*temp2) // Dealing with tolerances to allow for double issues { opserr << "WARNING StringPanelLin::setDomain() - StringerPanel " << this->getTag() << " is not coplanar\n"; return; } } // Create the load vector ----- if (theLoad == 0) theLoad = new Vector(numDOF); else if (theLoad->Size() != numDOF) { delete theLoad; theLoad = new Vector(numDOF); } if (theLoad == 0) { opserr << "StringPanelLin::setDomain - StringPanel " << this->getTag() << " out of memory creating vector of size " << numDOF << endln; exit(-1); return; } this->update(); } int StringPanelLin::commitState() { int retVal = 0; if ((retVal = this->Element::commitState()) != 0) opserr << "StringPanelLin::commitState () - failed in base class"; retVal += theSection1_1->commitState(); retVal += theSection1_2->commitState(); retVal += theSection1_3->commitState(); retVal += theSection2_1->commitState(); retVal += theSection2_2->commitState(); retVal += theSection2_3->commitState(); retVal += theSection3_1->commitState(); retVal += theSection3_2->commitState(); retVal += theSection3_3->commitState(); retVal += theSection4_1->commitState(); retVal += theSection4_2->commitState(); retVal += theSection4_3->commitState(); return retVal; } int StringPanelLin::revertToLastCommit() { int retVal = 0; retVal += theSection1_1->revertToLastCommit(); retVal += theSection1_2->revertToLastCommit(); retVal += theSection1_3->revertToLastCommit(); retVal += theSection2_1->revertToLastCommit(); retVal += theSection2_2->revertToLastCommit(); retVal += theSection2_3->revertToLastCommit(); retVal += theSection3_1->revertToLastCommit(); retVal += theSection3_2->revertToLastCommit(); retVal += theSection3_3->revertToLastCommit(); retVal += theSection4_1->revertToLastCommit(); retVal += theSection4_2->revertToLastCommit(); retVal += theSection4_3->revertToLastCommit(); return retVal; } int StringPanelLin::revertToStart() { int retVal = 0; retVal += theSection1_1->revertToStart(); retVal += theSection1_2->revertToStart(); retVal += theSection1_3->revertToStart(); retVal += theSection2_1->revertToStart(); retVal += theSection2_2->revertToStart(); retVal += theSection2_3->revertToStart(); retVal += theSection3_1->revertToStart(); retVal += theSection3_2->revertToStart(); retVal += theSection3_3->revertToStart(); retVal += theSection4_1->revertToStart(); retVal += theSection4_2->revertToStart(); retVal += theSection4_3->revertToStart(); return retVal; } int StringPanelLin::update() { // determine the current strain given trial displacements at nodes // CURRENTLY HAS TWO INTEGRATION POINTS, EACH INTEGRATION POINT DEFINES THE // GENERALIZED STRAINS e1 AND e2 IN HOOGENBOOM'S FORMULATION AND DETERMINES // THE STIFFNESS MATRIX AND FORCES WITH THOSE TWO. THE GENERALIZED STRAINS // e1 AND e2 ARE COMPUTED CONSIDERING HALF THE LENGTH. static Vector strain; strain = computeCurrentStrain(); // First stringer int order1 = theSection1_1->getOrder(); const ID& code1 = theSection1_1->getType(); Vector e1_1(order1); Vector e1_2(order1); Vector e1_3(order1); for (int j = 0; j < order1; j++) { if (code1(j) == SECTION_RESPONSE_P) { e1_1(j) = strain(0); e1_2(j) = 0.5 * strain(0) + 0.5 * strain(1); e1_3(j) = strain(1); } } theSection1_1->setTrialSectionDeformation(e1_1); theSection1_2->setTrialSectionDeformation(e1_2); theSection1_3->setTrialSectionDeformation(e1_3); // Second stringer int order2 = theSection2_1->getOrder(); const ID& code2 = theSection2_1->getType(); Vector e2_1(order2); Vector e2_2(order2); Vector e2_3(order2); for (int j = 0; j < order2; j++) { if (code2(j) == SECTION_RESPONSE_P) { e2_1(j) = strain(2); e2_2(j) = 0.5 * strain(2) + 0.5 * strain(3); e2_3(j) = strain(3); } } theSection2_1->setTrialSectionDeformation(e2_1); theSection2_2->setTrialSectionDeformation(e2_2); theSection2_3->setTrialSectionDeformation(e2_3); // Third stringer int order3 = theSection3_1->getOrder(); const ID& code3 = theSection3_1->getType(); Vector e3_1(order3); Vector e3_2(order3); Vector e3_3(order3); for (int j = 0; j < order3; j++) { if (code3(j) == SECTION_RESPONSE_P) { e3_1(j) = strain(4); e3_2(j) = 0.5 * strain(4) + 0.5 * strain(5); e3_3(j) = strain(5); } } theSection3_1->setTrialSectionDeformation(e3_1); theSection3_2->setTrialSectionDeformation(e3_2); theSection3_3->setTrialSectionDeformation(e3_3); // Fourth stringer int order4 = theSection4_1->getOrder(); const ID& code4 = theSection4_1->getType(); Vector e4_1(order4); Vector e4_2(order4); Vector e4_3(order4); for (int j = 0; j < order4; j++) { if (code4(j) == SECTION_RESPONSE_P) { e4_1(j) = strain(6); e4_2(j) = 0.5 * strain(6) + 0.5 * strain(7); e4_3(j) = strain(7); } } theSection4_1->setTrialSectionDeformation(e4_1); theSection4_2->setTrialSectionDeformation(e4_2); theSection4_3->setTrialSectionDeformation(e4_3); return 0; } const Matrix& StringPanelLin::getInitialStiff(void) { Matrix& stiff = *theMatrix; // Stringers stiffness matrix static Matrix k1(3, 3); static Matrix k2(3, 3); static Matrix k3(3, 3); static Matrix k4(3, 3); k1(0, 0) = 4.0; k1(0, 1) = -6.0; k1(0, 2) = 2.0; k1(1, 0) = -6.0; k1(1, 1) = 12.0; k1(1, 2) = -6.0; k1(2, 0) = 2.0; k1(2, 1) = -6.0; k1(2, 2) = 4.0; k2 = k1; k3 = k1; k4 = k1; double AEoverL[4]; // Currently the element only allows for a constant section in each stringer // The initial stiffness is computed based on one unique section of the stringer // regardles of having 2 integration points // Stringer 1 AEoverL[0] = 0.0; int order1 = theSection1_1->getOrder(); const ID& code1 = theSection1_1->getType(); const Matrix& k_1 = theSection1_1->getInitialTangent(); for (int j = 0; j < order1; j++) { if (code1(j) == SECTION_RESPONSE_P) AEoverL[0] += k_1(j, j); } AEoverL[0] /= L[0]; // Stringer 2 AEoverL[1] = 0.0; int order2 = theSection2_1->getOrder(); const ID& code2 = theSection2_1->getType(); const Matrix& k_2 = theSection2_1->getInitialTangent(); for (int j = 0; j < order2; j++) { if (code2(j) == SECTION_RESPONSE_P) AEoverL[1] += k_2(j, j); } AEoverL[1] /= L[1]; // Stringer 3 AEoverL[2] = 0.0; int order3 = theSection3_1->getOrder(); const ID& code3 = theSection3_1->getType(); const Matrix& k_3 = theSection3_1->getInitialTangent(); for (int j = 0; j < order3; j++) { if (code3(j) == SECTION_RESPONSE_P) AEoverL[2] += k_3(j, j); } AEoverL[2] /= L[2]; // Stringer 4 AEoverL[3] = 0.0; int order4 = theSection4_1->getOrder(); const ID& code4 = theSection4_1->getType(); const Matrix& k_4 = theSection4_1->getInitialTangent(); for (int j = 0; j < order4; j++) { if (code4(j) == SECTION_RESPONSE_P) AEoverL[3] += k_4(j, j); } AEoverL[3] /= L[3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { k1(i, j) *= AEoverL[0]; k2(i, j) *= AEoverL[1]; k3(i, j) *= AEoverL[2]; k4(i, j) *= AEoverL[3]; } } // Assemble stiffness matrix, panel contribution and transformation within function stiff = assembleK(k1, k2, k3, k4); return *theMatrix; } const Matrix& StringPanelLin::getTangentStiff(void) { Matrix& stiff = *theMatrix; // Stringers stiffness matrix static Matrix k1(3, 3); static Matrix k2(3, 3); static Matrix k3(3, 3); static Matrix k4(3, 3); k1.Zero(); k2.Zero(); k3.Zero(); k4.Zero(); double LoverEA[12]; // Array to save tangent flexibility values // Stringer 1 LoverEA[0] = L[0]; LoverEA[1] = L[0]; LoverEA[2] = L[0]; int order1 = theSection1_1->getOrder(); const ID& code1 = theSection1_1->getType(); const Matrix& f1_1 = theSection1_1->getSectionTangent(); const Matrix& f1_2 = theSection1_2->getSectionTangent(); const Matrix& f1_3 = theSection1_3->getSectionTangent(); for (int j = 0; j < order1; j++) { if (code1(j) == SECTION_RESPONSE_P) { LoverEA[0] /= (6*f1_1(j, j)); LoverEA[1] /= (6*f1_2(j, j)); LoverEA[2] /= (6*f1_3(j, j)); } } // Stringer 2 LoverEA[3] = L[1]; LoverEA[4] = L[1]; LoverEA[5] = L[1]; int order2 = theSection2_1->getOrder(); const ID& code2 = theSection2_1->getType(); const Matrix& f2_1 = theSection2_1->getSectionTangent(); const Matrix& f2_2 = theSection2_2->getSectionTangent(); const Matrix& f2_3 = theSection2_3->getSectionTangent(); for (int j = 0; j < order2; j++) { if (code2(j) == SECTION_RESPONSE_P) { LoverEA[3] /= (6*f2_1(j, j)); LoverEA[4] /= (6*f2_2(j, j)); LoverEA[5] /= (6*f2_3(j, j)); } } // Stringer 3 LoverEA[6] = L[2]; LoverEA[7] = L[2]; LoverEA[8] = L[2]; int order3 = theSection3_1->getOrder(); const ID& code3 = theSection3_1->getType(); const Matrix& f3_1 = theSection3_1->getSectionTangent(); const Matrix& f3_2 = theSection3_2->getSectionTangent(); const Matrix& f3_3 = theSection3_3->getSectionTangent(); for (int j = 0; j < order3; j++) { if (code2(j) == SECTION_RESPONSE_P) { LoverEA[6] /= (6*f3_1(j, j)); LoverEA[7] /= (6*f3_2(j, j)); LoverEA[8] /= (6*f3_3(j, j)); } } // Stringer 4 LoverEA[9] = L[3]; LoverEA[10] = L[3]; LoverEA[11] = L[3]; int order4 = theSection4_1->getOrder(); const ID& code4 = theSection4_1->getType(); const Matrix& f4_1 = theSection4_1->getSectionTangent(); const Matrix& f4_2 = theSection4_2->getSectionTangent(); const Matrix& f4_3 = theSection4_3->getSectionTangent(); for (int j = 0; j < order4; j++) { if (code2(j) == SECTION_RESPONSE_P) { LoverEA[9] /= (6*f4_1(j, j)); LoverEA[10] /= (6*f4_2(j, j)); LoverEA[11] /= (6*f4_3(j, j)); } } // Stringers flexibility matrix static Matrix f1(2, 2); static Matrix f2(2, 2); static Matrix f3(2, 2); static Matrix f4(2, 2); f1.Zero(); f2.Zero(); f3.Zero(); f4.Zero(); f1(0, 0) = LoverEA[0] + LoverEA[1]; f1(0, 1) = LoverEA[1]; f1(1, 0) = LoverEA[1]; f1(1, 1) = LoverEA[1] + LoverEA[2]; f2(0, 0) = LoverEA[3] + LoverEA[4]; f2(0, 1) = LoverEA[4]; f2(1, 0) = LoverEA[4]; f2(1, 1) = LoverEA[4] + LoverEA[5]; f3(0, 0) = LoverEA[6] + LoverEA[7]; f3(0, 1) = LoverEA[7]; f3(1, 0) = LoverEA[7]; f3(1, 1) = LoverEA[7] + LoverEA[8]; f4(0, 0) = LoverEA[9] + LoverEA[10]; f4(0, 1) = LoverEA[10]; f4(1, 0) = LoverEA[10]; f4(1, 1) = LoverEA[10] + LoverEA[11]; // Inverse of flexibility matrix static Matrix kf1(2, 2); static Matrix kf2(2, 2); static Matrix kf3(2, 2); static Matrix kf4(2, 2); f1.Invert(kf1); f2.Invert(kf2); f3.Invert(kf3); f4.Invert(kf4); // B'*D*B k1(0, 0) = kf1(0, 0); k1(0, 1) = kf1(0, 1) - kf1(0, 0); k1(0, 2) = -kf1(0, 1); k1(1, 0) = kf1(0, 1) - kf1(0, 0); k1(1, 1) = kf1(0, 0) - kf1(1, 0) - kf1(0, 1) + kf1(1, 1); k1(1, 2) = kf1(0, 1) - kf1(1, 1); k1(2, 0) = -kf1(1, 0); k1(2, 1) = kf1(1, 0) - kf1(1, 1); k1(2, 2) = kf1(1, 1); k2(0, 0) = kf2(0, 0); k2(0, 1) = kf2(0, 1) - kf2(0, 0); k2(0, 2) = -kf2(0, 1); k2(1, 0) = kf2(0, 1) - kf2(0, 0); k2(1, 1) = kf2(0, 0) - kf2(1, 0) - kf2(0, 1) + kf2(1, 1); k2(1, 2) = kf2(0, 1) - kf2(1, 1); k2(2, 0) = -kf2(1, 0); k2(2, 1) = kf2(1, 0) - kf2(1, 1); k2(2, 2) = kf2(1, 1); k3(0, 0) = kf3(0, 0); k3(0, 1) = kf3(0, 1) - kf3(0, 0); k3(0, 2) = -kf3(0, 1); k3(1, 0) = kf3(0, 1) - kf3(0, 0); k3(1, 1) = kf3(0, 0) - kf3(1, 0) - kf3(0, 1) + kf3(1, 1); k3(1, 2) = kf3(0, 1) - kf3(1, 1); k3(2, 0) = -kf3(1, 0); k3(2, 1) = kf3(1, 0) - kf3(1, 1); k3(2, 2) = kf3(1, 1); k4(0, 0) = kf4(0, 0); k4(0, 1) = kf4(0, 1) - kf4(0, 0); k4(0, 2) = -kf4(0, 1); k4(1, 0) = kf4(0, 1) - kf4(0, 0); k4(1, 1) = kf4(0, 0) - kf4(1, 0) - kf4(0, 1) + kf4(1, 1); k4(1, 2) = kf4(0, 1) - kf4(1, 1); k4(2, 0) = -kf4(1, 0); k4(2, 1) = kf4(1, 0) - kf4(1, 1); k4(2, 2) = kf4(1, 1); // Assemble stiffness matrix, panel contribution and transformation within function stiff = assembleK(k1, k2, k3, k4); return *theMatrix; } // Lumped mass matrix const Matrix& StringPanelLin::getMass() { // zero the matrix Matrix& mass = *theMatrix; mass.Zero(); // check if no rho was specified for quick return if (rho == 0.0) return mass; // get lumped mass matrix double Area = getPanelArea(); double m = 0.25 * rho * Area; int numDOF4 = numDOF / 4; for (int i = 0; i < dimension; i++) { mass(i, i) = m; mass(i + numDOF4, i + numDOF4) = m; mass(i + numDOF4 * 2, i + numDOF4 * 2) = m; mass(i + numDOF4 * 3, i + numDOF4 * 3) = m; } return mass; } void StringPanelLin::zeroLoad() { theLoad->Zero(); } // The element does not allow for applied loads to the stringers or panels, only nodal loads int StringPanelLin::addLoad(ElementalLoad* theLoad, double loadFactor) { opserr << "StringPanelLin::addLoad - load type unknown for StringPanelLin with tag: " << this->getTag() << endln; return -1; } int StringPanelLin::addInertiaLoadToUnbalance(const Vector &accel) { // check for quick return if (rho == 0.0) return 0; // get R*accel from the nodes const Vector& Raccel1 = theNodes[0]->getRV(accel); const Vector& Raccel2 = theNodes[1]->getRV(accel); const Vector& Raccel3 = theNodes[2]->getRV(accel); const Vector& Raccel4 = theNodes[3]->getRV(accel); // get mass value at each node double Area = getPanelArea(); double m = 0.25 * rho * Area; int numDOF4 = numDOF / 4; // get average acceleration at centroid of element double ave_accel[3] = { 0.0 }; if (dimension == 2) { ave_accel[0] = (Raccel1(0) + Raccel2(0) + Raccel3(0) + Raccel4(0)) / 4.; ave_accel[1] = (Raccel1(1) + Raccel2(1) + Raccel3(1) + Raccel4(1)) / 4.; } else { ave_accel[0] = (Raccel1(0) + Raccel2(0) + Raccel3(0) + Raccel4(0)) / 4.; ave_accel[1] = (Raccel1(1) + Raccel2(1) + Raccel3(1) + Raccel4(1)) / 4.; ave_accel[2] = (Raccel1(2) + Raccel2(2) + Raccel3(2) + Raccel4(2)) / 4.; } // add inertial load for (int i = 0; i < dimension; i++) { (*theLoad)(i) -= m * ave_accel[i]; (*theLoad)(i + numDOF4) -= m * ave_accel[i]; (*theLoad)(i + numDOF4 * 2) -= m * ave_accel[i]; (*theLoad)(i + numDOF4 * 3) -= m * ave_accel[i]; } return 0; } const Vector& StringPanelLin::getResistingForce() { static Vector fStringers(12); fStringers.Zero(); fStringers = getLocalForce(); static Vector fReduced(8); // Only the nodal forces fReduced(0) = fStringers(0); fReduced(1) = fStringers(2); fReduced(2) = fStringers(3); fReduced(3) = fStringers(5); fReduced(4) = fStringers(6); fReduced(5) = fStringers(8); fReduced(6) = fStringers(9); fReduced(7) = fStringers(11); // Transform into global coordinates static Matrix T(8, numDOF); static Vector fGlobal(numDOF); T = transformMatrix(); fGlobal.addMatrixTransposeVector(0.0, T, fReduced, 1.0); *theVector = fGlobal; // subtract external load *theVector -= *theLoad; return *theVector; } const Vector& StringPanelLin::getResistingForceIncInertia() { this->getResistingForce(); // Include the mass portion if (rho != 0.0) { // add inertial forces from element mass const Vector& accel1 = theNodes[0]->getTrialAccel(); const Vector& accel2 = theNodes[1]->getTrialAccel(); const Vector& accel3 = theNodes[2]->getTrialAccel(); const Vector& accel4 = theNodes[3]->getTrialAccel(); // get mass value at each node double Area = getPanelArea(); double m = 0.25 * rho * Area; int numDOF4 = numDOF / 4; // get average acceleration at centroid of element double ave_accel[3] = { 0.0 }; if (dimension == 2) { ave_accel[0] = (accel1(0) + accel2(0) + accel3(0) + accel4(0)) / 4.; ave_accel[1] = (accel1(1) + accel2(1) + accel3(1) + accel4(1)) / 4.; } else { ave_accel[0] = (accel1(0) + accel2(0) + accel3(0) + accel4(0)) / 4.; ave_accel[1] = (accel1(1) + accel2(1) + accel3(1) + accel4(1)) / 4.; ave_accel[2] = (accel1(2) + accel2(2) + accel3(2) + accel4(2)) / 4.; } //// add inertial load (average acceleration) for (int i = 0; i < dimension; i++) { (*theVector)(i) += m * ave_accel[i]; (*theVector)(i + numDOF4) += m * ave_accel[i]; (*theVector)(i + numDOF4 * 2) += m * ave_accel[i]; (*theVector)(i + numDOF4 * 3) += m * ave_accel[i]; } // add inertial load (1/4 of the mass at each corner) //for (int i = 0; i < dimension; i++) { // (*theVector)(i) += m * accel1(i); // (*theVector)(i + numDOF4) += m * accel2(i); // (*theVector)(i + numDOF4 * 2) += m * accel3(i); // (*theVector)(i + numDOF4 * 3) += m * accel4(i); //} // add the damping forces if rayleigh damping if (alphaM != 0.0 || betaK != 0.0 || betaK0 != 0.0 || betaKc != 0.0) *theVector += this->getRayleighDampingForces(); } return *theVector; } int StringPanelLin::sendSelf(int commitTag, Channel& theChannel) { int res; // note: we don't check for dataTag == 0 for Element // objects as that is taken care of in a commit by the Domain // object - don't want to have to do the check if sending data int dataTag = this->getDbTag(); // Get an ID for the sections static ID idSections(16); // Stringer 1_1 int sectClassTag1_1 = theSection1_1->getClassTag(); int sectDbTag1_1 = theSection1_1->getDbTag(); if (sectDbTag1_1 == 0) { sectDbTag1_1 = theChannel.getDbTag(); theSection1_1->setDbTag(sectDbTag1_1); } idSections(0) = sectClassTag1_1; idSections(1) = sectDbTag1_1; // Stringer 1_2 int sectClassTag1_2 = theSection1_2->getClassTag(); int sectDbTag1_2 = theSection1_2->getDbTag(); if (sectDbTag1_2 == 0) { sectDbTag1_2 = theChannel.getDbTag(); theSection1_2->setDbTag(sectDbTag1_2); } idSections(2) = sectClassTag1_2; idSections(3) = sectDbTag1_2; // Stringer 2_1 int sectClassTag2_1 = theSection2_1->getClassTag(); int sectDbTag2_1 = theSection2_1->getDbTag(); if (sectDbTag2_1 == 0) { sectDbTag2_1 = theChannel.getDbTag(); theSection2_1->setDbTag(sectDbTag2_1); } idSections(4) = sectClassTag2_1; idSections(5) = sectDbTag2_1; // Stringer 2_2 int sectClassTag2_2 = theSection2_2->getClassTag(); int sectDbTag2_2 = theSection2_2->getDbTag(); if (sectDbTag2_2 == 0) { sectDbTag2_2 = theChannel.getDbTag(); theSection2_2->setDbTag(sectDbTag2_2); } idSections(6) = sectClassTag2_2; idSections(7) = sectDbTag2_2; // Stringer 3_1 int sectClassTag3_1 = theSection3_1->getClassTag(); int sectDbTag3_1 = theSection3_1->getDbTag(); if (sectDbTag3_1 == 0) { sectDbTag3_1 = theChannel.getDbTag(); theSection3_1->setDbTag(sectDbTag3_1); } idSections(8) = sectClassTag3_1; idSections(9) = sectDbTag3_1; // Stringer 3_2 int sectClassTag3_2 = theSection3_2->getClassTag(); int sectDbTag3_2 = theSection3_2->getDbTag(); if (sectDbTag3_2 == 0) { sectDbTag3_2 = theChannel.getDbTag(); theSection3_2->setDbTag(sectDbTag3_2); } idSections(10) = sectClassTag3_2; idSections(11) = sectDbTag3_2; // Stringer 4_1 int sectClassTag4_1 = theSection4_1->getClassTag(); int sectDbTag4_1 = theSection4_1->getDbTag(); if (sectDbTag4_1 == 0) { sectDbTag4_1 = theChannel.getDbTag(); theSection4_1->setDbTag(sectDbTag4_1); } idSections(12) = sectClassTag4_1; idSections(13) = sectDbTag4_1; // Stringer 4_2 int sectClassTag4_2 = theSection4_2->getClassTag(); int sectDbTag4_2 = theSection4_2->getDbTag(); if (sectDbTag4_2 == 0) { sectDbTag4_2 = theChannel.getDbTag(); theSection4_2->setDbTag(sectDbTag4_2); } idSections(14) = sectClassTag4_2; idSections(15) = sectDbTag4_2; res = theChannel.sendID(dataTag, commitTag, idSections); if (res < 0) { opserr << "WARNING StringPanelLin::sendSelf() - " << this->getTag() << " failed to send idSections\n"; return res; } // Data ID static ID idData(7); idData(0) = this->getTag(); idData(1) = dimension; idData(2) = numDOF; for (int i = 0; i < 4; i++) idData(i + 3) = connectedExternalNodes(i); res += theChannel.sendID(dataTag, commitTag, idData); if (res < 0) { opserr << "WARNING StringPanelLin::sendSelf() - " << this->getTag() << " failed to send idData\n"; return res; } // Initial displacement ID int temp = dimension * 4; static Vector initialDispID(temp); if (dimension == 2) for (int j = 0; j < 4; j++) { initialDispID(j * 2) = initialDisp[j * 2]; initialDispID(j * 2 + 1) = initialDisp[j * 2 + 1]; } else if (dimension == 3) for (int j = 0; j < 4; j++) { initialDispID(j * 3) = initialDisp[j * 3]; initialDispID(j * 3 + 1) = initialDisp[j * 3 + 1]; initialDispID(j * 3 + 2) = initialDisp[j * 3 + 2]; } res += theChannel.sendVector(dataTag, commitTag, initialDispID); if (res < 0) { opserr << "WARNING StringPanelLin::sendSelf() - " << this->getTag() << " failed to send initialDispID\n"; return res; } // Ask sections to send themselves res += theSection1_1->sendSelf(commitTag, theChannel); res += theSection1_2->sendSelf(commitTag, theChannel); res += theSection2_1->sendSelf(commitTag, theChannel); res += theSection2_2->sendSelf(commitTag, theChannel); res += theSection3_1->sendSelf(commitTag, theChannel); res += theSection3_2->sendSelf(commitTag, theChannel); res += theSection4_1->sendSelf(commitTag, theChannel); res += theSection4_2->sendSelf(commitTag, theChannel); if (res < 0) { opserr << "WARNING StringPanelLin::sendSelf() - " << this->getTag() << " failed to send its sections\n"; return res; } return res; } int StringPanelLin::recvSelf(int commitTag, Channel& theChannel, FEM_ObjectBroker& theBroker) { int res; int dataTag = this->getDbTag(); static ID idSections(16); res = theChannel.recvID(dataTag, commitTag, idSections); if (res < 0) { opserr << "WARNING StringPanelLin::recvSelf() - " << this->getTag() << " failed to receive sections\n"; return res; } // Section 1_1 if (theSection1_1 == 0) { int sectClassTag1_1 = idSections(0); int sectDbTag1_1 = idSections(1); theSection1_1 = theBroker.getNewSection(sectClassTag1_1); if (theSection1_1 == 0) { opserr << "StringPanelLin::recvSelf() - Broker could not create a section of class type " << sectClassTag1_1 << endln; return -1; } theSection1_1->setDbTag(sectDbTag1_1); res += theSection1_1->recvSelf(commitTag, theChannel, theBroker); } else { int sectClassTag1_1 = idSections(0); int sectDbTag1_1 = idSections(1); if (theSection1_1->getClassTag() != sectClassTag1_1) { delete theSection1_1; theSection1_1 = theBroker.getNewSection(sectClassTag1_1); if (theSection1_1 == 0) { opserr << "StringPanelLin::recvSelf() - Broker could not create a section of class type " << sectClassTag1_1 << endln; return -1; } } theSection1_1->setDbTag(sectDbTag1_1); res += theSection1_1->recvSelf(commitTag, theChannel, theBroker); } // Section 1_2 if (theSection1_2 == 0) { int sectClassTag1_2 = idSections(2); int sectDbTag1_2 = idSections(3); theSection1_2 = theBroker.getNewSection(sectClassTag1_2); if (theSection1_2 == 0) { opserr << "StringPanelLin::recvSelf() - Broker could not create a section of class type " << sectClassTag1_2 << endln; return -1; } theSection1_2->setDbTag(sectDbTag1_2); res += theSection1_2->recvSelf(commitTag, theChannel, theBroker); } else { int sectClassTag1_2 = idSections(2); int sectDbTag1_2 = idSections(3); if (theSection1_2->getClassTag() != sectClassTag1_2) { delete theSection1_2; theSection1_2 = theBroker.getNewSection(sectClassTag1_2); if (theSection1_2 == 0) { opserr << "StringPanelLin::recvSelf() - Broker could not create a section of class type " << sectClassTag1_2 << endln; return -1; } } theSection1_2->setDbTag(sectDbTag1_2); res += theSection1_2->recvSelf(commitTag, theChannel, theBroker); } // Section 2_1 if (theSection2_1 == 0) { int sectClassTag2_1 = idSections(4); int sectDbTag2_1 = idSections(5); theSection2_1 = theBroker.getNewSection(sectClassTag2_1); if (theSection2_1 == 0) { opserr << "StringPanelLin::recvSelf() - Broker could not create a section of class type " << sectClassTag2_1 << endln; return -1; } theSection2_1->setDbTag(sectDbTag2_1); res += theSection2_1->recvSelf(commitTag, theChannel, theBroker); } else { int sectClassTag2_1 = idSections(4); int sectDbTag2_1 = idSections(5); if (theSection2_1->getClassTag() != sectClassTag2_1) { delete theSection2_1; theSection2_1 = theBroker.getNewSection(sectClassTag2_1); if (theSection2_1 == 0) { opserr << "StringPanelLin::recvSelf() - Broker could not create a section of class type " << sectClassTag2_1 << endln; return -1; } } theSection2_1->setDbTag(sectDbTag2_1); res += theSection2_1->recvSelf(commitTag, theChannel, theBroker); } // Section 2_2 if (theSection2_2 == 0) { int sectClassTag2_2 = idSections(6); int sectDbTag2_2 = idSections(7); theSection2_2 = theBroker.getNewSection(sectClassTag2_2); if (theSection2_2 == 0) { opserr << "StringPanelLin::recvSelf() - Broker could not create a section of class type " << sectClassTag2_2 << endln; return -1; } theSection2_2->setDbTag(sectDbTag2_2); res += theSection2_2->recvSelf(commitTag, theChannel, theBroker); } else { int sectClassTag2_2 = idSections(6); int sectDbTag2_2 = idSections(7); if (theSection2_2->getClassTag() != sectClassTag2_2) { delete theSection2_2; theSection2_2 = theBroker.getNewSection(sectClassTag2_2); if (theSection2_2 == 0) { opserr << "StringPanelLin::recvSelf() - Broker could not create a section of class type " << sectClassTag2_2 << endln; return -1; } } theSection2_2->setDbTag(sectDbTag2_2); res += theSection2_2->recvSelf(commitTag, theChannel, theBroker); } // Section 3_1 if (theSection3_1 == 0) { int sectClassTag3_1 = idSections(8); int sectDbTag3_1 = idSections(9); theSection3_1 = theBroker.getNewSection(sectClassTag3_1); if (theSection3_1 == 0) { opserr << "StringPanelLin::recvSelf() - Broker could not create a section of class type " << sectClassTag3_1 << endln; return -1; } theSection3_1->setDbTag(sectDbTag3_1); res += theSection3_1->recvSelf(commitTag, theChannel, theBroker); } else { int sectClassTag3_1 = idSections(8); int sectDbTag3_1 = idSections(9); if (theSection3_1->getClassTag() != sectClassTag3_1) { delete theSection3_1; theSection3_1 = theBroker.getNewSection(sectClassTag3_1); if (theSection3_1 == 0) { opserr << "StringPanelLin::recvSelf() - Broker could not create a section of class type " << sectClassTag3_1 << endln; return -1; } } theSection3_1->setDbTag(sectDbTag3_1); res += theSection3_1->recvSelf(commitTag, theChannel, theBroker); } // Section 3_2 if (theSection3_2 == 0) { int sectClassTag3_2 = idSections(10); int sectDbTag3_2 = idSections(11); theSection3_2 = theBroker.getNewSection(sectClassTag3_2); if (theSection3_2 == 0) { opserr << "StringPanelLin::recvSelf() - Broker could not create a section of class type " << sectClassTag3_2 << endln; return -1; } theSection3_2->setDbTag(sectDbTag3_2); res += theSection3_2->recvSelf(commitTag, theChannel, theBroker); } else { int sectClassTag3_2 = idSections(10); int sectDbTag3_2 = idSections(11); if (theSection3_2->getClassTag() != sectClassTag3_2) { delete theSection3_2; theSection3_2 = theBroker.getNewSection(sectClassTag3_2); if (theSection3_2 == 0) { opserr << "StringPanelLin::recvSelf() - Broker could not create a section of class type " << sectClassTag3_2 << endln; return -1; } } theSection3_2->setDbTag(sectDbTag3_2); res += theSection3_2->recvSelf(commitTag, theChannel, theBroker); } // Section 4_1 if (theSection4_1 == 0) { int sectClassTag4_1 = idSections(12); int sectDbTag4_1 = idSections(13); theSection4_1 = theBroker.getNewSection(sectClassTag4_1); if (theSection4_1 == 0) { opserr << "StringPanelLin::recvSelf() - Broker could not create a section of class type " << sectClassTag4_1 << endln; return -1; } theSection4_1->setDbTag(sectDbTag4_1); res += theSection4_1->recvSelf(commitTag, theChannel, theBroker); } else { int sectClassTag4_1 = idSections(12); int sectDbTag4_1 = idSections(13); if (theSection4_1->getClassTag() != sectClassTag4_1) { delete theSection4_1; theSection4_1 = theBroker.getNewSection(sectClassTag4_1); if (theSection4_1 == 0) { opserr << "StringPanelLin::recvSelf() - Broker could not create a section of class type " << sectClassTag4_1 << endln; return -1; } } theSection4_1->setDbTag(sectDbTag4_1); res += theSection4_1->recvSelf(commitTag, theChannel, theBroker); } // Section 4_2 if (theSection4_2 == 0) { int sectClassTag4_2 = idSections(14); int sectDbTag4_2 = idSections(15); theSection4_2 = theBroker.getNewSection(sectClassTag4_2); if (theSection4_2 == 0) { opserr << "StringPanelLin::recvSelf() - Broker could not create a section of class type " << sectClassTag4_2 << endln; return -1; } theSection4_2->setDbTag(sectDbTag4_2); res += theSection4_2->recvSelf(commitTag, theChannel, theBroker); } else { int sectClassTag4_2 = idSections(14); int sectDbTag4_2 = idSections(15); if (theSection4_2->getClassTag() != sectClassTag4_2) { delete theSection4_2; theSection4_2 = theBroker.getNewSection(sectClassTag4_2); if (theSection4_2 == 0) { opserr << "StringPanelLin::recvSelf() - Broker could not create a section of class type " << sectClassTag4_2 << endln; return -1; } } theSection4_2->setDbTag(sectDbTag4_2); res += theSection4_2->recvSelf(commitTag, theChannel, theBroker); } // check if (res < 0) { opserr << "WARNING StringPanelLin::recvSelf() - a section failed to recv itself\n"; return res; } // Data ID static ID idData(7); res += theChannel.recvID(dataTag, commitTag, idData); if (res < 0) { opserr << "WARNING StringPanelLin::recvSelf() - failed to receive idData\n"; return res; } this->setTag((int)idData(0)); dimension = (int)idData(1); numDOF = (int)idData(2); for (int i = 0; i < 4; i++) connectedExternalNodes(i) = (int)idData(i + 3); // Initial displacement ID int temp = dimension * 4; static Vector initialDispID(temp); res += theChannel.recvVector(dataTag, commitTag, initialDispID); if (res < 0) { opserr << "WARNING StringPanelLin::recvSelf() - failed to receive initialDispID\n"; return res; } if (dimension == 2) for (int j = 0; j < 4; j++) { initialDisp[j * 2] = initialDispID(j * 2); initialDisp[j * 2 + 1] = initialDispID(j * 2 + 1); } else if (dimension == 3) for (int j = 0; j < 4; j++) { initialDisp[j * 3] = initialDispID(j * 3); initialDisp[j * 3 + 1] = initialDispID(j * 3 + 1); initialDisp[j * 3 + 2] = initialDispID(j * 3 + 2); } return res; } // Currently, no forces are printed out void StringPanelLin::Print(OPS_Stream& s, int flag) { if (flag == OPS_PRINT_CURRENTSTATE) { s << "\nStringPanelLin, element id: " << this->getTag() << endln; s << "\tCorner node 1: " << connectedExternalNodes(0); s << "\tCorner node 2: " << connectedExternalNodes(1); s << "\tCorner node 3: " << connectedExternalNodes(2); s << "\tCorner node 4: " << connectedExternalNodes(3); s << "\tSection 1: " << theSection1_1->getTag(); s << "\tSection 2: " << theSection2_1->getTag(); s << "\tSection 3: " << theSection3_1->getTag(); s << "\tSection 4: " << theSection4_1->getTag(); // s << "\tmass density: " << rho << endln; } if (flag == OPS_PRINT_PRINTMODEL_JSON) { s << "\t\t\t{"; s << "\"name\": " << this->getTag() << ", "; s << "\"type\": \"StringPanelLin\", "; s << "\"nodes\": [" << connectedExternalNodes(0) << ", "; s << connectedExternalNodes(1) << ", "; s << connectedExternalNodes(2) << ", "; s << connectedExternalNodes(3) << "], "; s << "\"Sections \": " << theSection1_1->getTag() << ", "; s << theSection2_1->getTag() << ", "; s << theSection3_1->getTag() << ", "; s << theSection4_1->getTag() << "\"}"; s << "\"massperarea\": " << rho << ". \n"; } } // Currently, no display mode for forces int StringPanelLin::displaySelf(Renderer& theViewer, int displayMode, float fact, const char** modes, int numMode) { static Vector v1(3); static Vector v2(3); static Vector v3(3); static Vector v4(3); if (displayMode >= 0) { theNodes[0]->getDisplayCrds(v1, fact); theNodes[1]->getDisplayCrds(v2, fact); theNodes[2]->getDisplayCrds(v3, fact); theNodes[3]->getDisplayCrds(v4, fact); } else { theNodes[0]->getDisplayCrds(v1, 0.); theNodes[1]->getDisplayCrds(v2, 0.); theNodes[2]->getDisplayCrds(v3, 0.); theNodes[3]->getDisplayCrds(v4, 0.); // add eigenvector values int mode = displayMode * -1; const Matrix& eigen1 = theNodes[0]->getEigenvectors(); const Matrix& eigen2 = theNodes[1]->getEigenvectors(); const Matrix& eigen3 = theNodes[2]->getEigenvectors(); const Matrix& eigen4 = theNodes[3]->getEigenvectors(); if (eigen1.noCols() >= mode) { for (int i = 0; i < 3; i++) { v1(i) += eigen1(i, mode - 1) * fact; v2(i) += eigen2(i, mode - 1) * fact; v3(i) += eigen3(i, mode - 1) * fact; v4(i) += eigen4(i, mode - 1) * fact; } } } static Matrix coords(4, 3); static Vector values(4); for (int i = 0; i < 3; i++) { coords(0, i) = v1(i); coords(1, i) = v2(i); coords(2, i) = v3(i); coords(3, i) = v4(i); } for (int i = 0; i < 4; i++) values(i) = 0.0; int error = 0; error += theViewer.drawPolygon(coords, values); return error; } Response* StringPanelLin::setResponse(const char** argv, int argc, OPS_Stream& output) { Response* theResponse = 0; output.tag("ElementOutput"); output.attr("eleType", "StringPanelLin"); output.attr("eleTag", this->getTag()); output.attr("cornerNode1", connectedExternalNodes[0]); output.attr("cornerNode2", connectedExternalNodes[1]); output.attr("cornerNode3", connectedExternalNodes[2]); output.attr("cornerNode4", connectedExternalNodes[3]); // compare argv[0] for known response types // global force if ((strcmp(argv[0], "forces") == 0) || (strcmp(argv[0], "force") == 0) || (strcmp(argv[0], "globalForce") == 0) || (strcmp(argv[0], "globalForces") == 0)) { char outputData[10]; int numDOFperNode = numDOF / 4; for (int i = 0; i < 4; i++) { for (int j = 0; j < numDOFperNode; j++) { sprintf(outputData, "P%d_%d", i + 1, j + 1); output.tag("ResponseType", outputData); } } theResponse = new ElementResponse(this, 1, Vector(numDOF)); } // local force (axial forces in stringers) only else if ((strcmp(argv[0], "localForce") == 0) || (strcmp(argv[0], "localForces") == 0) || (strcmp(argv[0], "axialForce") == 0) || (strcmp(argv[0], "axialForces") == 0)) { theResponse = new ElementResponse(this, 2, Vector(12)); } // shear flow else if (strcmp(argv[0], "shearFlow") == 0) { output.tag("ResponseType", "q"); theResponse = new ElementResponse(this, 3, Vector(1)); } // initial stiffness in local coordinates else if (strcmp(argv[0], "stiffness") == 0) { output.tag("ResponseType", "K"); theResponse = new ElementResponse(this, 4, Matrix(numDOF, numDOF)); } // global force including inertial terms only else if ((strcmp(argv[0], "inertialForce") == 0) || (strcmp(argv[0], "inertiaForce") == 0)) { char outputData[10]; int numDOFperNode = numDOF / 4; for (int i = 0; i < 4; i++) { for (int j = 0; j < numDOFperNode; j++) { sprintf(outputData, "P%d_%d", i + 1, j + 1); output.tag("ResponseType", outputData); } } theResponse = new ElementResponse(this, 5, Vector(numDOF)); } // strain of stringers included in r1.12 else if ((strcmp(argv[0], "strain") == 0) || (strcmp(argv[0], "strains") == 0)) { output.tag("ResponseType", "e"); theResponse = new ElementResponse(this, 6, Vector(12)); } // displacements for debugging purposes else if (strcmp(argv[0], "dispPanel") == 0) { output.tag("ResponseType", "e"); theResponse = new ElementResponse(this, 7, Vector(12)); } output.endTag(); return theResponse; } int StringPanelLin::getResponse(int responseID, Information& eleInfo) { switch (responseID) { case 1: // global force return eleInfo.setVector(this->getResistingForce()); case 2: // local force { static Vector localF(12); // Getting the forces in local coordinates only localF = getLocalForce(); // Changing the sign to match general sign convention in output for (int i = 6; i < 12; i++) localF(i) *= -1.; return eleInfo.setVector(localF); } case 3: // shear flow { static Vector qFlow(1); // Shear flow double pForces[4]; // Panel forces static Vector localF(12); localF = getLocalForce(); pForces[0] = localF(1); pForces[1] = localF(4); pForces[2] = localF(7); pForces[3] = localF(10); qFlow(0) = -pForces[0] / L[0]; qFlow(0) += pForces[1] / L[1]; qFlow(0) += -pForces[2] / L[2]; qFlow(0) += pForces[3] / L[3]; qFlow(0) /= 4; qFlow(0) *= -1; return eleInfo.setVector(qFlow); } case 4: // Initial stiffness Matrix { static Matrix globalK(numDOF, numDOF); globalK.Zero(); globalK = getInitialStiff(); return eleInfo.setMatrix(globalK); } case 5: // global force including inertial terms only { static Vector inertialForce(numDOF); inertialForce.Zero(); if (rho != 0.0) { // add inertial forces from element mass const Vector& accel1 = theNodes[0]->getTrialAccel(); const Vector& accel2 = theNodes[1]->getTrialAccel(); const Vector& accel3 = theNodes[2]->getTrialAccel(); const Vector& accel4 = theNodes[3]->getTrialAccel(); // get mass value at each node double Area = getPanelArea(); double m = 0.25 * rho * Area; int numDOF4 = numDOF / 4; // get average acceleration at centroid of element double ave_accel[3] = { 0.0 }; if (dimension == 2) { ave_accel[0] = (accel1(0) + accel2(0) + accel3(0) + accel4(0)) / 4.; ave_accel[1] = (accel1(1) + accel2(1) + accel3(1) + accel4(1)) / 4.; } else { ave_accel[0] = (accel1(0) + accel2(0) + accel3(0) + accel4(0)) / 4.; ave_accel[1] = (accel1(1) + accel2(1) + accel3(1) + accel4(1)) / 4.; ave_accel[2] = (accel1(2) + accel2(2) + accel3(2) + accel4(2)) / 4.; } // add inertial load (average acceleration) for (int i = 0; i < dimension; i++) { inertialForce(i) += m * ave_accel[i]; inertialForce(i + numDOF4) += m * ave_accel[i]; inertialForce(i + numDOF4 * 2) += m * ave_accel[i]; inertialForce(i + numDOF4 * 3) += m * ave_accel[i]; } // add the damping forces if rayleigh damping if (alphaM != 0.0 || betaK != 0.0 || betaK0 != 0.0 || betaKc != 0.0) inertialForce += this->getRayleighDampingForces(); } return eleInfo.setVector(inertialForce); } case 6: // average strains in stringers { static Vector strain(12); // Vector for stains Vector dLoverL = this->computeCurrentStrain(); strain(1) = 0.5 * dLoverL(0) + 0.5 * dLoverL(1); strain(4) = 0.5 * dLoverL(2) + 0.5 * dLoverL(3); strain(7) = 0.5 * dLoverL(4) + 0.5 * dLoverL(5); strain(10) = 0.5 * dLoverL(6) + 0.5 * dLoverL(7); strain(0) = dLoverL(0); strain(2) = dLoverL(1); strain(3) = dLoverL(2); strain(5) = dLoverL(3); strain(6) = dLoverL(4); strain(8) = dLoverL(5); strain(9) = dLoverL(6); strain(11) = dLoverL(7); return eleInfo.setVector(strain); } case 7: // displacements for debugging purposes { static Vector UnTotal(12); // Vector for displacements const Vector& disp1 = theNodes[0]->getTrialDisp(); const Vector& disp2 = theNodes[1]->getTrialDisp(); const Vector& disp3 = theNodes[2]->getTrialDisp(); const Vector& disp4 = theNodes[3]->getTrialDisp(); // Assemble displacements and transform in local coordinates static Vector Un(numDOF); static Matrix T(8, numDOF); static Vector UnLocal(8); Un.Zero(); if (numDOF == 8) { // dim = 2, dof = 2 Un(0) = disp1(0); Un(1) = disp1(1); Un(2) = disp2(0); Un(3) = disp2(1); Un(4) = disp3(0); Un(5) = disp3(1); Un(6) = disp4(0); Un(7) = disp4(1); if (initialDisp != 0) { for (int i = 0; i < 4; i++) { Un(i * 2) -= initialDisp[i * 2]; Un(i * 2 + 1) -= initialDisp[i * 2 + 1]; } } } else if (numDOF == 12) { // dim = 2, dof = 3 Un(0) = disp1(0); Un(1) = disp1(1); Un(3) = disp2(0); Un(4) = disp2(1); Un(6) = disp3(0); Un(7) = disp3(1); Un(9) = disp4(0); Un(10) = disp4(1); if (initialDisp != 0) { for (int i = 0; i < 4; i++) { Un(i * 3) -= initialDisp[i * 2]; Un(i * 3 + 1) -= initialDisp[i * 2 + 1]; } } } else { // dim = 3, dof = 6 Un(0) = disp1(0); Un(1) = disp1(1); Un(2) = disp1(2); Un(6) = disp2(0); Un(7) = disp2(1); Un(8) = disp2(2); Un(12) = disp3(0); Un(13) = disp3(1); Un(14) = disp3(2); Un(18) = disp4(0); Un(19) = disp4(1); Un(20) = disp4(2); if (initialDisp != 0) { for (int i = 0; i < 4; i++) { Un(i * 6) -= initialDisp[i * 3]; Un(i * 6 + 1) -= initialDisp[i * 3 + 1]; Un(i * 6 + 2) -= initialDisp[i * 3 + 2]; } } } // Transform into local coordinates T = transformMatrix(); UnLocal.addMatrixVector(0.0, T, Un, 1.0); // Get midpoint displacements in local coordinates static Vector Uo(4); Uo = getMidDisp(UnLocal); UnTotal(0) = UnLocal(0); UnTotal(2) = UnLocal(1); UnTotal(3) = UnLocal(2); UnTotal(5) = UnLocal(3); UnTotal(6) = UnLocal(4); UnTotal(8) = UnLocal(5); UnTotal(9) = UnLocal(6); UnTotal(11) = UnLocal(7); UnTotal(1) = Uo(0); UnTotal(4) = Uo(1); UnTotal(7) = Uo(2); UnTotal(10) = Uo(3); return eleInfo.setVector(UnTotal); } default: return -1; } } // Compute the strain at two integration points Vector StringPanelLin::computeCurrentStrain() { // CURRENTLY HAS TWO INTEGRATION POINTS, EACH INTEGRATION POINT DEFINES THE // GENERALIZED STRAINS e1 AND e2 IN HOOGENBOOM'S FORMULATION AND DETERMINES // THE STIFFNESS MATRIX AND FORCES WITH THOSE TWO. THE GENERALIZED STRAINS // e1 AND e2 ARE COMPUTED CONSIDERING HALF THE LENGTH. // determine the strain // Vertices (counterclockwise) const Vector& disp1 = theNodes[0]->getTrialDisp(); const Vector& disp2 = theNodes[1]->getTrialDisp(); const Vector& disp3 = theNodes[2]->getTrialDisp(); const Vector& disp4 = theNodes[3]->getTrialDisp(); static Vector dL_overL(8); // Assemble displacements and transform in local coordinates static Vector Un(numDOF); static Matrix T(8, numDOF); static Vector UnLocal(8); Un.Zero(); if (numDOF == 8) { // dim = 2, dof = 2 Un(0) = disp1(0); Un(1) = disp1(1); Un(2) = disp2(0); Un(3) = disp2(1); Un(4) = disp3(0); Un(5) = disp3(1); Un(6) = disp4(0); Un(7) = disp4(1); if (initialDisp != 0) { for (int i = 0; i < 4; i++) { Un(i * 2) -= initialDisp[i * 2]; Un(i * 2 + 1) -= initialDisp[i * 2 + 1]; } } } else if (numDOF == 12) { // dim = 2, dof = 3 Un(0) = disp1(0); Un(1) = disp1(1); Un(3) = disp2(0); Un(4) = disp2(1); Un(6) = disp3(0); Un(7) = disp3(1); Un(9) = disp4(0); Un(10) = disp4(1); if (initialDisp != 0) { for (int i = 0; i < 4; i++) { Un(i * 3) -= initialDisp[i * 2]; Un(i * 3 + 1) -= initialDisp[i * 2 + 1]; } } } else { // dim = 3, dof = 6 Un(0) = disp1(0); Un(1) = disp1(1); Un(2) = disp1(2); Un(6) = disp2(0); Un(7) = disp2(1); Un(8) = disp2(2); Un(12) = disp3(0); Un(13) = disp3(1); Un(14) = disp3(2); Un(18) = disp4(0); Un(19) = disp4(1); Un(20) = disp4(2); if (initialDisp != 0) { for (int i = 0; i < 4; i++) { Un(i * 6) -= initialDisp[i * 3]; Un(i * 6 + 1) -= initialDisp[i * 3 + 1]; Un(i * 6 + 2) -= initialDisp[i * 3 + 2]; } } } // Transform into local coordinates T = transformMatrix(); UnLocal.addMatrixVector(0.0, T, Un, 1.0); // Get midpoint displacements in local coordinates static Vector Uo(4); Uo = getMidDisp(UnLocal); for (int i = 0; i < 4; i++) { // Added for r1.07 //dL_overL(i * 2) = -4 * UnLocal(i * 2) + 6 * Uo(i) - 2 * UnLocal(i * 2 + 1); //dL_overL(i * 2 + 1) = 2 * UnLocal(i * 2) - 6 * Uo(i) + 4 * UnLocal(i * 2 + 1); dL_overL(i * 2) = Uo(i) - UnLocal(i * 2); dL_overL(i * 2 + 1) = UnLocal(i * 2 + 1) - Uo(i); dL_overL(i * 2) /= (L[i]/2.); dL_overL(i * 2 + 1) /= (L[i]/2.); } return dL_overL; } // Get Panel stiffness matrix in local coordinates const Matrix& StringPanelLin::getPanelStiff(void) { double B[4]; // Panel B matrix // Get nodes coordinates const Vector& end1Crd = theNodes[0]->getCrds(); const Vector& end2Crd = theNodes[1]->getCrds(); const Vector& end3Crd = theNodes[2]->getCrds(); const Vector& end4Crd = theNodes[3]->getCrds(); double xl[4] = { 0 }; double yl[4] = { 0 }; static Matrix PanelK(4, 4); PanelK.Zero(); // Define local coordinate reference plane, only necessary in 3d space if (dimension == 3) { double a[3]; double b[3]; double xp[3]; double yp[3]; double n = 0.0; double d = 0.0; double lambda = 0.0; double temp = 0.0; // Procedure from Hoogenboom thesis Appendix 4 for (int i = 0; i < 3; i++) { a[i] = end2Crd(i) + end3Crd(i) - end1Crd(i) - end4Crd(i); b[i] = end3Crd(i) + end4Crd(i) - end1Crd(i) - end2Crd(i); a[i] *= 0.5; b[i] *= 0.5; n += a[i] * a[i] + b[i] * b[i]; d += 2 * a[i] * b[i]; } if (d < 0.0) temp = -1. * d; else temp = d; if (temp > n * 0.0000001) { double t = n / d; if (fabs(t) < 1.) { opserr << "StringPanelLin::getPanelStiff ERROR: Panel in StringPanel " << this->getTag() << " reference system cannot be established\n"; exit(-1); return PanelK; } else if (t > 1.) lambda = -1. * t + sqrt(t * t - 1.); else lambda = -1. * t - sqrt(t * t - 1.); } else lambda = 0.0; for (int i = 0; i < 3; i++) { xp[i] = a[i] + lambda * b[i]; yp[i] = b[i] + lambda * a[i]; } double lx = sqrt(xp[0] * xp[0] + xp[1] * xp[1] + xp[2] * xp[2]); double ly = sqrt(yp[0] * yp[0] + yp[1] * yp[1] + yp[2] * yp[2]); if (lx <= 0.0 || ly <= 0.0) { opserr << "StringPanelLin::getPanelStiff ERROR: Local x or y axis has no length in String Panel " << this->getTag() << "\n"; exit(-1); return PanelK; } // Transformation matrix static Matrix T(3, 3); for (int i = 0; i < 3; i++) { T(0, i) = xp[i] / lx; T(1, i) = yp[i] / ly; T(2, i) = 0.0; } // Vector of mid global coordinates double mid[3]; for (int i = 0; i < 3; i++) { mid[i] = (end1Crd(i) + end2Crd(i) + end3Crd(i) + end4Crd(i)) / 4.; } // Local coordinate computation double zl[4]; xl[0] = end1Crd(0) - mid[0]; xl[1] = end2Crd(0) - mid[0]; xl[2] = end3Crd(0) - mid[0]; xl[3] = end4Crd(0) - mid[0]; yl[0] = end1Crd(1) - mid[1]; yl[1] = end2Crd(1) - mid[1]; yl[2] = end3Crd(1) - mid[1]; yl[3] = end4Crd(1) - mid[1]; zl[0] = end1Crd(2) - mid[2]; zl[1] = end2Crd(2) - mid[2]; zl[2] = end3Crd(2) - mid[2]; zl[3] = end4Crd(2) - mid[2]; // Compute local coordinates using the transformation matrix T, zl are all 0's for (int j = 0; j < 4; j++) { xl[j] = T(0, 0) * xl[j] + T(0, 1) * yl[j] + T(0, 2) * zl[j]; yl[j] = T(1, 0) * xl[j] + T(1, 1) * yl[j] + T(1, 2) * zl[j]; } } else if (dimension == 2) { xl[0] = end1Crd(0); xl[1] = end2Crd(0); xl[2] = end3Crd(0); xl[3] = end4Crd(0); yl[0] = end1Crd(1); yl[1] = end2Crd(1); yl[2] = end3Crd(1); yl[3] = end4Crd(1); } ////// B matrix computation // Create director cosines. Hoogenboom & Blaauwendraad 2000 (see Reference) double c[4]; double s[4]; double r[4]; double l[4]; // Use for debugging purposes, come back and delete later double km[4]; // Vector with minors c[0] = xl[1] - xl[0]; c[1] = xl[2] - xl[1]; c[2] = xl[3] - xl[2]; c[3] = xl[0] - xl[3]; s[0] = yl[1] - yl[0]; s[1] = yl[2] - yl[1]; s[2] = yl[3] - yl[2]; s[3] = yl[0] - yl[3]; r[0] = xl[0] * yl[1] - xl[1] * yl[0]; r[1] = xl[1] * yl[2] - xl[2] * yl[1]; r[2] = xl[2] * yl[3] - xl[3] * yl[2]; r[3] = xl[3] * yl[0] - xl[0] * yl[3]; double A = 0.5 * (r[0] + r[1] + r[2] + r[3]); for (int i = 0; i < 4; i++) { l[i] = sqrt(c[i] * c[i] + s[i] * s[i]); // For debugging purposes. if (abs(l[i]/L[i] - 1) > 0.001) { opserr << "StringPanelLin::getPanelStiff WARNING: length local " << l[i] << " in panel " << this->getTag() << " is not the same as length L " << L[i] << " original. Results may not be accurate. \n"; exit(-1); return PanelK; } } km[0] = c[1] * (s[2] * r[3] - s[3] * r[2]) - s[1] * (c[2] * r[3] - c[3] * r[2]) + r[1] * (c[2] * s[3] - c[3] * s[2]); km[1] = c[0] * (s[2] * r[3] - s[3] * r[2]) - s[0] * (c[2] * r[3] - c[3] * r[2]) + r[0] * (c[2] * s[3] - c[3] * s[2]); km[2] = c[0] * (s[1] * r[3] - s[3] * r[1]) - s[0] * (c[1] * r[3] - c[3] * r[1]) + r[0] * (c[1] * s[3] - c[3] * s[1]); km[3] = c[0] * (s[1] * r[2] - s[2] * r[1]) - s[0] * (c[1] * r[2] - c[2] * r[1]) + r[0] * (c[1] * s[2] - c[2] * s[1]); double ksum = km[0] + km[1] + km[2] + km[3]; for (int i = 0; i < 4; i++) B[i] = 4.0 * km[i] * L[i] / ksum; B[0] *= -1.0; B[2] *= -1.0; ////// Compute constitutive factor D double xi[4]; // Natural coordinates double eta[4]; // Natural coordinates double wi = 0.25; // Integration point weights double J[4]; // Jacobian double Gs[4]; double cot[4]; double G = E_p / (2 * (1 + nu)); xi[0] = 0.5; xi[1] = 1.0; xi[2] = 0.5; xi[3] = 0.0; eta[0] = 0.0; eta[1] = 0.5; eta[2] = 1.0; eta[3] = 0.5; for (int i = 0; i < 4; i++) { cot[i] = (eta[i] * c[2] + (eta[i] - 1) * c[0]) * (xi[i] * c[1] + (xi[i] - 1) * c[3]) + (eta[i] * s[2] + (eta[i] - 1) * s[0]) * (xi[i] * s[1] + (xi[i] - 1) * s[3]); cot[i] /= (eta[i] * s[2] + (eta[i] - 1) * s[0]) * (xi[i] * c[1] + (xi[i] - 1) * c[3]) - (eta[i] * c[2] + (eta[i] - 1) * c[0]) * (xi[i] * s[1] + (xi[i] - 1) * s[3]); J[i] = A + (0.5 - xi[i]) * (c[0] * s[2] - c[2] * s[0]) + (0.5 - eta[i]) * (c[1] * s[3] - c[3] * s[1]); Gs[i] = 1 / G + 4. * cot[i] * cot[i] / E_p; Gs[i] = 1 / Gs[i]; } double e = 16 / (thickness * ksum * ksum); // Generalized strain double e_sum = 0; for (int i = 0; i < 4; i++) e_sum += km[i] * km[i] * wi * J[i] / Gs[i]; e *= e_sum; double D = 1. / e; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { PanelK(i, j) = B[i] * D * B[j]; } } return PanelK; } // Transform StringPanel stiffness matrix into global coordinates and assemble const Matrix& StringPanelLin::assembleK(const Matrix& kStringer1, const Matrix& kStringer2, const Matrix& kStringer3, const Matrix& kStringer4) { // Inputs are the 4 stringers stiffness matrix counterclockwise static Matrix globalK(numDOF, numDOF); // Stiffness matrix to return in global coordinates static Matrix localK(8, 8); // Stiffness matrix in local coordinates globalK.Zero(); localK.Zero(); // The midpoint of the stringer has a DOF, but only parallel to the end of the stringer. // We cannot enforce this condition or restraint in OpenSees internally, and if the user // is asked to model this node and input it in the element it would lead to instabilities // since it has no out of plane stiffness. The user cannot restraint this as this node is // free to move in any direction. // Thus, we apply static condensation to get the contribution from the panel and reduce the // number of DOF. The assumption is that no force is applied externally at the midpoint. // | Fn | = | Knn Kno | | Un | // | 0 | | <NAME> | | Uo | // Panel stiffness matrix local static Matrix kStringPan(4, 4); kStringPan = getPanelStiff(); // Static condensation matrices static Matrix knn(8, 8); static Matrix kno(8, 4); static Matrix kon(4, 8); static Matrix koo(4, 4); knn.Zero(); kno.Zero(); kon.Zero(); koo.Zero(); // Assemble sub-matrices knn(0, 0) += kStringer1(0, 0); knn(1, 0) += kStringer1(2, 0); knn(0, 1) += kStringer1(0, 2); knn(1, 1) += kStringer1(2, 2); knn(2, 2) += kStringer2(0, 0); knn(3, 2) += kStringer2(2, 0); knn(2, 3) += kStringer2(0, 2); knn(3, 3) += kStringer2(2, 2); knn(4, 4) += kStringer3(0, 0); knn(5, 4) += kStringer3(2, 0); knn(4, 5) += kStringer3(0, 2); knn(5, 5) += kStringer3(2, 2); knn(6, 6) += kStringer4(0, 0); knn(7, 6) += kStringer4(2, 0); knn(6, 7) += kStringer4(0, 2); knn(7, 7) += kStringer4(2, 2); kno(0, 0) += kStringer1(0, 1); kno(1, 0) += kStringer1(2, 1); kno(2, 1) += kStringer2(0, 1); kno(3, 1) += kStringer2(2, 1); kno(4, 2) += kStringer3(0, 1); kno(5, 2) += kStringer3(2, 1); kno(6, 3) += kStringer4(0, 1); kno(7, 3) += kStringer4(2, 1); koo.addMatrix(0.0, kStringPan, 1.0); koo(0, 0) += kStringer1(1, 1); koo(1, 1) += kStringer2(1, 1); koo(2, 2) += kStringer3(1, 1); koo(3, 3) += kStringer4(1, 1); kon(0, 0) += kStringer1(1, 0); kon(0, 1) += kStringer1(1, 2); kon(1, 2) += kStringer2(1, 0); kon(1, 3) += kStringer2(1, 2); kon(2, 4) += kStringer3(1, 0); kon(2, 5) += kStringer3(1, 2); kon(3, 6) += kStringer4(1, 0); kon(3, 7) += kStringer4(1, 2); // Compute local stiffness matrix static Matrix koo_inv(4, 4); static Matrix koo_kon(4, 8); static Matrix knokookon(8, 8); koo.Invert(koo_inv); koo_kon.addMatrixProduct(0.0, koo_inv, kon, 1.0); knokookon.addMatrixProduct(0.0, kno, koo_kon, 1.0); localK.addMatrix(1.0, knn, 1.0); localK.addMatrix(1.0, knokookon, -1.0); // Obtaining stiffness matrix in global coordinates depending on the dimension of the domain static Matrix T(8, numDOF); T = transformMatrix(); globalK.addMatrixTripleProduct(0.0, T, localK, 1.0); return globalK; } // Get coordinate transformation matrix const Matrix& StringPanelLin::transformMatrix(void) { // Transformation matrix static Matrix T(8, numDOF); T.Zero(); if (numDOF == 8) { // dimension = 2, dof = 2; // Direction cosines double cosX[4]; double cosY[4]; for (int i = 0; i < 4; i++) { cosX[i] = dx[i] / L[i]; cosY[i] = dy[i] / L[i]; } T(0, 0) = cosX[0]; T(0, 1) = cosY[0]; T(1, 2) = cosX[0]; T(1, 3) = cosY[0]; T(2, 2) = cosX[1]; T(2, 3) = cosY[1]; T(3, 4) = cosX[1]; T(3, 5) = cosY[1]; T(4, 4) = cosX[2]; T(4, 5) = cosY[2]; T(5, 6) = cosX[2]; T(5, 7) = cosY[2]; T(6, 6) = cosX[3]; T(6, 7) = cosY[3]; T(7, 0) = cosX[3]; T(7, 1) = cosY[3]; } else if (numDOF == 12) { // dimension = 2, dof = 3; // Direction cosines double cosX[4]; double cosY[4]; for (int i = 0; i < 4; i++) { cosX[i] = dx[i] / L[i]; cosY[i] = dy[i] / L[i]; } T(0, 0) = cosX[0]; T(0, 1) = cosY[0]; T(1, 3) = cosX[0]; T(1, 4) = cosY[0]; T(2, 3) = cosX[1]; T(2, 4) = cosY[1]; T(3, 6) = cosX[1]; T(3, 7) = cosY[1]; T(4, 6) = cosX[2]; T(4, 7) = cosY[2]; T(5, 9) = cosX[2]; T(5, 10) = cosY[2]; T(6, 9) = cosX[3]; T(6, 10) = cosY[3]; T(7, 0) = cosX[3]; T(7, 1) = cosY[3]; } else { // numDOF = 24 // dimension = 3, dof = 6; // Direction cosines double cosX[4]; double cosY[4]; double cosZ[4]; for (int i = 0; i < 4; i++) { cosX[i] = dx[i] / L[i]; cosY[i] = dy[i] / L[i]; cosZ[i] = dz[i] / L[i]; } T(0, 0) = cosX[0]; T(0, 1) = cosY[0]; T(0, 2) = cosZ[0]; T(1, 6) = cosX[0]; T(1, 7) = cosY[0]; T(1, 8) = cosZ[0]; T(2, 6) = cosX[1]; T(2, 7) = cosY[1]; T(2, 8) = cosZ[1]; T(3, 12) = cosX[1]; T(3, 13) = cosY[1]; T(3, 14) = cosZ[1]; T(4, 12) = cosX[2]; T(4, 13) = cosY[2]; T(4, 14) = cosZ[2]; T(5, 18) = cosX[2]; T(5, 19) = cosY[2]; T(5, 20) = cosZ[2]; T(6, 18) = cosX[3]; T(6, 19) = cosY[3]; T(6, 20) = cosZ[3]; T(7, 0) = cosX[3]; T(7, 1) = cosY[3]; T(7, 2) = cosZ[3]; } return T; } // Get force vector in local coordinates const Vector& StringPanelLin::getLocalForce(void) { // Kinematic and equilibrium B matrix // B = [-1 1 0; // 0 -1 1]; // The stress resultants at each integration point will be N1 and N2 (see references) // When multiplying by the transpose of the B matrix we obtain the resultants at the DOF // Vectors of forces for each stringer in local coordinates static Vector f1(3); static Vector f2(3); static Vector f3(3); static Vector f4(3); f1.Zero(); f2.Zero(); f3.Zero(); f4.Zero(); // Obtain the total force from the stress resultant from each stringer double f[8]; // Stringer 1 f[0] = 0.0; f[1] = 0.0; int order1 = theSection1_1->getOrder(); const ID& code1 = theSection1_1->getType(); const Vector& s1_1 = theSection1_1->getStressResultant(); const Vector& s1_3 = theSection1_3->getStressResultant(); for (int j = 0; j < order1; j++) { if (code1(j) == SECTION_RESPONSE_P) { f[0] += s1_1(j); f[1] += s1_3(j); } } // Stringer 2 f[2] = 0.0; f[3] = 0.0; int order2 = theSection2_1->getOrder(); const ID& code2 = theSection2_1->getType(); const Vector& s2_1 = theSection2_1->getStressResultant(); const Vector& s2_3 = theSection2_3->getStressResultant(); for (int j = 0; j < order2; j++) { if (code2(j) == SECTION_RESPONSE_P) { f[2] += s2_1(j); f[3] += s2_3(j); } } // Stringer 3 f[4] = 0.0; f[5] = 0.0; int order3 = theSection3_1->getOrder(); const ID& code3 = theSection3_1->getType(); const Vector& s3_1 = theSection3_1->getStressResultant(); const Vector& s3_3 = theSection3_3->getStressResultant(); for (int j = 0; j < order3; j++) { if (code3(j) == SECTION_RESPONSE_P) { f[4] += s3_1(j); f[5] += s3_3(j); } } // Stringer 4 f[6] = 0.0; f[7] = 0.0; int order4 = theSection4_1->getOrder(); const ID& code4 = theSection4_1->getType(); const Vector& s4_1 = theSection4_1->getStressResultant(); const Vector& s4_3 = theSection4_3->getStressResultant(); for (int j = 0; j < order4; j++) { if (code4(j) == SECTION_RESPONSE_P) { f[6] += s4_1(j); f[7] += s4_3(j); } } double N[8]; // Added for r1.07 for (int i = 0; i < 8; i++) N[i] = f[i]; // Multiply transpose of B to get the force at DOF f1(0) = -N[0]; f2(0) = -N[2]; f3(0) = -N[4]; f4(0) = -N[6]; f1(1) = N[0] - N[1]; f2(1) = N[2] - N[3]; f3(1) = N[4] - N[5]; f4(1) = N[6] - N[7]; f1(2) = N[1]; f2(2) = N[3]; f3(2) = N[5]; f4(2) = N[7]; static Vector fStringers(12); fStringers.Zero(); for (int i = 0; i < 3; i++) { fStringers(i) = f1(i); fStringers(i + 3) = f2(i); fStringers(i + 6) = f3(i); fStringers(i + 9) = f4(i); } return fStringers; } // Get displacement at midpoints const Vector& StringPanelLin::getMidDisp(const Vector& Un) { // Considers initial stiffness as an assupmtion to compute mid point displacement value // This is an approximation to avoid getting into an infinite loop and avoid having iterations within the code // Efficiency purposes // Stringers stiffness matrix static Matrix k1(3, 3); static Matrix k2(3, 3); static Matrix k3(3, 3); static Matrix k4(3, 3); k1(0, 0) = 4.0; k1(0, 1) = -6.0; k1(0, 2) = 2.0; k1(1, 0) = -6.0; k1(1, 1) = 12.0; k1(1, 2) = -6.0; k1(2, 0) = 2.0; k1(2, 1) = -6.0; k1(2, 2) = 4.0; k2 = k1; k3 = k1; k4 = k1; double AEoverL[4]; // Currently the element only allows for a constant section in each stringer // The initial stiffness is computed based on one unique section of the stringer // regardles of having 2 integration points // Stringer 1 AEoverL[0] = 0.0; int order1 = theSection1_1->getOrder(); const ID& code1 = theSection1_1->getType(); const Matrix& k_1 = theSection1_1->getInitialTangent(); for (int j = 0; j < order1; j++) { if (code1(j) == SECTION_RESPONSE_P) AEoverL[0] += k_1(j, j); } AEoverL[0] /= L[0]; // Stringer 2 AEoverL[1] = 0.0; int order2 = theSection2_1->getOrder(); const ID& code2 = theSection2_1->getType(); const Matrix& k_2 = theSection2_1->getInitialTangent(); for (int j = 0; j < order2; j++) { if (code2(j) == SECTION_RESPONSE_P) AEoverL[1] += k_2(j, j); } AEoverL[1] /= L[1]; // Stringer 3 AEoverL[2] = 0.0; int order3 = theSection3_1->getOrder(); const ID& code3 = theSection3_1->getType(); const Matrix& k_3 = theSection3_1->getInitialTangent(); for (int j = 0; j < order3; j++) { if (code3(j) == SECTION_RESPONSE_P) AEoverL[2] += k_3(j, j); } AEoverL[2] /= L[2]; // Stringer 4 AEoverL[3] = 0.0; int order4 = theSection4_1->getOrder(); const ID& code4 = theSection4_1->getType(); const Matrix& k_4 = theSection4_1->getInitialTangent(); for (int j = 0; j < order4; j++) { if (code4(j) == SECTION_RESPONSE_P) AEoverL[3] += k_4(j, j); } AEoverL[3] /= L[3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { k1(i, j) *= AEoverL[0]; k2(i, j) *= AEoverL[1]; k3(i, j) *= AEoverL[2]; k4(i, j) *= AEoverL[3]; } } // Panel stiffness matrix local static Matrix kStringPan(4, 4); kStringPan = getPanelStiff(); // Static condensation matrices static Matrix knn(8, 8); static Matrix kno(8, 4); static Matrix kon(4, 8); static Matrix koo(4, 4); knn.Zero(); kno.Zero(); kon.Zero(); koo.Zero(); // Assemble sub-matrices koo.addMatrix(0.0, kStringPan, 1.0); koo(0, 0) += k1(1, 1); koo(1, 1) += k2(1, 1); koo(2, 2) += k3(1, 1); koo(3, 3) += k4(1, 1); kon(0, 0) += k1(1, 0); kon(0, 1) += k1(1, 2); kon(1, 2) += k2(1, 0); kon(1, 3) += k2(1, 2); kon(2, 4) += k3(1, 0); kon(2, 5) += k3(1, 2); kon(3, 6) += k4(1, 0); kon(3, 7) += k4(1, 2); static Matrix koo_inv(4, 4); static Matrix koo_kon(4, 8); koo.Invert(koo_inv); koo_kon.addMatrixProduct(0.0, koo_inv, kon, 1.0); // Compute midpoint displacements static Vector Uo(4); Uo.addMatrixVector(0.0, koo_kon, Un, -1.0); return Uo; } // Get Panel stiffness matrix in local coordinates double StringPanelLin::getPanelArea(void) { double A = 0.0; // Panel area // Get nodes coordinates const Vector& end1Crd = theNodes[0]->getCrds(); const Vector& end2Crd = theNodes[1]->getCrds(); const Vector& end3Crd = theNodes[2]->getCrds(); const Vector& end4Crd = theNodes[3]->getCrds(); double xl[4] = { 0 }; double yl[4] = { 0 }; // Define local coordinate reference plane, only necessary in 3d space if (dimension == 3) { double a[3]; double b[3]; double xp[3]; double yp[3]; double n = 0.0; double d = 0.0; double lambda = 0.0; double temp = 0.0; // Procedure from Hoogenboom thesis Appendix 4 for (int i = 0; i < 3; i++) { a[i] = end2Crd(i) + end3Crd(i) - end1Crd(i) - end4Crd(i); b[i] = end3Crd(i) + end4Crd(i) - end1Crd(i) - end2Crd(i); a[i] *= 0.5; b[i] *= 0.5; n += a[i] * a[i] + b[i] * b[i]; d += 2 * a[i] * b[i]; } if (d < 0.0) temp = -1. * d; else temp = d; if (temp > n * 0.0000001) { double t = n / d; if (fabs(t) < 1.) { opserr << "StringPanelLin::getPanelArea ERROR: Panel in StringPanel " << this->getTag() << " reference system cannot be established\n"; exit(-1); return 0.0; } else if (t > 1.) lambda = -1. * t + sqrt(t * t - 1.); else lambda = -1. * t - sqrt(t * t - 1.); } else lambda = 0.0; for (int i = 0; i < 3; i++) { xp[i] = a[i] + lambda * b[i]; yp[i] = b[i] + lambda * a[i]; } double lx = sqrt(xp[0] * xp[0] + xp[1] * xp[1] + xp[2] * xp[2]); double ly = sqrt(yp[0] * yp[0] + yp[1] * yp[1] + yp[2] * yp[2]); if (lx <= 0.0 || ly <= 0.0) { opserr << "StringPanelLin::getPanelArea ERROR: Local x or y axis has no length in String Panel " << this->getTag() << "\n"; exit(-1); return 0.0; } // Transformation matrix static Matrix T(3, 3); for (int i = 0; i < 3; i++) { T(0, i) = xp[i] / lx; T(1, i) = yp[i] / ly; T(2, i) = 0.0; } // Vector of mid global coordinates double mid[3]; for (int i = 0; i < 3; i++) { mid[i] = (end1Crd(i) + end2Crd(i) + end3Crd(i) + end4Crd(i)) / 4.; } // Local coordinate computation double zl[4]; xl[0] = end1Crd(0) - mid[0]; xl[1] = end2Crd(0) - mid[0]; xl[2] = end3Crd(0) - mid[0]; xl[3] = end4Crd(0) - mid[0]; yl[0] = end1Crd(1) - mid[1]; yl[1] = end2Crd(1) - mid[1]; yl[2] = end3Crd(1) - mid[1]; yl[3] = end4Crd(1) - mid[1]; zl[0] = end1Crd(2) - mid[2]; zl[1] = end2Crd(2) - mid[2]; zl[2] = end3Crd(2) - mid[2]; zl[3] = end4Crd(2) - mid[2]; // Compute local coordinates using the transformation matrix T, zl are all 0's for (int j = 0; j < 4; j++) { xl[j] = T(0, 0) * xl[j] + T(0, 1) * yl[j] + T(0, 2) * zl[j]; yl[j] = T(1, 0) * xl[j] + T(1, 1) * yl[j] + T(1, 2) * zl[j]; } } else if (dimension == 2) { xl[0] = end1Crd(0); xl[1] = end2Crd(0); xl[2] = end3Crd(0); xl[3] = end4Crd(0); yl[0] = end1Crd(1); yl[1] = end2Crd(1); yl[2] = end3Crd(1); yl[3] = end4Crd(1); } ////// B matrix computation // Create director cosines. Hoogenboom & Blaauwendraad 2000 (see Reference) double r[4]; r[0] = xl[0] * yl[1] - xl[1] * yl[0]; r[1] = xl[1] * yl[2] - xl[2] * yl[1]; r[2] = xl[2] * yl[3] - xl[3] * yl[2]; r[3] = xl[3] * yl[0] - xl[0] * yl[3]; A += 0.5 * (r[0] + r[1] + r[2] + r[3]); return A; }
a9950aa945b82dd736c2b90b4ff71dc29938b4b6
[ "Markdown", "C++" ]
3
Markdown
SGodinez92/SPM
65d6ed599ad79efdeb1fd9f5eded033244704501
581c1ec433bf29868b990cf34e8cfcd1f82c015a
refs/heads/master
<file_sep>from __future__ import print_function import openravepy import prpy.util import unittest import os # environ, path import subprocess import sys # stderr import numpy # allclose, zeros # Add the models included with OpenRAVE to the OPENRAVE_DATA path. # These may not be available if the user manually set the OPENRAVE_DATA # environmental variable, e.g. through openrave_catkin. try: share_path = \ subprocess.check_output(['openrave-config', '--share-dir']).strip() os.environ['OPENRAVE_DATA'] = os.path.join(share_path, 'data') except subprocess.CalledProcessError as e: print('error: Failed using "openrave-config" to find the default' ' OPENRAVE_DATA path. Loading assets may fail.', file=sys.stderr) # Initialize OpenRAVE. openravepy.RaveInitialize(True) openravepy.misc.InitOpenRAVELogging() openravepy.RaveSetDebugLevel(openravepy.DebugLevel.Fatal) class TrajectoryTests(unittest.TestCase): def setUp(self): self.env = openravepy.Environment() self.env.Load('wamtest1.env.xml') self.traj = openravepy.RaveCreateTrajectory(self.env, '') self.robot = self.env.GetRobot('BarrettWAM') self.manipulator = self.robot.GetManipulator('arm') # Set all 7 DOF of the WAM arm to active with self.env: self.robot.SetActiveDOFs(self.manipulator.GetArmIndices()) self.robot.SetActiveManipulator(self.manipulator) self.active_dof_indices = self.robot.GetActiveDOFIndices() def CreateTrajectory(self, q_start, q_goal): """ Create a trajectory between two joint configurations. (a straight line in joint space) """ env = self.env robot = self.robot dof_indices = self.active_dof_indices traj = openravepy.RaveCreateTrajectory(env, '') cspec = robot.GetActiveConfigurationSpecification('linear') # Add first waypoint start_waypoint = numpy.zeros(cspec.GetDOF()) cspec.InsertJointValues(start_waypoint, q_start, robot, \ dof_indices, False) traj.Init(cspec) traj.Insert(0, start_waypoint.ravel()) # Add second waypoint, if different to first if not numpy.allclose(q_start, q_goal): goal_waypoint = numpy.zeros(cspec.GetDOF()) cspec.InsertJointValues(goal_waypoint, q_goal, robot, \ dof_indices, False) traj.Insert(1, goal_waypoint.ravel()) return traj # IsTimedTrajectory() def test_IsTimed_ReturnsTrue(self): cspec = openravepy.ConfigurationSpecification() cspec.AddDeltaTimeGroup() self.traj.Init(cspec) self.assertTrue(prpy.util.IsTimedTrajectory(self.traj)) self.traj.Insert(0, [0.]) self.assertTrue(prpy.util.IsTimedTrajectory(self.traj)) def test_IsNotTimed_ReturnsFalse(self): cspec = openravepy.ConfigurationSpecification() cspec.AddGroup('joint_values test_robot 0', 1, 'linear') self.traj.Init(cspec) self.assertFalse(prpy.util.IsTimedTrajectory(self.traj)) self.traj.Insert(0, [0.]) self.assertFalse(prpy.util.IsTimedTrajectory(self.traj)) # IsAtConfiguration() def test_IsAtConfiguration_ReturnsTrue(self): curr_config = self.robot.GetDOFValues(self.active_dof_indices) self.assertTrue(prpy.util.IsAtConfiguration(self.robot, curr_config)) def test_IsAtConfiguration_ReturnsFalse(self): goal_config = [0.02, 0.01, 0.02, 0.01, 0.01, 0.01, 0.0]; self.assertFalse(prpy.util.IsAtConfiguration(self.robot, goal_config)) # IsAtTrajectoryStart() def test_IsAtTrajectoryStart_ReturnsTrue(self): current_config = self.robot.GetDOFValues(self.active_dof_indices) goal_config = [0.02, 0.01, 0.02, 0.01, 0.01, 0.01, 0.0]; q0 = current_config q1 = goal_config traj = self.CreateTrajectory(q0, q1) self.assertTrue(prpy.util.IsAtTrajectoryStart(self.robot, traj)) # Test with only 1 waypoint traj = self.CreateTrajectory(q0, q0) self.assertTrue(prpy.util.IsAtTrajectoryStart(self.robot, traj)) def test_IsAtTrajectoryStart_ReturnsFalse(self): current_config = self.robot.GetDOFValues(self.active_dof_indices) goal_config = [0.02, 0.01, 0.02, 0.01, 0.01, 0.01, 0.0]; q0 = current_config q1 = goal_config traj = self.CreateTrajectory(q1, q0) # goal is 1st waypoint self.assertFalse(prpy.util.IsAtTrajectoryStart(self.robot, traj)) # IsAtTrajectoryEnd() def test_IsAtTrajectoryEnd_ReturnsTrue(self): current_config = self.robot.GetDOFValues(self.active_dof_indices) goal_config = [0.02, 0.01, 0.02, 0.01, 0.01, 0.01, 0.0]; q0 = current_config q1 = goal_config # set last waypoint to current config traj = self.CreateTrajectory(q1, q0) self.assertTrue(prpy.util.IsAtTrajectoryEnd(self.robot, traj)) def test_IsAtTrajectoryEnd_ReturnsFalse(self): current_config = self.robot.GetDOFValues(self.active_dof_indices) goal_config = [0.02, 0.01, 0.02, 0.01, 0.01, 0.01, 0.0]; q0 = current_config q1 = goal_config traj = self.CreateTrajectory(q0, q1) self.assertFalse(prpy.util.IsAtTrajectoryEnd(self.robot, traj)) <file_sep>#!/usr/bin/env python # Copyright (c) 2015, Carnegie Mellon University # All rights reserved. # Authors: <NAME> <<EMAIL>> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # - Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # - Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # - Neither the name of Carnegie Mellon University nor the names of its # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import logging import numpy import openravepy import time from .. import util from base import BasePlanner, PlanningError, PlanningMethod, Tags from enum import Enum import math logger = logging.getLogger(__name__) class TerminationError(PlanningError): def __init__(self): super(TerminationError, self).__init__('Terminated by callback.') class TimeLimitError(PlanningError): def __init__(self): super(TimeLimitError, self).__init__('Reached time limit.') class Status(Enum): ''' CONTINUE - keep going TERMINATE - stop gracefully and output the CACHEd trajectory CACHE_AND_CONTINUE - save the current trajectory and CONTINUE. return the saved trajectory if TERMINATEd. CACHE_AND_TERMINATE - save the current trajectory and TERMINATE ''' TERMINATE = -1 CACHE_AND_CONTINUE = 0 CONTINUE = 1 CACHE_AND_TERMINATE = 2 @classmethod def DoesTerminate(cls, status): return status in [cls.TERMINATE, cls.CACHE_AND_TERMINATE] @classmethod def DoesCache(cls, status): return status in [cls.CACHE_AND_CONTINUE, cls.CACHE_AND_TERMINATE] class VectorFieldPlanner(BasePlanner): def __init__(self): super(VectorFieldPlanner, self).__init__() def __str__(self): return 'VectorFieldPlanner' @PlanningMethod def PlanToEndEffectorPose(self, robot, goal_pose, timelimit=5.0, pose_error_tol=0.01, **kw_args): """ Plan to an end effector pose by following a geodesic loss function in SE(3) via an optimized Jacobian. @param robot @param goal_pose desired end-effector pose @param timelimit time limit before giving up @param pose_error_tol in meters @return traj """ manip = robot.GetActiveManipulator() def vf_geodesic(): twist = util.GeodesicTwist(manip.GetEndEffectorTransform(), goal_pose) dqout, tout = util.ComputeJointVelocityFromTwist( robot, twist, joint_velocity_limits=numpy.PINF) # Go as fast as possible vlimits = robot.GetDOFVelocityLimits(robot.GetActiveDOFIndices()) return min(abs(vlimits[i] / dqout[i]) if dqout[i] != 0. else 1. for i in xrange(vlimits.shape[0])) * dqout def CloseEnough(): pose_error = util.GeodesicDistance( manip.GetEndEffectorTransform(), goal_pose) if pose_error < pose_error_tol: return Status.TERMINATE return Status.CONTINUE traj = self.FollowVectorField(robot, vf_geodesic, CloseEnough, timelimit) # Flag this trajectory as unconstrained. This overwrites the # constrained flag set by FollowVectorField. util.SetTrajectoryTags(traj, {Tags.CONSTRAINED: False}, append=True) return traj @PlanningMethod def PlanToEndEffectorOffset(self, robot, direction, distance, max_distance=None, timelimit=5.0, position_tolerance=0.01, angular_tolerance=0.15, **kw_args): """ Plan to a desired end-effector offset with move-hand-straight constraint. movement less than distance will return failure. The motion will not move further than max_distance. @param robot @param direction unit vector in the direction of motion @param distance minimum distance in meters @param max_distance maximum distance in meters @param timelimit timeout in seconds @param position_tolerance constraint tolerance in meters @param angular_tolerance constraint tolerance in radians @return traj """ if distance < 0: raise ValueError('Distance must be non-negative.') elif numpy.linalg.norm(direction) == 0: raise ValueError('Direction must be non-zero') elif max_distance is not None and max_distance < distance: raise ValueError('Max distance is less than minimum distance.') elif position_tolerance < 0: raise ValueError('Position tolerance must be non-negative.') elif angular_tolerance < 0: raise ValueError('Angular tolerance must be non-negative.') # Normalize the direction vector. direction = numpy.array(direction, dtype='float') direction /= numpy.linalg.norm(direction) manip = robot.GetActiveManipulator() Tstart = manip.GetEndEffectorTransform() def vf_straightline(): twist = util.GeodesicTwist(manip.GetEndEffectorTransform(), Tstart) twist[0:3] = direction dqout, _ = util.ComputeJointVelocityFromTwist( robot, twist, joint_velocity_limits=numpy.PINF) return dqout def TerminateMove(): ''' Fail if deviation larger than position and angular tolerance. Succeed if distance moved is larger than max_distance. Cache and continue if distance moved is larger than distance. ''' from .exceptions import ConstraintViolationPlanningError Tnow = manip.GetEndEffectorTransform() error = util.GeodesicError(Tstart, Tnow) if numpy.fabs(error[3]) > angular_tolerance: raise ConstraintViolationPlanningError( 'Deviated from orientation constraint.') distance_moved = numpy.dot(error[0:3], direction) position_deviation = numpy.linalg.norm(error[0:3] - distance_moved*direction) if position_deviation > position_tolerance: raise ConstraintViolationPlanningError( 'Deviated from straight line constraint.') if max_distance is None: if distance_moved > distance: return Status.CACHE_AND_TERMINATE elif distance_moved > max_distance: return Status.TERMINATE elif distance_moved >= distance: return Status.CACHE_AND_CONTINUE return Status.CONTINUE return self.FollowVectorField(robot, vf_straightline, TerminateMove, timelimit, **kw_args) @PlanningMethod def FollowVectorField(self, robot, fn_vectorfield, fn_terminate, integration_timelimit=10., timelimit=5.0, dt_multiplier=1.01, **kw_args): """ Follow a joint space vectorfield to termination. @param robot @param fn_vectorfield a vectorfield of joint velocities @param fn_terminate custom termination condition @param timelimit time limit before giving up @param dt_multiplier multiplier of the minimum resolution at which the vector field will be followed. Defaults to 1.0. Any larger value means the vectorfield will be re-evaluated floor(dt_multiplier) steps @param kw_args keyword arguments to be passed to fn_vectorfield @return traj """ from .exceptions import ( CollisionPlanningError, SelfCollisionPlanningError, TimeoutPlanningError, JointLimitError ) from openravepy import CollisionReport, RaveCreateTrajectory from ..util import ComputeJointVelocityFromTwist, GetCollisionCheckPts, ComputeUnitTiming import time import scipy.integrate CheckLimitsAction = openravepy.KinBody.CheckLimitsAction # This is a workaround to emulate 'nonlocal' in Python 2. nonlocals = { 'exception': None, 't_cache': None, 't_check': 0., } env = robot.GetEnv() active_indices = robot.GetActiveDOFIndices() q_limit_min, q_limit_max = robot.GetActiveDOFLimits() qdot_limit = robot.GetDOFVelocityLimits(active_indices) cspec = robot.GetActiveConfigurationSpecification('linear') cspec.AddDeltaTimeGroup() cspec.ResetGroupOffsets() path = RaveCreateTrajectory(env, '') path.Init(cspec) time_start = time.time() def fn_wrapper(t, q): robot.SetActiveDOFValues(q, CheckLimitsAction.Nothing) return fn_vectorfield() def fn_status_callback(t, q): if time.time() - time_start >= timelimit: raise TimeLimitError() # Check joint position limits. Do this before setting the DOF so we # don't set the DOFs out of limits. lower_position_violations = (q < q_limit_min) if lower_position_violations.any(): index = lower_position_violations.nonzero()[0][0] raise JointLimitError(robot, dof_index=active_indices[index], dof_value=q[index], dof_limit=q_limit_min[index], description='position') upper_position_violations = (q> q_limit_max) if upper_position_violations.any(): index = upper_position_violations.nonzero()[0][0] raise JointLimitError(robot, dof_index=active_indices[index], dof_value=q[index], dof_limit=q_limit_max[index], description='position') robot.SetActiveDOFValues(q) # Check collision. report = CollisionReport() if env.CheckCollision(robot, report=report): raise CollisionPlanningError.FromReport(report) elif robot.CheckSelfCollision(report=report): raise SelfCollisionPlanningError.FromReport(report) # Check the termination condition. status = fn_terminate() if Status.DoesCache(status): nonlocals['t_cache'] = t if Status.DoesTerminate(status): raise TerminationError() def fn_callback(t, q): try: # Add the waypoint to the trajectory. waypoint = numpy.zeros(cspec.GetDOF()) cspec.InsertDeltaTime(waypoint, t - path.GetDuration()) cspec.InsertJointValues(waypoint, q, robot, active_indices, 0) path.Insert(path.GetNumWaypoints(), waypoint) # Run constraint checks at DOF resolution. if path.GetNumWaypoints() == 1: checks = [(t, q)] else: # TODO: This should start at t_check. Unfortunately, a bug # in GetCollisionCheckPts causes this to enter an infinite # loop. checks = GetCollisionCheckPts(robot, path, include_start=False) #start_time=nonlocals['t_check']) for t_check, q_check in checks: fn_status_callback(t_check, q_check) # Record the time of this check so we continue checking at # DOF resolution the next time the integrator takes a step. nonlocals['t_check'] = t_check return 0 # Keep going. except PlanningError as e: nonlocals['exception'] = e return -1 # Stop. # Integrate the vector field to get a configuration space path. # TODO: Tune the integrator parameters. integrator = scipy.integrate.ode(f=fn_wrapper) integrator.set_integrator(name='dopri5', first_step=0.1, atol=1e-3, rtol=1e-3) integrator.set_solout(fn_callback) integrator.set_initial_value(y=robot.GetActiveDOFValues(), t=0.) integrator.integrate(t=integration_timelimit) t_cache = nonlocals['t_cache'] exception = nonlocals['exception'] if t_cache is None: raise exception or PlanningError('An unknown error has occurred.') elif exception: logger.warning('Terminated early: %s', str(exception)) # Remove any parts of the trajectory that are not cached. This also # strips the (potentially infeasible) timing information. output_cspec = robot.GetActiveConfigurationSpecification('linear') output_path = RaveCreateTrajectory(env, '') output_path.Init(output_cspec) # Add all waypoints before the last integration step. GetWaypoints does # not include the upper bound, so this is safe. cached_index = path.GetFirstWaypointIndexAfterTime(t_cache) output_path.Insert(0, path.GetWaypoints(0, cached_index), cspec) # Add a segment for the feasible part of the last integration step. output_path.Insert(output_path.GetNumWaypoints(), path.Sample(t_cache), cspec) # Flag this trajectory as constrained. util.SetTrajectoryTags( output_path, { Tags.CONSTRAINED: 'true', Tags.SMOOTH: 'true' }, append=True ) return output_path <file_sep># PrPy [![Build Status](https://travis-ci.org/personalrobotics/prpy.svg?branch=master)](https://travis-ci.org/personalrobotics/prpy) PrPy is a Python library used by the Personal Robotics Laboratory at Carnegie Mellon University. This library includes robot-agnostic utilities that make it easier to use OpenRAVE in Python scripts. This includes a high-level planning pipeline, helper functions, and visualization tools. ## Planning Pipeline There are a large array of motion planners that have complementary strengths and weaknesses. PrPy provides a *planning pipeline* in the `prpy.planning` namespace that makes it easy plan with multiple planners in parallel on a single problem. Additionally, the planning pipeline takes advantage of the dynamic nature of Python to mix-and-match planners with heterogeneous capabilities. Every planner used in the PrPy planning pipeline extends the `prpy.planning.base.Planner` class. Typically, a planner will extend one of two subclasses: 1. `prpy.planning.base.BasePlanner`: implements or wraps a motion planner 2. `prpy.planning.base.MetaPlanner`: combines the output of multiple motion planners, each of which is a `BasePlanner` or another `MetaPlanner` Each planner has one or more *planning methods*, annotated with the `@PlanningMethod` decorator, that look like ordinary functions. However, unlike an ordinary function, calling a planning method clones the robot's environment into a *planning environment* associated with the planner. Planning occurs in the cloned environment to allow PrPy to run multiple planners in parallel and to paralellize planning and execution. For example, the following code will use OMPL to plan `robot`'s active DOFs from their current values to to the `goal_config` configuration: ```python planner = OMPLPlanner('RRTConnect') output_path = planner.PlanToConfiguration(robot, goal_config) ``` First, `robot.GetEnv()` is cloned into the the `planner.env` planning environment. Next, planning occurs in the cloned environment. Finally, the output path is cloned back into `robot.GetEnv()` and is returned by the planner. See the following sub-sections for more information about the built-in planners provided with PrPy, information about writing your own planner, and several more complex usage examples. ### Built-In Planners PrPy provides wrappers for several existing planning libraries: - `CBiRRTPlanner`: [Constrained Bi-directional Rapidly-Exploring Random Tree (CBiRRT)](http://www.ri.cmu.edu/publication_view.html?pub_id=6309), requires the [CoMPs suite](https://github.com/personalrobotics/comps) - `CHOMPPlanner`: [Covariant Hamiltonian Optimization for Motion Planning (CHOMP)](https://www.ri.cmu.edu/publication_view.html?pub_id=7421), requires [or_cdchomp](https://github.com/personalrobotics/or_cdchomp.git) - `OMPLPlanner`: wrapper for randomized planners implemented in the [Open Motion Planning Library](http://ompl.kavrakilab.org), requires [or_ompl](https://github.com/personalrobotics/or_ompl) - `OpenRAVEPlanner`: wrapper for OpenRAVE planners that implement the [`PlannerBase` interface](http://openrave.org/docs/latest_stable/coreapihtml/arch_planner.html) - `SBPLPlanner`: wrapper for the [Search-Based Planning Library (SBPL)](https://github.com/sbpl/sbpl), requires [or_sbpl](https://github.com/personalrobotics/or_sbpl) Additionally, PrPy provides several simple planners of its own: - `MKPlanner`: Jacobian pseudo-inverse controller for executing straight-line workspace trajectories - `SnapPlanner`: attempts to execute a straight-line joint-space trajectory to the goal - `GreedyIKPlanner`: follows a workspace path by greedily picking IK solutions - `VectorFieldPlanner`: follows any custom cspace vector field until a custom termination Finally, PrPy provides several meta-planners for combining the above planners: - `Sequence`: sequentially queries a list of planners and returns the result of the first planner in the list that succeeds. - `Ranked`: queries a list of planners in parallel and returns the solution first planner in the list that returns success - `IKPlanner`: plan to an end-effector pose by sequentially planning to a list of ranked IK solutions - `NamedPlanner`: plan to a named configuration associated with the robot See the Python docstrings the above classes for more information. ### Common Planning Methods There is no formal list of `@PlanningMethod`s or their arguments. However, we have found these methods to be useful: - `PlanToConfiguration(robot, goal_config)`: plan the robot's active DOFs from the robot's current configuration to the `goal_config` configuration. - `PlanToConfigurations(robot, goal_configs)`: plan the robot's active DOFs from the robot's current configuration to any of the elements in the `goal_configs` list. - `PlanToEndEffectorPose(robot, goal_pose)`: plan the robot's active manipulator's end-effector to `goal_pose`. - `PlanToEndEffectorOffset(robot, direction, min_distance, max_distance)`: plan the robot's active manipulator in a straight line in the direction specified by the `direction` unit vector for [ `min_distance`, `max_distance` ] meters. - `PlanToTSR(robot, tsrchains)`: plan with the start, goal, and/or constraints specified by a list of TSR chains. - `PlanToBasePose(robot, goal_pose)`: plan with the robot's affine DOFs in the plane to a desired base pose. Most planners that implement these methods accept a `timelimit` parameter, in seconds, for which to plan before raising a `PlanningError`. Additionally, many of these methods accept planner-specific keyword arguments. ### Writing a Custom Planner Implementing a custom planner requires extending the `BasePlanner` class and decorating one or more methods with the `@PlanningMethod` decorator. Extending the `BasePlanner` class constructs the planning environment `self.env` and allows PrPy to identify your planner as a base planner class, as opposed to a meta-planner. The `@PlanningMethod` decorator handles environment cloning and allows meta-planners to query the list of planning methods that the planner supports (e.g. to generate docstrings). Please obey the following guidelines: - Assume that the cloned environment is locked during the entire call. - Subclass constructor **must** call `BasePlanner.__init__`. - A `@PlanningMethod` **must not** call another `@PlanningMethod`. - Each `@PlanningMethod` **must** accept the first argument `robot`, which is a robot in the cloned environment. - Each `@PlanningMethod` **must** accept `**kwargs` to ignore arguments that are not supported by the planner. - Each `@PlanningMethod` **must** return a `Trajectory` which was created in the cloned environment. - When possible, use one of the defacto-standard `@PlanningMethod` names listed below. - Raise a `PlanningError` to indicate an expected, but fatal, error (e.g. timeout with no collision-free path). - When applicable, raise a context-specific subclass of `PlanningError` to indicate the nature of the error (e.g. `StartCollisionPlanningError`) - Raise a standard Python exception, e.g. `ValueError`, to indicate an unexpected error has occurred (e.g. argument out of range). - Raise a `UnsupportedPlanningError` to indicate that the planning operation is fundamentally not supported (e.g. constraint type is not implemented). ### Examples Trajectory optimizers, like CHOMP, typically produce higher quality paths than randomized planners. However, these algorithms are not probabilistically complete and can get stuck in local minima. You can mitigate this by using the `Sequence` planner to first call CHOMP, then fall back on RRT-Connect: ```python planner = Sequence(CHOMPPlanner(), OMPLPlanner('RRTConnect')) path = planner.PlanToConfiguration(robot, goal) ``` Unfortunately, this means that RRT-Connect does not start planning until CHOMP has already failed to find a solution. Instead of using `Sequence`, we can use the `Ranked` meta-planner to plan with both planners in parallel. Just as before, the meta-planner will immediately return CHOMP's solution if it returns success. However, RRT-Connect will have a head-start if CHOMP fails: ```python planner = Ranked(CHOMPPlanner(), OMPLPlanner('RRTConnect')) path = planner.PlanToConfiguration(robot, goal)` ``` In other cases, a meta-planner can be used to combine the disparate capabilities of multiple planenrs. For example, SBPL is currently the only planner included with PrPy that supports planning for affine DOFs. We can use a meta-planner to combine OMPL's support for `PlanToConfiguration` with SBPL's support for `PlanToBasePose`: ```python planner = Sequence(OMPLPlanner('RRTConnect'), SBPLPlanner()) path1 = planner.PlanToConfiguration(robot, goal) path2 = planner.PlanToBasePose(robot, goal_pose) ``` ## Environment Cloning Cloning environments is critical to enable planning with multiple planners in parallel and parallelizing planning and execution. PrPy provides two utilities to simplify environment cloning in OpenRAVE: the `Clone` context manager and the `Cloned` helper function. ### Clone Context Manager PrPy adds a `prpy.clone.Clone` context manager to manage temporary environment clones; e.g. those used during planning. This context manager clones an environment when entering the `with`-block and destroys the environment when exiting the block. This code is careful to lock the source and destination environments during cloning correctly to avoid introducing a race condition. In the simplest case, the `Clone` context manager creates an internal, temporary environment that is not re-used between calls: ```python with Clone(env) as cloned_env: robot = cloned_env.GetRobot('herb') # ... ``` The same context manager can be used to clone into an existing environment. In this case, the same target environment can be used by multiple calls. This allows OpenRAVE to re-use the environments resources (e.g. collision tri-meshes) and can dramatically improve performance: ```python clone_env = openravepy.Environment() with Clone(env, clone_env=clone_env): robot = cloned_env.GetRobot('herb') # ... ``` Often times, the cloned environment must be immediately locked to perform additional setup. This introduces a potential race condition between `Clone` releasing the lock and the code inside the `with`-block acquiring the lock. To avoid this, use the `lock` argument to enter the `with`-block without releasing the lock: ```python with Clone(env, lock=True) as cloned_env: robot = cloned_env.GetRobot('herb') # ... ``` In this case, the cloned environment will be automatically unlocked when exiting the `with`-statement. This may be undesirable if you need to explicitly unlock the environment inside the `with`-statement. In this case, you may pass the `unlock=False` flag. In this case, you **must** explicitly unlock the environment inside the `with`-statement: ```python with Clone(env, lock=True, unlock=False) as cloned_env: robot = cloned_env.GetRobot('herb') env.Unlock() # ... ``` ### Cloned Helper Function It is frequently necessary to find an object in a cloned environment that refers to a particular object in the parent environment. This code frequently looks like this: ```python with Clone(env) as cloned_env: cloned_robot = cloned_env.GetRobot(robot.GetName()) # ... ``` The `prpy.clone.Cloned` helper function handles this name resolution for most OpenRAVE data types (including `Robot`, `KinBody`, `Link`, and `Manipulator`). This function accepts an arbitrary number of input parameters---of the supported types---and returns the corresponding objects in `Clone`d environment. For example, the above code can be re-written as: ```python with Clone(env) as cloned_env: cloned_robot = Cloned(robot) # ... ``` If multiple `Clone` context managers are nested, the `Cloned` function returns the corresponding object in the inner-most block: ```python with Clone(env) as cloned_env1: cloned_robot1 = Cloned(robot) # from cloned_env1 # ... with Clone(env) as cloned_env2: cloned_robot2 = Cloned(robot) # from cloned_env2 # ... # ... cloned_robot3 = Cloned(robot) # from cloned_env1 ``` The `Cloned` function only works if it is called from the same thread in which the `Clone` context manager was created. If this is not the case, you can still use the `Cloned` helper function by explicitly passing an environment: ```python with Clone(env) as cloned_env: def fn(body, e): cloned_robot = Cloned(body, clone_env=e) # ... thread = Thread(target=fn, args=(body, cloned_env)) thread.start() thread.join() ``` Finally, as a convenience, the `Cloned` function can be used to simultaneously resolve multiple objects in one statement: ```python with Clone(env) as cloned_env: cloned_robot, cloned_body = Cloned(robot, body) # ... ``` ## Concurrent Execution PrPy has native support for [futures](http://en.wikipedia.org/wiki/Futures_and_promises) and [coroutines](http://en.wikipedia.org/wiki/Coroutine) to simplify concurrent programming. A _future_ encapsulates the execution of a long-running task. We use the concurrency primitives provided by the [`trollius` module](http://trollius.readthedocs.org/en/latest/using.html), which is a Python 2 backport of the [`asyncio` module](https://docs.python.org/3/library/asyncio.html) from Python 3. We can use these primitives to parallelize planning and execution: ```python @coroutine def do_plan(robot): # Plan to goal1 and start executing the trajectory. path1 = yield From(robot.PlanToEndEffectorPose(goal1, execute=False)) exec1_future = robot.ExecutePath(path1) # Plan from goal1 to goal2. robot.SetDOFValues(GetLastWaypoint(path1)) path2 = yield From(robot.PlanToEndEffectorPope(goal2, execute=False)) # Wait for path1 to finish executing, then execute path2. exec1 = yield From(exec1_future) exec2 = yield From(robot.ExecutePath(path2)) raise Return(path1, path2) loop = trollius.get_event_loop() path = loop.run_until_complete(do_plan(robot)) ``` ## Method Binding Finally, PrPy offers helper functions for binding custom methods on (i.e. [monkey patching](http://en.wikipedia.org/wiki/Monkey_patch)) OpenRAVE data types, including: `KinBody`, `Robot`, `Link`, and `Joint`. This may appear trivial to accomplish using `setattr`. However, this is actually quite challenging to implement because OpenRAVE's Python bindings for these classes are automatically generated as [Boost.Python bindings](www.boost.org/doc/libs/release/libs/python/) that are managed by a `shared_ptr`. Each instance of a `shared_ptr` returned by C++ is wrapped in a separate Python object. As a result, the following code does not work as expected: ```python robot = env.GetRobot('herb') setattr(robot, 'foo', 'bar') robot_ref = env.GetRobot('herb') robot_ref.foo # raises AttributeError ``` PrPy provides the `prpy.bind.InstanceDeduplicator` class to work around this issue. This class takes advantage of the user data attached to an OpenRAVE environment to de-duplicate multiple Python `shared_ptr` instances that reference same object. This is implemented by overriding `__getattribute__` and `__setattribute__` to defer all attribute queries to a single *canonical instance* of the object. ### Canonical Instances An object is flagged for de-duplication using the `InstanceDeduplicator.add_canonical` function. The above example can be modified to work as follows: ```python robot = env.GetRobot('herb') InstanceDeduplicator.add_canonical(robot) setattr(robot, 'foo', 'bar') robot_ref = env.GetRobot('herb') robot_ref.foo # returns 'bar' ``` ### Subclass Binding Frequently we wish to extend an OpenRAVE object with several tightly coupled attributes, properties, and methods. This can be achieved by creating subclass of appropriate OpenRAVE data type (e.g. `Robot`) and dynamically changing that instance's `__class__` at runtime. PrPy provides a `prpy.bind.bind_subclass` helper function that calls `add_canonical`, changes `__class__`, and calls the subclass' `__init__` function. This functionality is most frequently used with the generic PrPy subclasses provided in the `prpy.base` module. For example, the following code adds the capabilities of `prpy.base.Robot` to an existing robot: ```python robot = env.GetRobot('herb') bind_subclass(robot, prpy.base.Robot) ``` See the docstrings on the classes defined in `prpy.base` for more information. ### Cloning Bound Subclasses OpenRAVE is not aware of methods, attributes, or properties that are added to objects in Python; e.g. using `add_canonical`. As a result, these attributes are not duplicated when the OpenRAVE environment is cloned. PrPy provides the limited capability to clone these attributes when: (1) the class was extended using the `bind_subclass` function and (2) the clone was created using the PrPy `Clone` function. If these two conditions hold, PrPy will call the `CloneBindings()` function on your custom subclass the first time the cloned object is referenced. See the classes in `prpy.base` for example implementations of `CloneBindings`. ## Dependencies To run prpy, you will need to have installed the pacakge enum34. To do that, go to a local directory and run ``sudo pip install enum34`` ## License PrPy is licensed under a BSD license. See `LICENSE` for more information. ## Contributors PrPy is developed by the [Personal Robotics Lab](https://personalrobotics.ri.cmu.edu) in the [Robotics Institute](https://www.ri.cmu.edu) at [Carnegie Mellon University](http://www.cmu.edu). This library was originally developed by [<NAME>](https://github.com/mkoval), with some code copied from the earlier `prrave` library developed by [<NAME>](https://github.com/cdellin). This is a non-exhaustive list of contributors: - [<NAME>](https://github.com/cdellin) - [<NAME>](https://github.com/es92) - [<NAME>](https://github.com/jeking) - [<NAME>](https://github.com/mkoval) - [<NAME>](https://github.com/psigen) - [<NAME>](https://github.com/sjavdani) - [<NAME>](https://github.com/siddhss5) - [<NAME>](https://github.com/Stefanos19) <file_sep>#!/usr/bin/env python # Copyright (c) 2013, Carnegie Mellon University # All rights reserved. # Authors: <NAME> <<EMAIL>> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # - Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # - Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # - Neither the name of Carnegie Mellon University nor the names of its # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import numpy import openravepy from ..util import SetTrajectoryTags from base import BasePlanner, PlanningError, PlanningMethod, Tags class SnapPlanner(BasePlanner): """Planner that checks the straight-line trajectory to the goal. SnapPlanner is a utility planner class that collision checks the straight-line trajectory to the goal. If that trajectory is invalid, i.e.. due to an environment or self collision, the planner immediately returns failure by raising a PlanningError. Collision checking is performed using the standard CheckPathAllConstraints method. SnapPlanner is intended to be used only as a "short circuit" to speed up planning between nearby configurations. This planner is most commonly used as the first item in a Sequence meta-planner to avoid calling a motion planner when the trivial solution is valid. """ def __init__(self): super(SnapPlanner, self).__init__() def __str__(self): return 'SnapPlanner' @PlanningMethod def PlanToConfiguration(self, robot, goal, **kw_args): """ Attempt to plan a straight line trajectory from the robot's current configuration to the goal configuration. This will fail if the straight-line path is not collision free. @param robot @param goal desired configuration @return traj """ return self._Snap(robot, goal, **kw_args) @PlanningMethod def PlanToEndEffectorPose(self, robot, goal_pose, **kw_args): """ Attempt to plan a straight line trajectory from the robot's current configuration to a desired end-effector pose. This happens by finding the closest IK solution to the robot's current configuration and attempts to snap there (using PlanToConfiguration) if possible. In the case of a redundant manipulator, no attempt is made to check other IK solutions. @param robot @param goal_pose desired end-effector pose @return traj """ from .exceptions import CollisionPlanningError,SelfCollisionPlanningError from openravepy import CollisionReport ikp = openravepy.IkParameterizationType ikfo = openravepy.IkFilterOptions # Find an IK solution. OpenRAVE tries to return a solution that is # close to the configuration of the arm, so we don't need to do any # custom IK ranking. manipulator = robot.GetActiveManipulator() ik_param = openravepy.IkParameterization(goal_pose, ikp.Transform6D) ik_solution = manipulator.FindIKSolution( ik_param, ikfo.CheckEnvCollisions, ikreturn=False, releasegil=True ) if ik_solution is None: # FindIKSolutions is slower than FindIKSolution, # so call this only to identify and raise error when there is no solution ik_solutions = manipulator.FindIKSolutions( ik_param, ikfo.IgnoreSelfCollisions, ikreturn=False, releasegil=True ) for q in ik_solutions: robot.SetActiveDOFValues(q) report = CollisionReport() if self.env.CheckCollision(robot, report=report): raise CollisionPlanningError.FromReport(report) elif robot.CheckSelfCollision(report=report): raise SelfCollisionPlanningError.FromReport(report) raise PlanningError('There is no IK solution at the goal pose.') return self._Snap(robot, ik_solution, **kw_args) def _Snap(self, robot, goal, **kw_args): from .exceptions import CollisionPlanningError,SelfCollisionPlanningError,JointLimitError from openravepy import CollisionReport Closed = openravepy.Interval.Closed start = robot.GetActiveDOFValues() active_indices = robot.GetActiveDOFIndices() # Use the CheckPathAllConstraints helper function to collision check # the straight-line trajectory. We pass dummy values for dq0, dq1, # and timeelapsed since this is a purely geometric check. params = openravepy.Planner.PlannerParameters() params.SetRobotActiveJoints(robot) params.SetGoalConfig(goal) check = params.CheckPathAllConstraints(start, goal, [], [], 0., Closed, options = 15, returnconfigurations = True) # If valid, above function returns (0,None, None, 0) # if not, it returns (1, invalid_config ,[], time_when_invalid), # in which case we identify and raise appropriate error. if check[0] != 0: q = check[1] # Check for joint limit violation q_limit_min, q_limit_max = robot.GetActiveDOFLimits() lower_position_violations = (q < q_limit_min) if lower_position_violations.any(): index = lower_position_violations.nonzero()[0][0] raise JointLimitError(robot, dof_index=active_indices[index], dof_value=q[index], dof_limit=q_limit_min[index], description='position') upper_position_violations = (q> q_limit_max) if upper_position_violations.any(): index = upper_position_violations.nonzero()[0][0] raise JointLimitError(robot, dof_index=active_indices[index], dof_value=q[index], dof_limit=q_limit_max[index], description='position') # Check for collision robot.SetActiveDOFValues(q) report = CollisionReport() if self.env.CheckCollision(robot, report=report): raise CollisionPlanningError.FromReport(report) elif robot.CheckSelfCollision(report=report): raise SelfCollisionPlanningError.FromReport(report) raise PlanningError('Straight line trajectory is not valid.' ) # Create a two-point trajectory that starts at our current # configuration and takes us to the goal. traj = openravepy.RaveCreateTrajectory(self.env, '') cspec = robot.GetActiveConfigurationSpecification('linear') active_indices = robot.GetActiveDOFIndices() start_waypoint = numpy.zeros(cspec.GetDOF()) cspec.InsertJointValues(start_waypoint, start, robot, active_indices, False) traj.Init(cspec) traj.Insert(0, start_waypoint.ravel()) # Make the trajectory end at the goal configuration, as long as it # was not identical to the start configuration. if not numpy.allclose(start, goal): goal_waypoint = numpy.zeros(cspec.GetDOF()) cspec.InsertJointValues(goal_waypoint, goal, robot, active_indices, False) traj.Insert(1, goal_waypoint.ravel()) # Tag the return trajectory as smooth (in joint space) and return it. SetTrajectoryTags(traj, {Tags.SMOOTH: True}, append=True) return traj
95b392061287b5464c619f8de4bf6057afaac836
[ "Markdown", "Python" ]
4
Python
athackst/prpy
1a1a08688e1ae8424c7ae541399a0329401406dd
f8723c0953066871883682fc62af8281e79546f4
refs/heads/master
<repo_name>icc3101-201920/laboratorio-06-Anchor9<file_sep>/Laboratorio_5_OOP_201902/Visualization.cs using System; using System.Linq; using System.Text; using System.Collections.Generic; using System.Threading.Tasks; using System.IO; using Laboratorio_5_OOP_201902.Cards; // asi puedo llamar a cards namespace Laboratorio_5_OOP_201902 { //Manejar inputs y outpus -- interaccion usuario public static class Visualization { public static void ShowHand(Hand hand) { //Game game = new Game(); //game.AddDecks(); //game.AddCaptains(); //Player player = new Player(); //Board board = new Board(); //player.Board = board; //player.Deck = game.Decks[0]; //player.Deck.Shuffle(); //player.FirstHand(); //player.ChooseCaptainCard(game.Captains[0]); //Console.WriteLine($"Player captain card: {player.Captain.Name}\n"); //int counter = 1; //Console.WriteLine("Player Hand:"); //foreach (Card card in player.Hand.Cards) int contador = 0; // parecido al for de arriba foreach (Card card in hand.Cards) { if (card.GetType().Name == nameof(SpecialCard)) { Console.ForegroundColor = ConsoleColor.Blue; Console.Write($"({contador++}) {card.Name} ({card.GetType()})"); } if (card.GetType().Name == nameof(CombatCard)) { Console.ForegroundColor = ConsoleColor.Red; Console.Write($"({contador++}) {card.Name} ({card.GetType()})"); } } } public static void ShowDecks(List<Deck> decks) { int contador = 0; Console.WriteLine("Select Deck: "); foreach (Deck deck in decks) { Console.WriteLine($"({contador}) Deck {contador + 1}"); contador = contador +1; } } public static void ShowCaptains(List<SpecialCard> captains) { int contador = 0; foreach (SpecialCard captain in captains) { Console.WriteLine($"({contador}) Captain: {captain.Name}: {captain.Effect}"); contador = contador + 1; } } public static void ConsoleError(string message) { Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine(message); Console.BackgroundColor = ConsoleColor.Black; } public static void ShowProgramMessage(string message) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(message); Console.ForegroundColor = ConsoleColor.White; } static void ShowListOptions(List<string> options, string message = null) { int contador = 0; if (message != null) { Console.WriteLine(message); foreach (string option in options) { Console.WriteLine($"({contador}) {option}"); } } } public static void ClearConsole() { Console.Clear(); } // falta completar metodo getuserinput static void GetUserInput(int maxInput, bool stopper = false) { while (true) { string Input = Console.ReadLine(); int number; try { number = Convert.ToInt32(); // Que va en el int } } } } }
19b085f89dd2c40be10b43a4e7e817ee44b7d611
[ "C#" ]
1
C#
icc3101-201920/laboratorio-06-Anchor9
3b5c5f01882ffcdcd289199078858f9e5826b96d
405a65414ce57cc9128ef2bbaf8dd69f914ba4ec
refs/heads/master
<repo_name>Warrior-47/File-Share<file_sep>/File Share/src/file/share/Client.java package file.share; import java.io.*; import java.net.*; public class Client { public static final String ANSI_RESET = "\u001B[0m"; public static final String ANSI_GREEN = "\u001B[32m"; public static void main(String[] args) { try { Socket s = new Socket("192.168.1.103",1830); System.out.println("Connection Established."); byte[] file = new byte[65536]; DataInputStream temp = new DataInputStream(s.getInputStream()); String dirName = (String)temp.readUTF(); String path = "downloaded files\\"; if(!dirName.equals(" ")) { path += dirName; System.out.println("path created: "+new File(path).mkdir()); path += "\\"; } int noOfFiles = temp.readInt(); File[] objects = new File[noOfFiles]; long[] fileSize = new long[noOfFiles]; for(int i=0;i<noOfFiles;i++) { String fileName = temp.readUTF(); objects[i] = new File(path+fileName); fileSize[i] = temp.readLong(); } long dirSize = 0; InputStream receive = s.getInputStream(); for(int i=0;i<noOfFiles;i++) { System.out.println("Downloading File: "+objects[i].getName()+"\nFile Size: "+fileSize[i]+" Bytes"); FileOutputStream fos = new FileOutputStream(objects[i]); long dataLeft = fileSize[i]; long totalData = 0; int dataRead = 0; long start = System.currentTimeMillis(); boolean failed = false; while((dataRead=receive.read(file, 0, Math.min(file.length,(int)dataLeft)))==0){ long end = System.currentTimeMillis(); if((end-start)>=60000) { failed = true; break; } } System.out.println("Downloading..."); boolean t5, f0, s5; t5 = f0 = s5 = true; while(dataRead!=-1 && dataLeft!=0) { fos.write(file,0,dataRead); dataLeft -= dataRead; totalData += dataRead; double pern = (double)totalData/fileSize[i]*100; if(t5 && pern>=25.0 && pern<50.0) { System.out.printf("%s%.1f%% Downloaded.%s\n",ANSI_GREEN,pern,ANSI_RESET); t5 = false; }else if(f0 && pern >=50 && pern<75.0) { f0 = false; System.out.printf("%s%.1f%% Downloaded.%s\n",ANSI_GREEN,pern,ANSI_RESET); }else if(s5 && pern>=75 && pern<100.0) { s5 = false; System.out.printf("%s%.1f%% Downloaded.%s\n",ANSI_GREEN,pern,ANSI_RESET); }else if(pern==100){ System.out.printf("%s%.1f%% Downloaded.%s\n",ANSI_GREEN,pern,ANSI_RESET); } if(totalData==fileSize[i]) break; start = System.currentTimeMillis(); while((dataRead=receive.read(file, 0, min(file.length,dataLeft)))==0){ long end = System.currentTimeMillis(); if((end-start)>=60000) { failed = true; break; } } } fos.close(); if(failed) { objects[i].delete(); System.err.println("Failed to Download "+objects[i].getName()+". Check Internet Connection.\nTotal Received: "+totalData); }else { System.out.println(ANSI_GREEN+"Download Completed."+ANSI_RESET); } dirSize += totalData; } System.out.println("Total File Size: "+dirSize); receive.close(); temp.close(); s.close(); }catch(Exception e) { e.printStackTrace(); } } public static void printa(byte[] f, long r) { for(int i=0;i<r;i++) { System.out.println(f[i]); } } public static int min(int x, long y) { if(x<y) return x; return (int)y; } }
2d6dd81b305f7cfe2cf0289df8fac9f5f6c24734
[ "Java" ]
1
Java
Warrior-47/File-Share
f5c3fa0055e182d7b4682c1e94150a7533aa9ce8
37d8c58e31ab78f857f5a242b819181a138405f7
refs/heads/master
<repo_name>ColleenWoolsey/building-component-function<file_sep>/README.md # Student-Components PRACTICE EXERCISE 1. Created 3 different functions to add h1, section, and aside elements with a given css class inside an article container to display student name, course and comment info. EMPLOYED ${} SUBSTITUTION 2. Used these three functions to create a student component function EMPLOYED document.QuerySelector to select container 3. Iterated through data objects separating students by grade EMPLOYED A for ( of ) with a nested if else loop CHALLENGE: Use Rest Operator 1. Pass multiple arguments into component building function without having to define each one in the argument list CHALLENGE: Generic HTML Function 1. Created a more generic function that takes the element argument as well as the style and content arguments. ADVANCED CHALLENGE: Using createElement for Components 1. The learning objective of this challenge was to move away from using string templates completely, and use the methods of createElement() and appendChild() to create DOM components. 2. Created a simple list of chat messages ADVANCED CHALLENGE: DOM Fragments 1. Used code from previous challenge to create multiple components and add them to the Dom as a one time operation<file_sep>/scripts.js const students = [ { name: "<NAME>", course: "History", info: "Failed last exam", score: 59 }, { name: "<NAME>", course: "History", info: "Has completed all homework", score: 91 }, { name: "<NAME>", course: "History", info: "Wonderful at helping other students", score: 88 }, { name: "<NAME>", course: "History", info: "Has never missed a class or exam", score: 92 }, { name: "<NAME>", course: "History", info: "Sub-par performance all around", score: 64 }, { name: "<NAME>", course: "History", info: "Wonderful student", score: 97 }, { name: "<NAME>", course: "History", info: "Smokes too much. Distracting.", score: 76 }, { name: "<NAME>", course: "History", info: "Falls asleep in class", score: 79 }, { name: "<NAME>", course: "History", info: "Talks too much", score: 83 }, { name: "<NAME>", course: "History", info: "Asks pointless, unrelated questions", score: 78 }, { name: "<NAME>", course: "History", info: "When was the last time he attended class?", score: 48 }, { name: "<NAME>", course: "History", info: "Needs to contribute to in-class discussions", score: 95 } ] // const h1 = (title, style) => { // return `<h1 class="${style}">${title}</h1>` // } // CHALLENGE: Use Rest Operator // 1. Pass multiple arguments into component building function // without having to define each one in the argument list const h1 = (...props) => { return `<h1 class="${props[1]}">${props[0]}</h1>` } // const section = (title, style) => { // return `<section class="${style}">${title}</section>` // } const section = (...props) => { return `<section class="bordered dashed ${props[1]}">${props[0]}</section>` } // const aside = (title, style) => { // return `<aside class="${style}">${title}</aside>` // } const aside = (...props) => { return `<aside class="${props[1]}">${props[0]}</aside>` } // const studentp = function(name, course, info) { // return `<article id="student"> // ${h1(name, "xx-large passing")} // ${section(course, "bordered dashed section--padded")} // ${aside(info, "pushRight")} // </article>` // } // CHALLENGE: Generic HTML Function // 1. Created a more generic function that takes the element // argument as well as the style and content arguments. const studentp = (...props) => { return `<article id="student"> ${h1(props[0], "xx-large passing")} ${section(props[1], "bordered dashed section--padded")} ${aside(props[2], "pushRight")} </article>` }; const studentf = function(name, course, info) { return `<article id="student"> ${h1(name, "xx-large failing")} ${section(course, "section--padded")} ${aside(info, "pushRight")} </article>` } const container = document.querySelector("#container"); students.forEach(function(student) { let studentComponent = ""; if (student.score >= 60) { studentComponent = studentp(student.name, student.course, student.info); let newarticle = document.createElement('article'); newarticle.innerHTML = studentComponent; document.querySelector('div').appendChild(newarticle); } else { studentComponent = studentf(student.name, student.course, student.info); let newarticle = document.createElement('article'); newarticle.innerHTML = studentComponent; document.querySelector('div').appendChild(newarticle); } console.log(studentComponent) }); // Here the first two arguments go into variables and the // rest go into titles array: // function showName(firstName, lastName, ...titles) { // alert( firstName + ' ' + lastName ); // <NAME> // // the rest go into titles array // // i.e. titles = ["Consul", "Imperator"] // alert( titles[0] ); // Consul // alert( titles[1] ); // Imperator // alert( titles.length ); // 2 // } // showName("Julius", "Caesar", "Consul", "Imperator"); // Advanced Challenge: Using createElement for Components const messageArticle = document.querySelector("#messages"); let messageSection = document.createElement("section"); messageSection.textContent = "Are we doing fireworks this year?"; messageArticle.appendChild(messageSection); console.log(messageSection) messageSection = document.createElement("section"); messageSection.textContent = `After last year's "tree incident", should we?`; messageArticle.appendChild(messageSection); console.log(messageSection) messageSection = document.createElement("section"); messageSection.textContent = "The fire fighters put it out in like a minute. Wasn't even a real fire."; messageArticle.appendChild(messageSection); console.log(messageSection) messageSection = document.createElement("section"); messageSection.textContent = "We can set them off in the street."; messageArticle.appendChild(messageSection); console.log(messageSection) messageSection = document.createElement("section"); messageSection.textContent = "Our neighbors' houses are flammable, too"; messageArticle.appendChild(messageSection); console.log(messageSection) // Advanced Challenge: DOM Fragments const fragment = document.createDocumentFragment(); const message1 = document.createElement("section"); message1.textContent = "Are we doing fireworks this year?"; fragment.appendChild(message1); const message2 = document.createElement("section"); message2.textContent = `After last year's "tree incident", should we?`; fragment.appendChild(message2); const message3 = document.createElement("section"); message3.textContent = "The fire fighters put it out in like a minute. Wasn't even a real fire."; fragment.appendChild(message3); const message4 = document.createElement("section"); message4.textContent = "We can set them off in the street."; fragment.appendChild(message4); const message5 = document.createElement("section"); message5.textContent = "Our neighbors' houses are flammable, too"; fragment.appendChild(message5); document.querySelector("#messages").appendChild(fragment);
0d1dba23e4599406edc882616704bda01d422b78
[ "Markdown", "JavaScript" ]
2
Markdown
ColleenWoolsey/building-component-function
6070a0834b19e236f68374676988bac15b9bba46
684361eb7c847ba608f421315127ecd30b098161
refs/heads/master
<file_sep>package com.coldradio.benzene.library; import android.graphics.Bitmap; import android.text.Spanned; import com.android.volley.Response; import com.coldradio.benzene.compound.Compound; import java.util.List; public abstract class CompoundIndex { final public int searchID; final public String title; final public int cid; final public String mf; final public float mw; final public String IUPAC; private Bitmap bitmap; public Spanned description; public CompoundIndex(int searchID, String title, int cid, String mf, float mw, String IUPAC) { this.searchID = searchID; this.title = title; this.cid = cid; this.mf = mf; this.mw = mw; this.IUPAC = IUPAC; } public void setBitmap(Bitmap bitmap) { this.bitmap = bitmap; } public Bitmap getBitmap() { return bitmap; } public abstract void requestCompound(Response.Listener<List<Compound>> onCompoundReady); public abstract void requestDescription(Response.Listener<Spanned> listener); }<file_sep>package com.coldradio.benzene.compound.funcgroup; import android.graphics.PointF; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.Compound; import com.coldradio.benzene.compound.CompoundReactor; public class Propyl_FG extends Ethyl_FG { public Propyl_FG(Atom a_atom) { super(a_atom); Atom c1 = super.appendAtom(); Atom c2 = c1.getSkeletonAtom(); Compound tmpCompound = CompoundReactor.chainCompound(new PointF[]{a_atom.getPoint(), c1.getPoint(), c2.getPoint()}); Methyl_FG methyl = new Methyl_FG(tmpCompound.getAtom(2)); // append to the last C // delete one H in parentCompound, and adjust the positions of remained two H CompoundReactor.addFunctionalGroupToAtom(super.getCompound(), c2, methyl, true); } @Override public String getName() { return "propyl"; } } <file_sep>package com.coldradio.benzene.library.local; import android.text.Spanned; import com.android.volley.Response; import com.coldradio.benzene.compound.Compound; import com.coldradio.benzene.library.CompoundIndex; import java.util.List; public class LocalCompoundIndex extends CompoundIndex { LocalCompoundIndex(int searchID, String title, int cid, String mf, float mw, String IUPAC) { super(searchID, title, cid, mf, mw, IUPAC); } @Override public void requestCompound(Response.Listener<List<Compound>> onCompoundReady) { } @Override public void requestDescription(Response.Listener<Spanned> listener) { } } <file_sep>package com.coldradio.benzene.compound.funcgroup; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.Bond; import com.coldradio.benzene.compound.Compound; public interface IFunctionalGroup { Compound nextForm(); Compound prevForm(); Compound curForm(); String getName(); Atom appendAtom(); Bond.BondType bondType(); } <file_sep>package com.coldradio.benzene.compound.funcgroup; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.AtomicNumber; import com.coldradio.benzene.compound.CompoundInspector; public class NNN_FG extends NCO_FG { public NNN_FG(Atom a_atom) { super(a_atom); Atom[] c = CompoundInspector.extractSkeletonChain(super.appendAtom(), 3); c[1].setAtomicNumber(AtomicNumber.N); c[2].setAtomicNumber(AtomicNumber.N); } @Override public String getName() { return "NNN"; } } <file_sep>package com.coldradio.benzene.compound.funcgroup; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.AtomicNumber; import com.coldradio.benzene.compound.Bond; import com.coldradio.benzene.compound.CompoundReactor; import com.coldradio.benzene.project.Configuration; import com.coldradio.benzene.util.Geometry; public class CHO_FG extends IsoPropyl_FG { public CHO_FG(Atom a_atom) { super(a_atom); CompoundReactor.deleteAllHydrogen(super.getCompound()); Atom c1 = super.appendAtom(); Atom c2 = c1.getSkeletonAtom(); Atom c2_dot = c1.getSkeletonAtomExcept(c2); c2.setAtomicNumber(AtomicNumber.O); c1.doubleBond(c2); c2.setBond(c1, Bond.BondType.DOUBLE_MIDDLE); c2_dot.setAtomicNumber(AtomicNumber.H); c2_dot.getAtomDecoration().setShowElementName(false); c2_dot.setPoint(Geometry.pointInLine(c1.getPoint(), c2_dot.getPoint(), Configuration.H_BOND_LENGTH_RATIO)); } @Override public String getName() { return "CHO"; } } <file_sep>package com.coldradio.benzene.compound.funcgroup; import android.graphics.PointF; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.Compound; import com.coldradio.benzene.compound.CompoundInspector; import com.coldradio.benzene.compound.CompoundReactor; public class Pentyl_FG extends Butyl_FG { public Pentyl_FG(Atom a_atom) { super(a_atom); Atom[] c = CompoundInspector.extractSkeletonChain(super.appendAtom(), 4); Compound tmpCompound = CompoundReactor.chainCompound(new PointF[]{c[1].getPoint(), c[2].getPoint(), c[3].getPoint()}); Methyl_FG methyl = new Methyl_FG(tmpCompound.getAtom(2)); // append to the last CompoundReactor.addFunctionalGroupToAtom(super.getCompound(), c[3], methyl, true); } @Override public String getName() { return "pentyl"; } } <file_sep>package com.coldradio.benzene.library.rule; import com.coldradio.benzene.compound.Compound; import java.util.ArrayList; import java.util.List; public class RuleSet { private static RuleSet msInstance = new RuleSet(); private List<ICompoundRule> mRuleSet = new ArrayList<>(); private boolean isRegistered(ICompoundRule compoundRule) { for (ICompoundRule rule : mRuleSet) { if (rule == compoundRule) { return true; } } return false; } public RuleSet() { add(new LetteringIfCompoundNotSeenRule()); add(new LetteringIfNotCarbonRule()); add(new DoubleMiddleBondTypeRule()); add(new HFirstWhenLetteringRule()); add(new PutAllHydrogenInOneSideRule()); } public static RuleSet instance() { return msInstance; } public void add(ICompoundRule compoundRule) { if (! isRegistered(compoundRule)) { mRuleSet.add(compoundRule); } } public Compound apply(Compound compound) { for (ICompoundRule rule : mRuleSet) { rule.apply(compound); } return compound; } public List<Compound> apply(List<Compound> compounds) { for (Compound c : compounds) apply(c); return compounds; } public List<Compound> apply(List<Compound> compounds, ICompoundRule rule) { for (Compound c : compounds) rule.apply(c); return compounds; } } <file_sep>package com.coldradio.benzene.util.translate; import com.android.volley.Response; public interface ITranslator { void translateToEnglish(String text, String langType, Response.Listener<String> listener, Response.ErrorListener errorListener); } <file_sep>package com.coldradio.benzene.util.translate; import com.android.volley.Response; public interface ILangDetector { void detectLang(String text, Response.Listener<String> listener, Response.ErrorListener errorListener); } <file_sep>package com.coldradio.benzene.compound; import java.util.BitSet; public class AtomCondition { private AtomicNumber mAtomicNumber; private int mCharge; private BitSet mFieldMask = new BitSet(); private enum CondMask {ATOMIC_NUMBER_MASK, CHARGE_MASK, HAS_HYDROGEN_MASK}; public boolean satisfiedBy(Atom atom) { if (mFieldMask.get(CondMask.ATOMIC_NUMBER_MASK.ordinal()) && atom.getAtomicNumber() != mAtomicNumber) return false; if (mFieldMask.get(CondMask.CHARGE_MASK.ordinal()) && atom.getAtomDecoration().getCharge() != mCharge) return false; if (mFieldMask.get(CondMask.HAS_HYDROGEN_MASK.ordinal()) && CompoundInspector.numberOfHydrogen(atom) == 0) return false; return true; } public AtomCondition atomicNumber(AtomicNumber an) { mAtomicNumber = an; mFieldMask.set(CondMask.ATOMIC_NUMBER_MASK.ordinal()); return this; } public AtomCondition charge(int c) { mCharge = c; mFieldMask.set(CondMask.CHARGE_MASK.ordinal()); return this; } public AtomCondition hasHydrogen() { mFieldMask.set(CondMask.HAS_HYDROGEN_MASK.ordinal()); return this; } } <file_sep>package com.coldradio.benzene.compound.funcgroup; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.CompoundInspector; import com.coldradio.benzene.compound.CompoundReactor; public class CycPentyl_FG extends Pentyl_FG { public CycPentyl_FG(Atom a_atom) { super(a_atom); Atom[] c = CompoundInspector.extractSkeletonChain(super.appendAtom(), 5); CompoundReactor.alkaneToCyclo(super.getCompound(), c, a_atom.getPoint()); } @Override public String getName() { return "cyc-pentyl"; } } <file_sep>package com.coldradio.benzene.project.history; public abstract class History { protected final short mCID; public History(short cID) { mCID = cID; } public abstract void undo(); public abstract void redo(); } <file_sep>package com.coldradio.benzene.util; import android.graphics.PointF; import android.graphics.RectF; public class Geometry { public static PointF cwRotate(PointF current, PointF center, float angle) { float currentToZeroX = current.x - center.x; float currentToZeroY = current.y - center.y; float cos_theta = (float) Math.cos(angle), sin_theta = (float) Math.sin(angle); return new PointF(currentToZeroX * cos_theta - currentToZeroY * sin_theta + center.x, currentToZeroY * cos_theta + currentToZeroX * sin_theta + center.y); } public static float distanceFromPointToPoint(PointF p1, PointF p2) { return (float) Math.sqrt((p2.y - p1.y) * (p2.y - p1.y) + (p2.x - p1.x) * (p2.x - p1.x)); } public static float distanceFromPointToPoint(float x1, float y1, float x2, float y2) { return (float) Math.sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1)); } public static float distanceFromPointToLineSegment(PointF p, PointF l1, PointF l2) { if (angleOfTriangle(p, l1, l2) > MathConstant.RADIAN_90 || angleOfTriangle(p, l2, l1) > MathConstant.RADIAN_90) { // p is out of l1 and l2 return Math.min(distanceFromPointToPoint(p, l1), distanceFromPointToPoint(p, l2)); } else { // p is within l1 and l2 return distanceFromPointToLine(p, l1, l2); } } public static float distanceFromPointToLine(PointF p, PointF l1, PointF l2) { return Math.abs((l2.y - l1.y) * p.x - (l2.x - l1.x) * p.y + l2.x * l1.y - l2.y * l1.x) / distanceFromPointToPoint(l1, l2); } public static PointF zoom(PointF point, PointF center, float ratio) { return zoom(point.x, point.y, center, ratio); } public static PointF zoom(float x, float y, PointF center, float ratio) { float x_dot = x - center.x, y_dot = y - center.y; return new PointF(x_dot * ratio + center.x, y_dot * ratio + center.y); } public static boolean sameSideOfLine(PointF p1, PointF p2, PointF l1, PointF l2) { return whichSideOfLine(p1, l1, l2) * whichSideOfLine(p2, l1, l2) > 0; } public static float whichSideOfLine(PointF p, PointF l1, PointF l2) { return (p.x - l1.x) * (l2.y - l1.y) - (p.y - l1.y) * (l2.x - l1.x); } public static PointF centerOfLine(PointF p1, PointF p2) { return new PointF((p1.x + p2.x) / 2, (p1.y + p2.y) / 2); } public static PointF symmetricToLine(PointF p, PointF l1, PointF l2) { float args[] = lineEquationFrom2Points(l1, l2); // https://math.stackexchange.com/questions/1013230/how-to-find-coordinates-of-reflected-point return new PointF((p.x * (args[1] * args[1] - args[0] * args[0]) - 2 * args[0] * (args[1] * p.y + args[2])) / (args[1] * args[1] + args[0] * args[0]), (p.y * (args[0] * args[0] - args[1] * args[1]) - 2 * args[1] * (args[0] * p.x + args[2])) / (args[1] * args[1] + args[0] * args[0])); } public static PointF symmetricToPoint(PointF p, PointF center) { return new PointF(2 * center.x - p.x, 2 * center.y - p.y); } public static float[] lineEquationFrom2Points(PointF p1, PointF p2) { float[] args; if (p1 == p2) { args = new float[]{0, 0, 0}; } else if (p1.x == p2.x) { args = new float[]{1, 0, -p1.x}; } else if (p1.y == p2.y) { args = new float[]{0, 1, -p1.y}; } else { args = new float[]{1, -(p1.x - p2.x) / (p1.y - p2.y), (p1.x - p2.x) / (p1.y - p2.y) * p1.y - p1.x}; } return args; } public static float interiorAngleOfPolygon(int numberOfSide) { return (float) Math.toRadians((180.0f * numberOfSide - 360) / numberOfSide); } public static PointF[] regularTrianglePoint(PointF p1, PointF p2) { return new PointF[]{cwRotate(p1, p2, (float) Math.toRadians(60)), cwRotate(p1, p2, (float) Math.toRadians(-60))}; } public static float angleOfTriangle(PointF p1, PointF p2, PointF center) { if (p1.equals(p2) || p2.equals(center) || center.equals(p1)) { return Float.NaN; } // calculated from cos 2 law float a = distanceFromPointToPoint(center, p1); float b = distanceFromPointToPoint(center, p2); float c = distanceFromPointToPoint(p1, p2); float arg = (a * a + b * b - c * c) / (2 * a * b); if (arg >= 1) { return 0; } else if (arg <= -1) { return MathConstant.RADIAN_180; } else { return (float) Math.acos(arg); } } public static float cwAngle(PointF from, PointF to, PointF center) { // this function returns always positive value float Xfrom = from.x - center.x, Yfrom = from.y - center.y; float Xto = to.x - center.x, Yto = to.y - center.y; float angle = (float) (Math.atan2(Yto, Xto) - Math.atan2(Yfrom, Xfrom)); if (angle < 0) angle = MathConstant.RADIAN_360 + angle; return angle; } public static float center(float[] points) { float center = 0; for (float point : points) { center += point; } return center / points.length; } public static PointF[] lineOrthogonalShift(PointF l1, PointF l2, float shiftRatio, boolean up) { PointF[] shifted = new PointF[2]; // rotate l2 90 Degrees against l1 shifted[0] = cwRotate(l2, l1, MathConstant.RADIAN_90 * (up ? -1 : 1)); shifted[0] = zoom(shifted[0].x, shifted[0].y, l1, shiftRatio); shifted[1] = cwRotate(l1, l2, MathConstant.RADIAN_90 * (up ? 1 : -1)); shifted[1] = zoom(shifted[1].x, shifted[1].y, l2, shiftRatio); return shifted; } public static PointF orthogonalPointToLine(PointF l1, PointF l2, float shiftRatio, boolean up) { // return orthogonal point to line (l1, l2). the returned point goes through l2 PointF shifted = cwRotate(l1, l2, MathConstant.RADIAN_90 * (up ? -1 : 1)); shifted = zoom(shifted.x, shifted.y, l2, shiftRatio); return shifted; } public static PointF cwCenterOfAngle(PointF from, PointF to, PointF c) { return cwRotate(from, c, cwAngle(from, to, c) / 2); } public static PointF pointInLine(PointF l1, PointF l2, float ratioFromL1, PointF result) { // if ratioFromL1 is 0, l1 is returned, if 1 l2 is returned result.set(l1.x, l1.y); result.offset((l2.x - l1.x) * ratioFromL1, (l2.y - l1.y) * ratioFromL1); return result; } public static PointF pointInLine(PointF l1, PointF l2, float ratioFromL1) { return pointInLine(l1, l2, ratioFromL1, new PointF()); } public static RectF enlarge(RectF rect, float dxy) { rect.left -= dxy; rect.top -= dxy; rect.right += dxy; rect.bottom += dxy; return rect; } public static boolean onRight(PointF ref, PointF p) { return p.x > ref.x; } } <file_sep>package com.coldradio.benzene.compound.funcgroup; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.AtomicNumber; import com.coldradio.benzene.compound.Bond; import com.coldradio.benzene.compound.Compound; import com.coldradio.benzene.compound.CompoundInspector; import com.coldradio.benzene.compound.CompoundReactor; import com.coldradio.benzene.project.Configuration; import com.coldradio.benzene.util.Geometry; import java.util.List; public class SO2Me_FG extends Ethyl_FG { public SO2Me_FG(Atom a_atom) { super(a_atom); Atom[] c = CompoundInspector.extractSkeletonChain(super.appendAtom(), 2); c[0].setAtomicNumber(AtomicNumber.S); List<Atom> h_of_s = CompoundInspector.allHydrogens(c[0]); Atom o1 = h_of_s.get(0); Atom o2 = h_of_s.get(1); o1.setAtomicNumber(AtomicNumber.O); o1.setBond(c[0], Bond.BondType.DOUBLE_MIDDLE); o2.setAtomicNumber(AtomicNumber.O); o2.setBond(c[0], Bond.BondType.DOUBLE_MIDDLE); o1.setPoint(Geometry.zoom(o1.getPoint(), c[0].getPoint(), 1/Configuration.H_BOND_LENGTH_RATIO)); o2.setPoint(Geometry.zoom(o2.getPoint(), c[0].getPoint(), 1/Configuration.H_BOND_LENGTH_RATIO)); } @Override public String getName() { return "SO2Me"; } } <file_sep>package com.coldradio.benzene.compound; public class AtomDecoration { public enum Direction { TOP, BOTTOM, LEFT, RIGHT } public enum Marker { NONE, MARKER_1, MARKER_2, MARKER_3, MARKER_4, MARKER_5, MARKER_6, MARKER_7, MARKER_8 } public enum UnsharedElectron { NONE, SINGLE, DOUBLE } private boolean mShowElementName = true; private UnsharedElectron[] mUnsharedElectron = new UnsharedElectron[4]; private int mCharge = 0; private Marker mChargeAsCircle = Marker.NONE; private Marker mStarMarker = Marker.NONE; private boolean mLettering; public AtomDecoration() { for (int ii = 0; ii < mUnsharedElectron.length; ++ii) { mUnsharedElectron[ii] = UnsharedElectron.NONE; } } public void setMarker(Marker marker) { mStarMarker = marker; } public Marker getMarker() { return mStarMarker; } public void setChargeAsCircle(Marker chargeAsCircle) { mChargeAsCircle = chargeAsCircle; } public Marker getChargeAsCircle() { return mChargeAsCircle; } public UnsharedElectron getUnsharedElectron(Direction direction) { return mUnsharedElectron[direction.ordinal()]; } public void setUnsharedElectron(Direction direction, UnsharedElectron unsharedElectron) { mUnsharedElectron[direction.ordinal()] = unsharedElectron; } public void setCharge(int charge) { mCharge = charge; } public int getCharge() { return mCharge; } public boolean getShowElementName() { return mShowElementName; } public void setShowElementName(boolean show) { mShowElementName = show; } public void lettering(boolean on) { mLettering = on; } public boolean isLettering() { return mLettering; } public AtomDecoration copy() { AtomDecoration copied = new AtomDecoration(); copied.mShowElementName = mShowElementName; for (int ii = 0; ii < mUnsharedElectron.length; ++ii) { copied.mUnsharedElectron[ii] = mUnsharedElectron[ii]; } copied.mCharge = mCharge; copied.mChargeAsCircle = mChargeAsCircle; copied.mStarMarker = mStarMarker; copied.mLettering = mLettering; return copied; } } <file_sep>package com.coldradio.benzene.util; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.support.v4.content.FileProvider; import com.coldradio.benzene.project.Configuration; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.nio.channels.FileChannel; import java.text.DateFormat; import java.util.Date; public class FileUtil { public static String INVALID_CHARS = "\\/:*?\"<>|&%"; private static int BUF_SIZE = 1024; private static String prefixFromName(String name) { if (name.endsWith(")")) { int varStartInd = name.lastIndexOf('('); for (int ii = varStartInd + 1; ii < name.length() - 1; ii++) { if (!Character.isDigit(name.charAt(ii))) { return name; } } return name.substring(0, varStartInd); } return name; } public static void closeIgnoreException(FileChannel fc) { if (fc != null) { try { fc.close(); } catch (Exception e) { } } } public static void closeIgnoreException(Reader reader) { if (reader != null) { try { reader.close(); } catch (Exception e) { } } } public static void closeIgnoreException(Writer writer) { if (writer != null) { try { writer.close(); } catch (Exception e) { } } } public static void closeIgnoreException(OutputStream out) { if (out != null) { try { out.close(); } catch (Exception e) { } } } public static void closeIgnoreException(InputStream in) { if (in != null) { try { in.close(); } catch (Exception e) { } } } public static boolean rename(String sourcePath, String destPath) { return new File(sourcePath).renameTo(new File(destPath)); } public static boolean delete(String filePath) { return new File(filePath).delete(); } public static String availableFileName(String name) { return fileNameWithoutExt(availableFileNameExt(AppEnv.instance().projectFileDir(), name, Configuration.PROJECT_FILE_EXT)); } public static String availableFileNameExt(String dirPath, String name, String postfix) { String prefix = prefixFromName(name); File candidate = new File(dirPath, prefix + postfix); if (name.equals(prefix) && !candidate.exists()) { return candidate.getName(); } for (int ii = 1; ; ++ii) { candidate = new File(dirPath, prefix + "(" + ii + ")" + postfix); if (!candidate.exists()) { return candidate.getName(); } } } public static String fileNameWithoutExt(String name) { int dot_index = name.lastIndexOf('.'); if (dot_index < 0) { return name; } return name.substring(0, dot_index); } public static boolean copy(Uri sourceUri, String destPath) { InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = AppEnv.instance().getApplicationContext().getContentResolver().openInputStream(sourceUri); outputStream = new FileOutputStream(destPath); byte[] bytes = new byte[BUF_SIZE]; while (true) { int count = inputStream.read(bytes, 0, BUF_SIZE); if (count == -1) break; outputStream.write(bytes, 0, count); } return true; } catch (Exception e) { return false; } finally { closeIgnoreException(inputStream); closeIgnoreException(outputStream); } } public static boolean copy(String sourcePath, String destPath) { FileChannel sourceChannel = null; FileChannel destChannel = null; try { sourceChannel = new FileInputStream(sourcePath).getChannel(); destChannel = new FileOutputStream(destPath).getChannel(); destChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); return true; } catch (Exception e) { return false; } finally { closeIgnoreException(sourceChannel); closeIgnoreException(destChannel); } } public static boolean validFileName(String name) { if (name.equals(".") || name.equals("..")) { return false; } else { for (int ii = 0; ii < name.length(); ++ii) { if (INVALID_CHARS.indexOf(name.charAt(ii)) >= 0) { return false; } } } return true; } public static long lastModifiedTime(String filePath) { File file = new File(filePath); if (file.exists()) return file.lastModified(); return 0; } public static String toDateTimeString(long timeInMs) { Date date = new Date(); date.setTime(timeInMs); return DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT).format(date); } public static boolean exists(String fileName) { return new File(AppEnv.instance().projectFileDir(), fileName + Configuration.PROJECT_FILE_EXT).exists(); } public static boolean share(String filePath, Activity activity) { try { Intent share = new Intent(Intent.ACTION_SEND); File file = new File(filePath); if (!file.exists()) { return false; } if (filePath.endsWith(Configuration.IMAGE_FILE_EXT)) { share.setType("image/" + Configuration.IMAGE_FILE_EXT.substring(1)); } else { share.setType("text/xml"); } Uri uri = FileProvider.getUriForFile(activity, "com.coldradio.benzene.fileprovider", file); share.putExtra(Intent.EXTRA_STREAM, uri); activity.startActivity(Intent.createChooser(share, "Share to Others")); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public static boolean makeDirIfNotExist(String path) { File dir = new File(path); if (dir.exists() || dir.mkdirs()) { return true; } return false; } public static void removeAllFilesInDir(String path) { File dirFile = new File(path); File[] files = dirFile.listFiles(); if (files != null) { for (File file : files) { file.delete(); } } } public static void browseFile(int requestCode) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("*/*"); AppEnv.instance().getCurrentActivity().startActivityForResult(intent, requestCode); } public static String fileNameExt(String filePath) { int cut = filePath.lastIndexOf('/'); if (cut < 0) { return filePath; } return filePath.substring(cut + 1); } public static boolean isValidProjectFile(Uri uri) { InputStream inputStream = null; try { inputStream = AppEnv.instance().getApplicationContext().getContentResolver().openInputStream(uri); byte[] bytes = new byte[100]; int count = inputStream.read(bytes, 0, 100); if (count == -1) { return false; } String firstLine = new String(bytes); if (firstLine.contains("Atom") || firstLine.contains("AID")) { return true; } return false; } catch (Exception e) { return false; } finally { closeIgnoreException(inputStream); } } public static Bitmap loadBitmap(String fileName) { File file = new File(AppEnv.instance().projectFileDir() + fileName + Configuration.IMAGE_FILE_EXT); Bitmap bitmap = null; if (file.exists()) { bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); } return bitmap; } } <file_sep>package com.coldradio.benzene.library.rule; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.AtomicNumber; import com.coldradio.benzene.compound.Compound; import com.coldradio.benzene.compound.CompoundArranger; import com.coldradio.benzene.compound.CompoundInspector; public class LetteringIfCompoundNotSeenRule implements ICompoundRule { @Override public Compound apply(Compound compound) { if (CompoundInspector.lessThanTwoSkeletonAtom(compound)) { for (Atom atom : compound.getAtoms()) { if (atom.getAtomicNumber() != AtomicNumber.H) { atom.getAtomDecoration().lettering(true); CompoundArranger.showAllHydrogen(atom, false); } } } return compound; } } <file_sep>package com.coldradio.benzene.library.local; import android.content.res.Resources; import com.coldradio.benzene.library.CompoundIndex; import com.coldradio.benzene.library.ICompoundSearch; import java.util.ArrayList; import java.util.List; public class LocalCompounds { private List<CompoundIndex> mAllCompounds = new ArrayList<>(); private static LocalCompounds smInstance = new LocalCompounds(); private LocalCompounds() { } public static LocalCompounds instance() { return smInstance; } public void parseLibrary(Resources resources) { // when raw directory is empty. R.raw is unidentified. // if (mAllCompounds.isEmpty()) { // Field[] fields = R.raw.class.getFields(); // Gson gson = new Gson(); // // for (Field field : fields) { // String res_name = field.getName(); // // if (res_name.startsWith("structure")) { // Reader reader = null; // try { // reader = new InputStreamReader(resources.openRawResource(field.getInt(field))); // PC_Compound_JSON compound_json = gson.fromJson(reader, CompoundStructure_JSON.class).PC_Compounds.get(0); // Compound cmpd = RuleSet.instance().apply(PubChemCompoundFactory.create(compound_json)); // // mAllCompounds.add(new LocalCompoundIndex("", -1, "", -1, compound_json.preferredIUPACName())); // } catch (IllegalAccessException iae) { // // skip this resource // } finally { // FileUtil.closeIgnoreException(reader); // } // } // } // } } public CompoundIndex getCompoundIndex(int index) { if (index >= 0 && index < mAllCompounds.size()) { return mAllCompounds.get(index); } return null; } public int size() { return mAllCompounds.size(); } public List<CompoundIndex> search(ICompoundSearch.KeywordType keywordType, String keyword) { if (keyword == null || keyword.isEmpty()) { return null; } List<CompoundIndex> result = new ArrayList<>(); for (CompoundIndex index : mAllCompounds) { if (index.title.contains(keyword) || index.IUPAC.contains(keyword) || String.valueOf(index.cid).contains(keyword) || index.mf.contains(keyword)) result.add(index); } return result; } } <file_sep>package com.coldradio.benzene.view.drawer; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.RectF; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.AtomicNumber; import com.coldradio.benzene.compound.Bond; import com.coldradio.benzene.project.Configuration; import com.coldradio.benzene.util.Geometry; public class DrawingLib { private static Rect drawTextSubscript(String txt, int start, int end, Rect prevBounds, boolean toRight, boolean bgOn, int bgColor, Canvas canvas, Paint paint) { float origTextSize = paint.getTextSize(); paint.setTextSize(origTextSize * Configuration.SUBSCRIPT_SIZE_RATIO); // when subscripting, the char is overlapped with the previous char. so give some padding prevBounds.offset(toRight ? 2 : 0, 0); Rect myBounds = drawChar(txt, start, end, prevBounds, toRight, bgOn, bgColor, canvas, paint); paint.setTextSize(origTextSize); return myBounds; } private static Rect drawChar(String txt, int start, int end, Rect prevBounds, boolean toRight, boolean bgOn, int bgColor, Canvas canvas, Paint paint) { int prevColor = paint.getColor(); Rect myBounds = new Rect(); // calc my bounds paint.getTextBounds(txt, start, end, myBounds); if (toRight) { myBounds.offsetTo(prevBounds.right, prevBounds.bottom - myBounds.height()); } else { myBounds.offsetTo(prevBounds.left, prevBounds.bottom - myBounds.height()); myBounds.offset(-myBounds.width(), 0); } if (bgOn) { paint.setColor(bgColor); canvas.drawRect(myBounds, paint); paint.setColor(prevColor); } paint.setStyle(Paint.Style.FILL); canvas.drawText(txt, start, end, myBounds.left, myBounds.bottom, paint); return myBounds; } private static Rect charBounds = new Rect(); private static void drawText(String text, PointF centerOfFirstLetter, boolean toRight, boolean bgOn, int bgColor, Canvas canvas, Paint paint) { charBounds = DrawingLib.atomEnclosingRect("C", centerOfFirstLetter, charBounds); int topOrigTextLine = charBounds.top; if (toRight) { // 2. offset to left by the character's width charBounds.offset(-charBounds.width(), 0); } else { charBounds.offset(charBounds.width(), 0); } for (int ii = (toRight ? 0 : text.length() - 1); ii < text.length() && ii >= 0; ii = ii + (toRight ? 1 : -1)) { if (Character.isDigit(text.charAt(ii))) { charBounds = drawTextSubscript(text, ii, ii + 1, charBounds, toRight, bgOn, bgColor, canvas, paint); charBounds.top = topOrigTextLine; } else if (text.charAt(ii) == '+' || text.charAt(ii) == '-') { charBounds = drawTextSuperscript(text, ii, ii + 1, charBounds, toRight, bgOn, bgColor, canvas, paint); charBounds.top = topOrigTextLine; } else { charBounds = drawChar(text, ii, ii + 1, charBounds, toRight, bgOn, bgColor, canvas, paint); } // give some padding after the first letter charBounds.offset(toRight ? 3 : -3, 0); } } private static int centerBias(Atom atom, PointF center, PointF l1, PointF l2) { int bias = 0; for (Bond bond : atom.getBonds()) { Atom boundAtom = bond.getBoundAtom(); PointF boundAtomPoint = boundAtom.getPoint(); // here address compare for boundAtomPoint is intentionally used instead of equals() if (boundAtom.getAtomicNumber() != AtomicNumber.H && boundAtomPoint != l1 && boundAtomPoint != l2) { bias += (Geometry.sameSideOfLine(boundAtomPoint, center, l1, l2) ? 1 : -1); } } return bias; } static Rect atomEnclosingRect(String atomName, PointF atomXY, Rect result) { int oneCharWidth = PaintSet.instance().fontWidth(PaintSet.PaintType.GENERAL), oneCharHeight = PaintSet.instance().fontHeight(PaintSet.PaintType.GENERAL); result.set(0, 0, oneCharWidth * atomName.length(), oneCharHeight); result.offsetTo((int) atomXY.x - oneCharWidth / 2, (int) atomXY.y - oneCharHeight / 2); return result; } private static RectF msRectF = new RectF(); static void drawCwArc(PointF start, PointF end, PointF center, Canvas canvas, Paint paint) { // https://stackoverflow.com/questions/4196749/draw-arc-with-2-points-and-center-of-the-circle float r = Geometry.distanceFromPointToPoint(start, center); float startAngle = (float) (180 / Math.PI * Math.atan2(start.y - center.y, start.x - center.x)); float endAngle_minus_startAngle = (float) (180 / Math.PI * Math.atan2(end.y - center.y, end.x - center.x)) - startAngle; if (endAngle_minus_startAngle < 0) { endAngle_minus_startAngle += 360; } msRectF.set(center.x - r, center.y - r, center.x + r, center.y + r); canvas.drawArc(msRectF, startAngle, endAngle_minus_startAngle, false, paint); } static Rect drawTextSuperscript(String txt, Rect prevBounds, boolean bgOn, int bgColor, Canvas canvas, Paint paint) { return drawTextSuperscript(txt, 0, txt.length(), prevBounds, true, bgOn, bgColor, canvas, paint); } static Rect drawTextSuperscript(String txt, int start, int end, Rect prevBounds, boolean toRight, boolean bgOn, int bgColor, Canvas canvas, Paint paint) { float origTextSize = paint.getTextSize(); paint.setTextSize(origTextSize * Configuration.SUPERSCRIPT_SIZE_RATIO); // when subscripting, the char is overlapped with the previous char. so give some padding prevBounds.offset(toRight ? 2 : 0, 0); prevBounds.offset(0, -prevBounds.height() / 2); Rect myBounds = drawChar(txt, start, end, prevBounds, toRight, bgOn, bgColor, canvas, paint); myBounds.offset(0, prevBounds.height() / 2); paint.setTextSize(origTextSize); return myBounds; } static void drawText(String text, PointF centerOfFirstLetter, boolean bgOn, int bgColor, Canvas canvas, Paint paint) { if (text.length() > 0 && text.charAt(0) == 'H') { drawText(text, centerOfFirstLetter, false, bgOn, bgColor, canvas, paint); } else { drawText(text, centerOfFirstLetter, true, bgOn, bgColor, canvas, paint); } } public static PointF centerForDoubleBond(Atom a1, Atom a2, boolean opposite) { PointF a1p = a1.getPoint(), a2p = a2.getPoint(); Atom before_a1 = a1.getSkeletonAtomExcept(a2); Atom after_a2 = a2.getSkeletonAtomExcept(a1); if (before_a1 != null && after_a2 != null && before_a1 == after_a2) { // propane case, returns the center of the triangle PointF before_a1p = before_a1.getPoint(); PointF center = new PointF((a1p.x + a2p.x + before_a1p.x) / 3, (a1p.y + a2p.y + before_a1p.y) / 3); return opposite ? Geometry.symmetricToLine(center, a1p, a2p) : center; } else { PointF[] centers = Geometry.regularTrianglePoint(a1p, a2p); int centerIndex; // next prefer the center side with more substituents int centerBiasTo0 = 0; centerBiasTo0 += centerBias(a1, centers[0], a1p, a2p); centerBiasTo0 += centerBias(a2, centers[0], a1p, a2p); centerIndex = centerBiasTo0 > 0 ? 0 : 1; if (opposite) { centerIndex = (centerIndex + 1) % 2; } return centers[centerIndex]; } } } <file_sep>package com.coldradio.benzene.library.pubchem; import java.util.List; class AutoComplete_JSON { public class dictionary_terms_JSON { List<String> compound; } public class status_JSON { int code; } status_JSON status; int total; dictionary_terms_JSON dictionary_terms; } <file_sep>package com.coldradio.benzene.view; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.coldradio.benzene.R; import com.coldradio.benzene.project.Project; import com.coldradio.benzene.project.ProjectFile; import com.coldradio.benzene.project.ProjectFileManager; import com.coldradio.benzene.util.AppEnv; import com.coldradio.benzene.util.EditTextDialog; import com.coldradio.benzene.util.FileUtil; import com.coldradio.benzene.util.Notifier; import com.coldradio.benzene.util.StringSearchFilter; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private RecyclerView.Adapter mProjectViewAdapter; private MenuItem mRemoveFilterItem; private RecyclerView.LayoutManager mRecyclerVewLayoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.project_toolbar); setSupportActionBar(toolbar); // call this as early as possible. shall be called with the Application context, not an Activity context AppEnv.instance().initialize(this.getApplicationContext()); DrawerLayout drawer = findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); // add ProjectView ViewGroup project_layout = findViewById(R.id.project_main); if (project_layout != null) { ProjectView projectView = new ProjectView(this); project_layout.addView(projectView); // attach CardView Adapter RecyclerView recyclerView = findViewById(R.id.project_recycler_view); recyclerView.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); mProjectViewAdapter = new ProjectViewAdapter(this); recyclerView.setAdapter(mProjectViewAdapter); mRecyclerVewLayoutManager = recyclerView.getLayoutManager(); } // add FloatingActionBar FloatingActionButton fab = findViewById(R.id.fab_add); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Project.instance().createNew(ProjectFileManager.instance().createNew()); startActivityForResult(new Intent("com.coldradio.benzene.CANVAS"), ActivityRequestCode.START_CANVAS_REQ.ordinal()); } }); } @Override protected void onResume() { super.onResume(); AppEnv.instance().setCurrentActivity(this); } @Override protected void onPause() { super.onPause(); AppEnv.instance().setCurrentActivity(null); } @Override public void onBackPressed() { DrawerLayout drawer = findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.project_toolbar_menu, menu); mRemoveFilterItem = menu.findItem(R.id.action_remove_filter); if (mRemoveFilterItem != null) { mRemoveFilterItem.setVisible(ProjectFileManager.instance().hasFilter()); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_filter) { final EditTextDialog dialog = new EditTextDialog(this); dialog.setOkListener(new View.OnClickListener() { @Override public void onClick(View v) { String inputText = dialog.getInputText().trim(); if (!inputText.isEmpty()) { ProjectFileManager.instance().setFilter(new StringSearchFilter<ProjectFile>(inputText)); dialog.dismiss(); mProjectViewAdapter.notifyDataSetChanged(); if (mRemoveFilterItem != null) { mRemoveFilterItem.setVisible(true); } } else { Notifier.instance().notification("Nothing Inputted"); } } }).setTitle("Project Name Filter").show(); } else if (id == R.id.action_remove_filter) { // here always filter exists ProjectFileManager.instance().setFilter(null); mProjectViewAdapter.notifyDataSetChanged(); if (mRemoveFilterItem != null) { mRemoveFilterItem.setVisible(false); } } else if (id == R.id.action_sort) { ProjectFileManager.instance().sortByNext(); mProjectViewAdapter.notifyDataSetChanged(); } return super.onOptionsItemSelected(item); } @Override public boolean onNavigationItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.help) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/ktnslt/benzene/blob/master/BenzeneTreeTutorial.md")); startActivity(intent); } else if (id == R.id.import_project) { FileUtil.browseFile(ActivityRequestCode.BROWSE_FILE_REQ.ordinal()); } DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ActivityRequestCode.START_CANVAS_REQ.ordinal()) { // Regardless of the resultCode, refresh the list // First, I tried to setData(RESULT_OK) in the CanvasActivity.onDestroy(), but this onActivityResult() called first before onDestroy() called. // It means, I should call setData() in the event handler such as backPressed() or back arrow in the title bar. mProjectViewAdapter.notifyDataSetChanged(); } else if (requestCode == ActivityRequestCode.BROWSE_FILE_REQ.ordinal() && resultCode == RESULT_OK) { if (data != null) { if (ProjectFileManager.instance().importProject(data.getData())) { mProjectViewAdapter.notifyItemInserted(0); if (mRecyclerVewLayoutManager != null) { mRecyclerVewLayoutManager.scrollToPosition(0); } } else { Notifier.instance().notification("Import Failed"); } } } } } <file_sep>package com.coldradio.benzene.compound.funcgroup; import com.coldradio.benzene.compound.AtomicNumber; import com.coldradio.benzene.compound.Compound; public class FunctionalGroupCompound extends Compound { public FunctionalGroupCompound(int[] aids, AtomicNumber[] atomicNumber) { super(aids, atomicNumber); } } <file_sep>package com.coldradio.benzene.library.pubchem; import android.text.Spanned; import com.android.volley.Response; import com.android.volley.VolleyError; import com.coldradio.benzene.compound.Compound; import com.coldradio.benzene.library.CompoundIndex; import com.coldradio.benzene.util.AppEnv; import com.coldradio.benzene.util.Notifier; import java.util.List; public class PubChemCompoundIndex extends CompoundIndex { PubChemCompoundIndex(int searchID, String title, int cid, String mf, float mw, String IUPAC) { super(searchID, title, cid, mf, mw, IUPAC); } @Override public void requestCompound(Response.Listener<List<Compound>> onCompoundReady) { PubChemCompoundRequest request = new PubChemCompoundRequest(super.cid, onCompoundReady, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Notifier.instance().notification(PubChemCompoundIndex.this.title + " NOT created. " + error.toString()); } }); AppEnv.instance().addToNetworkQueue(request); Notifier.instance().notification(PubChemCompoundIndex.this.title + " Requested"); } @Override public void requestDescription(final Response.Listener<Spanned> listener) { PubChemDescriptionRequest request = new PubChemDescriptionRequest(super.cid, listener); AppEnv.instance().addToNetworkQueue(request); } } <file_sep>package com.coldradio.benzene.library.rule; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.AtomicNumber; import com.coldradio.benzene.compound.Compound; import com.coldradio.benzene.compound.CompoundArranger; public class LetteringIfNotCarbonRule implements ICompoundRule { @Override public Compound apply(Compound compound) { // All Carbons shall not show element name, and hide H bond for (Atom atom : compound.getAtoms()) { AtomicNumber an = atom.getAtomicNumber(); if (an == AtomicNumber.C) { atom.getAtomDecoration().setShowElementName(false); } else if (an != AtomicNumber.H) { atom.getAtomDecoration().lettering(true); } CompoundArranger.showAllHydrogen(atom, false); } return compound; } } <file_sep>package com.coldradio.benzene.util.translate; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.toolbox.HttpHeaderParser; import com.coldradio.benzene.util.AppEnv; import com.google.gson.JsonSyntaxException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; public class PapagoTranslator implements ITranslator { class PapagoTranslateResponse_JSON { class PapagoMessage_JSON { class Result_JSON { String srcLangType; String tarLangType; String translatedText; } Result_JSON result; } PapagoMessage_JSON message; } class PapagoTranslateRequest extends Request<PapagoTranslateResponse_JSON> { private Response.Listener<String> mListener; private final String mText; private final String mLangType; PapagoTranslateRequest(String text, String langType, Response.Listener<String> listener, Response.ErrorListener errorListener) { super(Method.POST, "https://openapi.naver.com/v1/papago/n2mt", errorListener); mListener = listener; mText = text; mLangType = langType; } @Override protected Map<String, String> getParams() { Map<String,String> params = new HashMap<>(); params.put("source", mLangType); params.put("target", "en"); params.put("text", mText); return params; } @Override public Map<String, String> getHeaders() { Map<String,String> params = new HashMap<>(); params.put("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); params.put("X-Naver-Client-Id", "7ZS7esNAWAg5jrw9VTpG"); params.put("X-Naver-Client-Secret", "<KEY>"); return params; } @Override protected Response<PapagoTranslateResponse_JSON> parseNetworkResponse(NetworkResponse response) { try { String data = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); PapagoTranslateResponse_JSON json = AppEnv.instance().gson().fromJson(data, PapagoTranslateResponse_JSON.class); return Response.success(json, HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JsonSyntaxException e) { return Response.error(new ParseError(e)); } } @Override protected void deliverResponse(PapagoTranslateResponse_JSON response) { mListener.onResponse(response.message.result.translatedText); } } @Override public void translateToEnglish(String text, String langType, Response.Listener<String> listener, Response.ErrorListener errorListener) { PapagoTranslateRequest request = new PapagoTranslateRequest(text, langType, listener, errorListener); AppEnv.instance().addToNetworkQueue(request); } } <file_sep>package com.coldradio.benzene.library.pubchem; public class urn_JSON { String label; String name; } <file_sep>package com.coldradio.benzene.compound.funcgroup; import android.graphics.PointF; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.Compound; import com.coldradio.benzene.compound.CompoundInspector; import com.coldradio.benzene.compound.CompoundReactor; import java.util.List; public class Ethyl_FG extends Methyl_FG { public Ethyl_FG(Atom a_atom) { super(a_atom); Atom c1 = super.appendAtom(); // C--C(a_atom)--C // // c1 (this is NOT connected to a_atom!!). // Hence a chain compound contains methyl_atom, a_atom, b_atom will be created /// the purpose is to set the position of the second appended methyl Compound tmpCompound = CompoundReactor.chainCompound(new PointF[]{ c1.getPoint(), // aid 0 a_atom.getPoint(), // aid 1 (a_atom.getSkeletonAtom() != null) ? a_atom.getSkeletonAtom().getPoint() : null}); // aid 2 Methyl_FG methyl = new Methyl_FG(tmpCompound.getAtom(0)); CompoundReactor.addFunctionalGroupToAtom(super.getCompound(), c1, methyl, true); Atom c2 = methyl.appendAtom(); // adjust the hydrogen position of C1 again. this is related to https://github.com/ktnslt/benzene/issues/45 tmpCompound = CompoundReactor.chainCompound(new PointF[]{a_atom.getPoint(), c1.getPoint(), c2.getPoint()}); CompoundReactor.saturateWithHydrogen(tmpCompound, tmpCompound.getAtom(1), 4); // now copy the position of H to Ethyl List<Atom> tmpH = CompoundInspector.allHydrogens(tmpCompound.getAtom(1)); List<Atom> c1H = CompoundInspector.allHydrogens(c1); c1H.get(0).setPoint(tmpH.get(0).getPoint()); c1H.get(1).setPoint(tmpH.get(1).getPoint()); } @Override public String getName() { return "ethyl"; } } <file_sep>package com.coldradio.benzene.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.PointF; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import com.coldradio.benzene.R; import com.coldradio.benzene.compound.Edge; import com.coldradio.benzene.project.Project; import com.coldradio.benzene.project.ProjectFileManager; import com.coldradio.benzene.util.AppEnv; import com.coldradio.benzene.util.Notifier; import com.coldradio.benzene.view.drawer.DrawingLib; import com.coldradio.benzene.view.drawer.PaintSet; public class AddToBondActivity extends AppCompatActivity { private AddToBondPreview mPreview; private EditText mEdgeNumber; private boolean mDeleteHydrogenBeforeAdd = true; private boolean mSaturateWithHydrogen = true; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_to_bond_main); Edge edge = Project.instance().getElementSelector().getSelectedEdge(); if (edge == null) { finish(); Notifier.instance().notification("No Selected Edge"); return; } // setting for Preview ViewGroup previewLayout = findViewById(R.id.a2b_view); if (previewLayout != null) { mPreview = new AddToBondPreview(this, edge); previewLayout.addView(mPreview); } // setting for checkbox ((CheckBox)findViewById(R.id.a2b_cb_opposite_site)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mPreview.toggleOppositeSite(); mPreview.invalidate(); } }); ((CheckBox)findViewById(R.id.a2b_cb_delete_h_before_add)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mDeleteHydrogenBeforeAdd = isChecked; } }); ((CheckBox)findViewById(R.id.a2b_cb_saturate_h)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mSaturateWithHydrogen = isChecked; } }); // setting for EditText; Edge Number mEdgeNumber = findViewById(R.id.a2b_et_edge_number); findViewById(R.id.a2b_btn_edge_down).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { offsetEdgeNumber(-1); } }); findViewById(R.id.a2b_btn_edge_up).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { offsetEdgeNumber(1); } }); findViewById(R.id.a2b_btn_tri).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setEdgeNumber(3); } }); findViewById(R.id.a2b_btn_tetra).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setEdgeNumber(4); } }); findViewById(R.id.a2b_btn_pent).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setEdgeNumber(5); } }); findViewById(R.id.a2b_btn_hex).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setEdgeNumber(6); } }); // setting for OK Cancel Button findViewById(R.id.a2b_btn_ok).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int edgeNumber = Integer.parseInt(mEdgeNumber.getText().toString()); if (edgeNumber >= 3) { ProjectFileManager.instance().pushCompoundChangedHistory(Project.instance().getElementSelector().getSelectedCompound()); Project.instance().addCyclicToSelectedBond(edgeNumber, mPreview.getAddSite(), mDeleteHydrogenBeforeAdd, mSaturateWithHydrogen); } finish(); } }); findViewById(R.id.a2b_btn_cancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } @Override protected void onResume() { super.onResume(); AppEnv.instance().setCurrentActivity(this); } @Override protected void onPause() { super.onPause(); AppEnv.instance().setCurrentActivity(null); } private void setEdgeNumber(int edge) { if (mEdgeNumber != null) { mEdgeNumber.setText(String.valueOf(edge)); } } private void offsetEdgeNumber(int offset) { if (mEdgeNumber != null) { int newVal = Integer.parseInt(mEdgeNumber.getText().toString()) + offset; if (newVal >= 3) mEdgeNumber.setText(String.valueOf(newVal)); } } } class AddToBondPreview extends Preview { private boolean mOppositeSite = true; private Edge mSelectedEdge; private PointF mAddSite; public AddToBondPreview(Context context, Edge edge) { super(context); PointF center = edge.center(); setCenter(center); mSelectedEdge = edge; mAddSite = DrawingLib.centerForDoubleBond(mSelectedEdge.first, mSelectedEdge.second, mOppositeSite); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawCircle(mAddSite.x, mAddSite.y, 20, PaintSet.instance().paint(PaintSet.PaintType.GUIDE_LINE)); } public void toggleOppositeSite() { mOppositeSite = !mOppositeSite; mAddSite = DrawingLib.centerForDoubleBond(mSelectedEdge.first, mSelectedEdge.second, mOppositeSite); } public PointF getAddSite() { return mAddSite; } }<file_sep>package com.coldradio.benzene.view; import android.app.Activity; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.coldradio.benzene.R; import com.coldradio.benzene.project.Configuration; import com.coldradio.benzene.project.PreviewHandler; import com.coldradio.benzene.project.Project; import com.coldradio.benzene.project.ProjectFile; import com.coldradio.benzene.project.ProjectFileManager; import com.coldradio.benzene.util.EditTextDialog; import com.coldradio.benzene.util.AppEnv; import com.coldradio.benzene.util.FileUtil; import com.coldradio.benzene.util.Notifier; import com.coldradio.benzene.util.TextUtil; public class ProjectViewAdapter extends RecyclerView.Adapter<ProjectViewAdapter.ProjectViewHolder> { private Activity mMainActivity; static class ProjectViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private TextView mProjectName; private TextView mLastModifiedTime; private ImageView mImageView; final private ProjectViewAdapter mAdapter; private ProjectViewHolder(View v, ProjectViewAdapter adapter) { super(v); mProjectName = v.findViewById(R.id.project_view_name); mLastModifiedTime = v.findViewById(R.id.project_view_last_modified); mImageView = v.findViewById(R.id.project_view_preview); mAdapter = adapter; v.setOnClickListener(this); // More Menu Button final ImageButton btn = v.findViewById(R.id.project_view_button); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PopupMenu popup = new PopupMenu(mAdapter.mMainActivity, v); popup.getMenuInflater().inflate(R.menu.project_view_popup_menu, popup.getMenu()); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { int id = menuItem.getItemId(); final String projectNameString = mProjectName.getText().toString(); if (id == R.id.action_project_rename) { final EditTextDialog dialog = new EditTextDialog(mAdapter.mMainActivity); dialog.setOkListener(new View.OnClickListener() { @Override public void onClick(View v) { String newProjName = dialog.getInputText().trim(); if (FileUtil.exists(newProjName)) { Notifier.instance().notification("Already exists"); } else if (newProjName.isEmpty()) { Notifier.instance().notification("Empty File Name"); } else if (FileUtil.validFileName(newProjName)) { if (ProjectFileManager.instance().rename(projectNameString, newProjName)) { mAdapter.notifyItemChanged(getAdapterPosition()); } else { Notifier.instance().notification("Rename File Failed"); } dialog.dismiss(); } else { Notifier.instance().notification("Invalid Chars " + FileUtil.INVALID_CHARS); } } }).setInitialText(projectNameString).setTitle("New Project Name"); dialog.show(); } else if (id == R.id.action_project_share_image) { if (!FileUtil.share(AppEnv.instance().projectFileDir() + projectNameString + Configuration.IMAGE_FILE_EXT, mAdapter.mMainActivity)) { Notifier.instance().notification("Share Failed"); } } else if (id == R.id.action_project_share_project_file) { if (!FileUtil.share(AppEnv.instance().projectFileDir() + projectNameString + Configuration.PROJECT_FILE_EXT, mAdapter.mMainActivity)) { Notifier.instance().notification("Share Failed"); } } else if (id == R.id.action_project_copy) { int insertedIndex = ProjectFileManager.instance().copy(projectNameString); if (insertedIndex >= 0) { mAdapter.notifyItemInserted(insertedIndex); } } else if (id == R.id.action_project_delete) { ProjectFileManager.instance().delete(projectNameString); mAdapter.notifyItemRemoved(getAdapterPosition()); } else { return false; } return true; } }); popup.show(); } }); } @Override public void onClick(View v) { ProjectFileManager.instance().loadToProject(mProjectName.getText().toString(), Project.instance()); mAdapter.mMainActivity.startActivityForResult(new Intent("com.coldradio.benzene.CANVAS"), ActivityRequestCode.START_CANVAS_REQ.ordinal()); } } public ProjectViewAdapter(Activity activity) { mMainActivity = activity; } @NonNull @Override public ProjectViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.project_view_holder_main, parent, false); return new ProjectViewHolder(v, this); } @Override public void onBindViewHolder(@NonNull ProjectViewHolder holder, int position) { ProjectFile projectFile = ProjectFileManager.instance().getProjectFile(position); if (ProjectFileManager.instance().hasFilter()) { holder.mProjectName.setText(Html.fromHtml(TextUtil.styleKeyword(projectFile.getName(), ProjectFileManager.instance().getFilter().getKeyword()))); } else { holder.mProjectName.setText(projectFile.getName()); } holder.mLastModifiedTime.setText(FileUtil.toDateTimeString(projectFile.lastModified())); holder.mImageView.setImageBitmap(projectFile.getPreview()); } @Override public int getItemCount() { return ProjectFileManager.instance().numberOfProjects(); } } <file_sep>package com.coldradio.benzene.compound.funcgroup; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.AtomicNumber; import com.coldradio.benzene.compound.Bond; import com.coldradio.benzene.compound.CompoundInspector; import com.coldradio.benzene.compound.CompoundReactor; import com.coldradio.benzene.util.Geometry; public class NCO_FG extends Propyl_FG { public NCO_FG(Atom a_atom) { super(a_atom); CompoundReactor.deleteAllHydrogen(super.getCompound()); Atom[] c = CompoundInspector.extractSkeletonChain(super.appendAtom(), 3); c[2].setPoint(Geometry.symmetricToPoint(c[0].getPoint(), c[1].getPoint())); c[0].setAtomicNumber(AtomicNumber.N); c[2].setAtomicNumber(AtomicNumber.O); c[0].setBond(c[1], Bond.BondType.DOUBLE_MIDDLE); c[1].setBond(c[2], Bond.BondType.DOUBLE_MIDDLE); c[1].getAtomDecoration().setShowElementName(true); } @Override public String getName() { return "NCO"; } } <file_sep>package com.coldradio.benzene.compound; public class Bond { public enum BondType { NONE, SINGLE, DOUBLE, DOUBLE_OTHER_SIDE, DOUBLE_MIDDLE, TRIPLE } public enum BondAnnotation { NONE, WEDGE_UP, WEDGE_DOWN, WAVY } private transient Atom mAtom; private int mAIDForAtom; // this is hack for resolving the circular reference caused by the mAtom during serialization. private BondType mBondType; private BondAnnotation mBondAnnotation = BondAnnotation.NONE; public Bond(Atom bondTo, BondType bondType) { mAtom = bondTo; mBondType = bondType; } public BondType getBondType() { return mBondType; } public boolean isDoubleBond() { return mBondType == BondType.DOUBLE || mBondType == BondType.DOUBLE_OTHER_SIDE || mBondType == BondType.DOUBLE_MIDDLE; } public boolean hasBondTo(Atom atom) { return mAtom == atom; } public void setBondType(BondType bondType) { mBondType = bondType; } public Atom getBoundAtom() { return mAtom; } public void cycleBond() { mBondType = BondType.values()[(mBondType.ordinal() + 1) % BondType.values().length]; if (mBondType == BondType.NONE) mBondType = BondType.SINGLE; } public void preSerialization() { mAIDForAtom = mAtom.getAID(); } public void postDeserialization(Compound compound) { mAtom = compound.getAtom(mAIDForAtom); } public BondAnnotation getBondAnnotation() { return mBondAnnotation; } public void setBondAnnotation(BondAnnotation bondAnnotation) { mBondAnnotation = bondAnnotation; } } <file_sep>package com.coldradio.benzene.library.pubchem; import com.coldradio.benzene.compound.AtomicNumber; import com.coldradio.benzene.compound.Bond; import java.util.List; public class PC_Compound_JSON { public class ID_JSON { public SID_JSON id; } public class atoms_JSON { public class charge_JSON { int aid; int value; } public int[] aid; public int[] element; public List<charge_JSON> charge; } public class bonds_JSON { public int[] aid1; public int[] aid2; public int[] order; } public class coords_JSON { public class conformer_JSON { public float[] x; public float[] y; public style_JSON style; } public int[] aid; public List<conformer_JSON> conformers; } public class props_JSON { public urn_JSON urn; public value_JSON value; } public ID_JSON id; public atoms_JSON atoms; public bonds_JSON bonds; public List<coords_JSON> coords; public List<props_JSON> props; public int cid() { return id.id.cid; } public AtomicNumber getAtomicNumber(int aid) { return AtomicNumber.values()[atoms.element[aid - 1]]; } public int bondLength() { if (bonds != null && bonds.aid1 != null) { return bonds.aid1.length; } else { return 0; } } public Bond.BondType bondType(int bondIndex) { if (bonds.order[bondIndex] == 2) { return Bond.BondType.DOUBLE; } else if (bonds.order[bondIndex] == 3) { return Bond.BondType.TRIPLE; } else { return Bond.BondType.SINGLE; } } public style_JSON getStyle() { return coords.get(0).conformers.get(0).style; } }<file_sep>package com.coldradio.benzene.view; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.text.Spanned; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.android.volley.Response; import com.coldradio.benzene.R; import com.coldradio.benzene.compound.Compound; import com.coldradio.benzene.library.CompoundIndex; import com.coldradio.benzene.library.CompoundLibrary; import com.coldradio.benzene.project.Project; import com.coldradio.benzene.project.ProjectFileManager; import com.coldradio.benzene.project.history.CompoundAddedHistory; import com.coldradio.benzene.util.AppEnv; import com.coldradio.benzene.util.ImageTextViewDialog; import com.coldradio.benzene.util.Notifier; import com.coldradio.benzene.util.TextUtil; import java.util.List; public class CompoundSearchAdapter extends RecyclerView.Adapter<CompoundSearchAdapter.CompoundViewHolder> { static class CompoundViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private TextView mTitle; private TextView mCID; private TextView mMF; private TextView mMW; private TextView mIUPACName; private ImageView mPreview; private CompoundViewHolder(View v) { super(v); mTitle = v.findViewById(R.id.tv_title); mCID = v.findViewById(R.id.tv_cid); mMF = v.findViewById(R.id.tv_mf); mMW = v.findViewById(R.id.tv_mw); mIUPACName = v.findViewById(R.id.tv_iupac); mPreview = v.findViewById(R.id.iv_preview); v.setOnClickListener(this); v.findViewById(R.id.btn_compound_desc).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CompoundIndex index = CompoundLibrary.instance().getCompoundIndex(getAdapterPosition()); if (index != null) { final ImageTextViewDialog dialog = new ImageTextViewDialog().setTitle(index.title).setImage(index.getBitmap()).setContent(Html.fromHtml("Waiting...")).show(); CompoundLibrary.instance().requestDescription(getAdapterPosition(), new Response.Listener<Spanned>() { @Override public void onResponse(Spanned response) { dialog.setContent(response); } }); } } }); } @Override public void onClick(View v) { CompoundLibrary.instance().requestCompound(getAdapterPosition(), new Response.Listener<List<Compound>>() { @Override public void onResponse(List<Compound> compound) { if (compound != null) { for (Compound c : compound) { Project.instance().addCompound(c, true); ProjectFileManager.instance().push(new CompoundAddedHistory(c)); // when the user fast-clicks the backbutton after clicking searched compound, compound might be added later when the CanvasView is already shown // In this case, the Canvas shall be invalidated (if not it is now drawn). AppEnv.instance().invalidateCanvasView(); AppEnv.instance().updateContextMenu(); } Notifier.instance().notification(mTitle.getText().toString() + " is added. " + (compound.size() > 1 ? "Total " + compound.size() + " Compounds" : "")); } } }); } } @Override @NonNull public CompoundViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.compound_holder_main, parent, false); return new CompoundViewHolder(v); } @Override public void onBindViewHolder(@NonNull CompoundViewHolder holder, int position) { CompoundIndex index = CompoundLibrary.instance().getCompoundIndex(position); holder.mTitle.setText(index.title); holder.mCID.setText(String.valueOf(index.cid)); holder.mMF.setText(Html.fromHtml(TextUtil.subscriptNumber(index.mf))); holder.mMW.setText(String.valueOf(index.mw)); holder.mIUPACName.setText(index.IUPAC); holder.mPreview.setImageBitmap(index.getBitmap()); // when getBitmap() returns null, this will reset the Preview } @Override public int getItemCount() { return CompoundLibrary.instance().size(); } } <file_sep>package com.coldradio.benzene.project.history; import com.coldradio.benzene.compound.Compound; import com.coldradio.benzene.project.Project; public class CompoundDeletedHistory extends History { public final Compound mDeletedCompound; public CompoundDeletedHistory(Compound compound) { super(compound.getID()); mDeletedCompound = compound; } @Override public void undo() { Project.instance().addCompound(mDeletedCompound, false); } @Override public void redo() { Project.instance().removeCompound(Project.instance().findCompound(mCID)); } } <file_sep>package com.coldradio.benzene.compound.funcgroup; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.AtomicNumber; import com.coldradio.benzene.compound.CompoundReactor; import com.coldradio.benzene.project.Configuration; import com.coldradio.benzene.util.Geometry; public class OH_FG extends Ethyl_FG { public OH_FG(Atom a_atom) { super(a_atom); CompoundReactor.deleteAllHydrogen(super.getCompound()); Atom c1 = super.appendAtom(); Atom c2 = c1.getSkeletonAtom(); c2.setAtomicNumber(AtomicNumber.H); c2.setPoint(Geometry.pointInLine(c1.getPoint(), c2.getPoint(), Configuration.H_BOND_LENGTH_RATIO)); c1.setAtomicNumber(AtomicNumber.O); c1.getAtomDecoration().lettering(true); } @Override public String getName() { return "OH"; } } <file_sep>package com.coldradio.benzene.compound.funcgroup; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.AtomicNumber; import com.coldradio.benzene.compound.Bond; import com.coldradio.benzene.compound.CompoundReactor; public class COO_FG extends IsoPropyl_FG { public COO_FG(Atom a_atom) { super(a_atom); CompoundReactor.deleteAllHydrogen(super.getCompound()); Atom c1 = super.appendAtom(); Atom c2 = c1.getSkeletonAtom(); Atom c2_dot = c1.getSkeletonAtomExcept(c2); c2.setAtomicNumber(AtomicNumber.O); c1.doubleBond(c2); c2.setBond(c1, Bond.BondType.DOUBLE_MIDDLE); c2_dot.setAtomicNumber(AtomicNumber.O); c2_dot.getAtomDecoration().setCharge(-1); } @Override public String getName() { return "COO-"; } } <file_sep>package com.coldradio.benzene.project; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PointF; import android.view.MotionEvent; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.Compound; import com.coldradio.benzene.util.Geometry; import java.util.ArrayList; import java.util.List; public class FingerSelector implements IRegionSelector { private List<PointF> mFingerPath = new ArrayList<>(); private List<Atom> mSelectedAtoms = new ArrayList<>(); private boolean mCancelSelector = false; private void updateSelectedAtoms(PointF l1, PointF l2) { for (Compound compound : Project.instance().getCompounds()) { for (Atom atom : compound.getAtoms()) { float distance = (l1.equals(l2) ? Geometry.distanceFromPointToPoint(atom.getPoint(), l1) : Geometry.distanceFromPointToLineSegment(atom.getPoint(), l1, l2)); if (! mSelectedAtoms.contains(atom) && atom.isVisible() && distance < Configuration.SELECT_RANGE) { mSelectedAtoms.add(atom); } } } } private void addToPath(PointF point) { if (mFingerPath.size() > 0) { updateSelectedAtoms(mFingerPath.get(mFingerPath.size() - 1), point); } else { updateSelectedAtoms(point, point); } // added as new. the passed point is reused, and the reference will not be changed at all mFingerPath.add(new PointF(point.x, point.y)); } @Override public void draw(Canvas canvas, Paint paint) { Paint.Style origStyle = paint.getStyle(); float origStrokeWidth = paint.getStrokeWidth(); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(Configuration.SELECT_RANGE * 2); for (int ii = 0; ii < mFingerPath.size() - 1; ++ii) { PointF p1 = mFingerPath.get(ii), p2 = mFingerPath.get(ii + 1); canvas.drawLine(p1.x, p1.y, p2.x, p2.y, paint); } paint.setStyle(origStyle); paint.setStrokeWidth(origStrokeWidth); } @Override public boolean onTouchEvent(PointF point, int touchAction) { if (touchAction == MotionEvent.ACTION_DOWN) { if (mFingerPath.isEmpty()) { addToPath(point); } else { // shall return false. if return true, this ACTION_DOWN event will not go to GestureDetector. // Then, the GestureDetector scroll the screen without DOWN event only with MOVE event mCancelSelector = true; // this will delete this object, hence no need to reset it to false return false; } } else if (touchAction == MotionEvent.ACTION_MOVE) { if (Geometry.distanceFromPointToPoint(point, mFingerPath.get(mFingerPath.size() - 1)) > 20) { addToPath(point); } } else if (touchAction == MotionEvent.ACTION_UP) { // empty body. if this case returns false, UP will be handled by others, and ElementSelector will be reset } else { return false; } return true; } @Override public List<Atom> getSelectedAtoms() { return mSelectedAtoms; } @Override public boolean canceled() { return mCancelSelector; } } <file_sep># Benzene Tree Tutorial * [Go Back to Help Root](README.md) * [Full Menu Description](FullMenuDescription.md) , *Refer to this page if you not familiar with menus* ## Contents * [Basic operations](#basic-operations---go-to-top) * [From cyclohexane to aspirin](#from-cyclohexane-to-aspirin---go-to-top) * [Other way for aspirin](#Other-way-for-aspirin---go-to-top) * [From benzene to quinoline](#From-benzene-to-quinoline---go-to-top) * [Saturate with hydrogens](#Saturate-with-hydrogen---go-to-top) ## Basic Operations - [Go to Top](#Benzene-tree-tutorial) <img src="https://github.com/ktnslt/benzene/blob/images/images/menu/basic_operations.png" height="300"> * Double Tap to center the view * To scroll, use one finger * To move the selected, use two fingers ## From cyclohexane to aspirin - [Go to Top](#Benzene-tree-tutorial) * Click the Red PLUS button for creating a new project <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin0.png" height="300"> * Click the + button in the bottom toolbar to add compound. Type **cyclohexane** and enter. Click the cyclohexane to add. ``` Surely, you can search and add aspirin directly. Try it! This is just a tutorial. ``` <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin1.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin2.png" height="300"> * You will see the added cyclohexane. You may rotate by using the yellow circle. <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin4.png" height="300"> * Now, turning the cyclohexane into benzene. For this, click the ChangeBondType icon (the first icon) in the bottom toolbar. <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin5.png" height="300"> * Now, turning the cyclohexane into benzene. For this, click the ChangeBondType icon (the first icon) in the bottom toolbar. Similarly, apply the same for two more bonds. Now you have benzene! * Click the top atom in benzene. In this way, functional group can be added <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin6.png" height="300"> * click the fx icon in the bottom toolbar. Select **COOH**, and click OK. <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin7.png" height="300"> * With the Benzoic Acid, select the atom in the right beside. we will add **OH** functional group to it. <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin8.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin8-1.png" height="300"> * This is not definitely aspirin. Click the O atom in OH. Then click fx icon. In the window, select **COCH3** functional group. <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin9.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin10.png" height="300"> * Finally you have aspirin. <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin11.png" height="300"> * You might want to flip the bond. For this, select the bond and click the FlipBond icon. You will see the guideline for bond, and click the right icon. <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin12.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin13.png" height="300"> * You have the aspirin <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin14.png" height="300"> ## Other way for aspirin - [Go to Top](#Benzene-tree-tutorial) * Sometimes, you may want to letter the COOH functional group. Something like below. <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin27.png" height="300"> * First, double click any atom or bond of the aspirin. You can select the compound. Select the **Copy** menu in the upper toolbar, and **Paste** it. <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin17.png" height="300"> * move the second aspirin with your **two finger**. With two finger, you can move the selected compound. <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin19.png" height="300"> * select the **FingerSelect** icon in the bottom toolbar. Select the COOH part, and **Delete** it. <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin19-1.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin20.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin21.png" height="300"> * Select the atom where the COOH was attached, the add **methyl** to it <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin22.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin23.png" height="300"> * Select the atom below, and click the **Edit** menu in the bottom toolbar. <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin24.png" height="300"> * Check the checkbox **Change to Ele**, and click **ELE** button. you will see below periodic table. There, type **CO2H** or **COOH** whatever you want. <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin25.png" height="300"> * Click OK to the below aspirin <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin26.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/aspirin/aspirin27.png" height="300"> ## From benzene to quinoline - [Go to Top](#Benzene-tree-tutorial) * Search and add benzene. <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline1.png" height="300"> * Select the side bond and click the **FlipBond** icon. <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline2.png" height="300"> * The blue dot means the direction where the ring will be added. You can change it by **Add To Opposite** checkbox. Click OK. <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline3.png" height="300"> * Select the atom where the Nitrogen will be placed. Click **Edit** icon. In the window, check the checkbox **Change to ELE**. <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline4.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline5.png" height="300"> * Select **N** and click OK. <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline6.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline7.png" height="300"> * Select the bond, and change the bond type to Double <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline8.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline9.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline10.png" height="300"> * It seems that you have quinoline. But, there is one hidden problem. Click the **Show Hydrogen** icon. <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline11.png" height="300"> * It will show your Nitrogen has two hydrogens. Click the **Saturate with hydrogen** icon. Click OK. You will have the correct quinoline now. <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline12.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline13.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline14.png" height="300"> * If you want to show the **unshared electron** of the Nitrogen, click **Edit** icon. There, click the unshared electron position that you want to show. <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline15.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline16.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline17.png" height="300"> * Finally, you can hide the hydrogen again by **Show Hydrogen** icon <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline18.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/quinoline/quinoline19.png" height="300"> ## Saturate with Hydrogen - [Go to Top](#Benzene-tree-tutorial) This section explains the **Saturate with Hydrogen** menu. In chemistry, saturation has diverse meaning, but here it specifies the maximum number of hydrogen, that can be bound to a atom. For example, carbon can be saturated with 4 hydrogens in normal condition. Hydrogens are not shown by default, and this is what you have learned in the basic chemistry courses in school. Please look at the below images. Compounds only show the skeletons, but it has hidden hydrogens. To see hidden hydrogens, you can click **Show hydrogen** menu <img src="https://github.com/ktnslt/benzene/blob/images/images/saturate/saturate1.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/saturate/saturate1-1.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/saturate/saturate2.png" height="300"> **Saturate with hydrogen** menu comes up when a compound or an atom is selected. With a compound selected, the saturation will be applied for the whole compound. With an atom selected, it only applied to the atom. If you click the **Saturate with hydrogen** menu, you will see the below screen. The first three rows is for commonly used atoms; Carbon, Nitrogen and Oxygen. They are set with the basic saturation number. The **Faimly** checkbox means whether it shall be applied for the entire the family. For example, checking **Family** of carbon will apply for C, Si, Ge, Sn, Pb, Fl. With last one, you can saturate for any atoms like saturating B up to 3 hydrogens. <img src="https://github.com/ktnslt/benzene/blob/images/images/saturate/saturate3.png" height="300"> Here, the carbon saturation will be demonstrated. First, change the maximum bonds of carbon to **2** like below. Then, you will have only one hydrogen in the bottom tail of the toluene. If you change the saturation number of carbon back to **4**, you will have the normal toluene again. <img src="https://github.com/ktnslt/benzene/blob/images/images/saturate/saturate4.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/saturate/saturate5.png" height="300"> <img src="https://github.com/ktnslt/benzene/blob/images/images/saturate/saturate6.png" height="300"> <file_sep>package com.coldradio.benzene.project.preference; import android.content.SharedPreferences; import java.util.ArrayList; import java.util.List; public class PreferenceManager { private List<OnPreferenceEvent> mListenerList = new ArrayList<>(); public void add(OnPreferenceEvent listener) { if (!mListenerList.contains(listener)) { mListenerList.add(listener); } } public void restore(SharedPreferences sharedPreferences) { if (sharedPreferences != null) { for (OnPreferenceEvent listener : mListenerList) { listener.onRestore(sharedPreferences); } } } public void save(SharedPreferences.Editor editor) { if (editor != null) { for (OnPreferenceEvent listener : mListenerList) { listener.onSave(editor); } } } } <file_sep>package com.coldradio.benzene.view.drawer; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PointF; import android.graphics.Rect; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.AtomDecoration; import com.coldradio.benzene.compound.AtomicNumber; import com.coldradio.benzene.compound.Compound; import com.coldradio.benzene.compound.CompoundInspector; import com.coldradio.benzene.project.Configuration; import com.coldradio.benzene.util.Geometry; import com.coldradio.benzene.util.TreeTraveler; public class AtomDecorationDrawer implements ICompoundDrawer { private static String atomToString(Atom atom) { String text = atom.getAtomicNumber().toString(); if (atom.getAtomicNumber() == AtomicNumber.TEXT) { text = atom.getArbitraryName(); } else if (atom.getAtomDecoration().isLettering()) { int hNumber = CompoundInspector.numberOfHydrogen(atom); boolean hydrogenInRight = CompoundInspector.moreHydrogensInRight(atom); if (hNumber == 1) { text = hydrogenInRight ? text + "H" : "H" + text; } else if (hNumber > 1) { text = hydrogenInRight ? text + "H" + String.valueOf(hNumber) : "H" + String.valueOf(hNumber) + text; } } return text; } private static void drawMarker(Atom atom, Canvas canvas, Paint paint) { PointF atomXY = atom.getPoint(); PointF xy = new PointF(atomXY.x, atomXY.y); xy.offset(0, -35); xy = Geometry.cwRotate(xy, atomXY, (float) Math.toRadians(45 * (atom.getAtomDecoration().getMarker().ordinal() - 1))); xy.offset(0, 15); DrawingLib.drawText(Character.toString(Configuration.ATOM_MARKER), xy, false, 0, canvas, paint); } private static void drawUnsharedElectron(Atom atom, Canvas canvas, Paint paint) { int fontHeight = PaintSet.instance().fontHeight(PaintSet.PaintType.GENERAL); int fontWidth = PaintSet.instance().fontWidth(PaintSet.PaintType.GENERAL); PointF xy = atom.getPoint(); AtomDecoration atomDecoration = atom.getAtomDecoration(); final float padding = 8; for (AtomDecoration.Direction direction : AtomDecoration.Direction.values()) { if (atomDecoration.getUnsharedElectron(direction) != AtomDecoration.UnsharedElectron.NONE) { float eleX = xy.x, eleY = xy.y; // calculate the position if (direction == AtomDecoration.Direction.TOP) { eleY = xy.y - fontHeight / 2 - padding; } else if (direction == AtomDecoration.Direction.BOTTOM) { // in case of RIGHT, BOTTOM, more padding is added eleY = xy.y + fontHeight / 2 + padding + 3; } else if (direction == AtomDecoration.Direction.LEFT) { eleX = xy.x - fontWidth / 2 - padding; } else { eleX = xy.x + fontWidth / 2 + padding + 3; } // draw electron if (atomDecoration.getUnsharedElectron(direction) == AtomDecoration.UnsharedElectron.SINGLE) { canvas.drawCircle(eleX, eleY, Configuration.ELECTRON_RADIUS, paint); } else { if (direction == AtomDecoration.Direction.TOP || direction == AtomDecoration.Direction.BOTTOM) { canvas.drawCircle(eleX - fontWidth / 4, eleY, Configuration.ELECTRON_RADIUS, paint); canvas.drawCircle(eleX + fontWidth / 4, eleY, Configuration.ELECTRON_RADIUS, paint); } else { canvas.drawCircle(eleX, eleY - fontHeight / 4, Configuration.ELECTRON_RADIUS, paint); canvas.drawCircle(eleX, eleY + fontHeight / 4, Configuration.ELECTRON_RADIUS, paint); } } } } } private static void drawChargeAsCircle(Atom atom, Canvas canvas, Paint paint) { PointF atomXY = atom.getPoint(); PointF xy = new PointF(atomXY.x, atomXY.y); Paint.Style origPaintStyle = paint.getStyle(); paint.setStyle(Paint.Style.STROKE); // TODO: assume this is GENERAL type, could be a bug, but what else.., one possible solution is to pass the PaintType not the paint object xy.offset(0, -PaintSet.instance().fontHeight(PaintSet.PaintType.GENERAL)); xy = Geometry.cwRotate(xy, atomXY, (float) Math.toRadians(45 * (atom.getAtomDecoration().getChargeAsCircle().ordinal() - 1))); // draw circle canvas.drawCircle(xy.x, xy.y, Configuration.CHARGE_CIRCLE_RADIUS, paint); // draw negative float positiveRadius = Configuration.CHARGE_CIRCLE_RADIUS / 2; canvas.drawLine(xy.x - positiveRadius, xy.y, xy.x + positiveRadius, xy.y, paint); if (atom.getAtomDecoration().getCharge() == 1) { canvas.drawLine(xy.x, xy.y - positiveRadius, xy.x, xy.y + positiveRadius, paint); } paint.setStyle(origPaintStyle); } private static Rect rect = new Rect(); private static void drawChargeAsNumber(Atom atom, Canvas canvas, Paint paint) { int charge = atom.getAtomDecoration().getCharge(); PointF xy = atom.getPoint(); String atomName = atom.getAtomicNumber().toString(); if (charge == 1 || charge == -1) { String sign = (charge == 1 ? "+" : "-"); if (CompoundInspector.uniqueSkeletonOnRightSide(atom)) { DrawingLib.drawTextSuperscript(sign, 0, 1, DrawingLib.atomEnclosingRect(atomName, xy, rect), false, false, 0, canvas, paint); } else { DrawingLib.drawTextSuperscript(sign, 0, 1, DrawingLib.atomEnclosingRect(atomName, xy, rect), true, false, 0, canvas, paint); } } else if (charge > 1) { DrawingLib.drawTextSuperscript(String.valueOf(charge) + "+", DrawingLib.atomEnclosingRect(atomName, xy, rect), false, 0, canvas, paint); } else if (charge < -1) { DrawingLib.drawTextSuperscript(String.valueOf(-charge) + "-", DrawingLib.atomEnclosingRect(atomName, xy, rect), false, 0, canvas, paint); } } private static void drawCharge(Atom atom, Canvas canvas, Paint paint) { AtomDecoration atomDecoration = atom.getAtomDecoration(); int charge = atomDecoration.getCharge(); if (charge * charge == 1 && atomDecoration.getChargeAsCircle() != AtomDecoration.Marker.NONE) { drawChargeAsCircle(atom, canvas, paint); } else { drawChargeAsNumber(atom, canvas, paint); } } @Override public boolean draw(Compound compound, Canvas canvas, Paint paint) { TreeTraveler.returnFirstAtom(new TreeTraveler.AtomVisitorAlwaysTravelDown() { @Override public boolean visit(Atom atom, int distanceFromRoot, Object... args) { Canvas canvas = (Canvas) args[0]; Paint paint = (Paint) args[1]; AtomDecoration atomDecoration = atom.getAtomDecoration(); if (atomDecoration.getShowElementName() || atomDecoration.isLettering() || atom.getAtomicNumber() == AtomicNumber.TEXT) { DrawingLib.drawText(atomToString(atom), atom.getPoint(), true, Color.WHITE, canvas, paint); } if (atomDecoration.getMarker() != AtomDecoration.Marker.NONE) { drawMarker(atom, canvas, paint); } if (atomDecoration.getCharge() != 0) { drawCharge(atom, canvas, paint); } drawUnsharedElectron(atom, canvas, paint); return false; } }, compound, canvas, paint); return true; } } <file_sep>package com.coldradio.benzene.util; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Environment; import android.view.View; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; import com.coldradio.benzene.project.preference.OnPreferenceEvent; import com.coldradio.benzene.project.preference.PreferenceManager; import com.coldradio.benzene.view.CanvasView; import com.google.gson.Gson; import java.io.File; public class AppEnv { private static AppEnv msInstance = new AppEnv(); private String mProjectFileRootDir; private String mScreenShotDir; private String mTemporaryDir; private RequestQueue mRequestQueue; private Context mApplicationContext; private Gson mGson = new Gson(); private View mCanvasView; private Activity mCurrentActivity; private PreferenceManager mPreferenceManager = new PreferenceManager(); public static AppEnv instance() { return msInstance; } public void initialize(Context appContext) { // shall called with Application Context, not with the Activity context if (mProjectFileRootDir == null) { mProjectFileRootDir = appContext.getFilesDir().getPath() + File.separator; mScreenShotDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString() + "/BenzeneScreenshots/"; mTemporaryDir = mProjectFileRootDir + "temp/"; mRequestQueue = Volley.newRequestQueue(appContext); mApplicationContext = appContext; } } public void saveState() { SharedPreferences.Editor editor = mApplicationContext.getSharedPreferences("BenzenePreference", Context.MODE_PRIVATE).edit(); mPreferenceManager.save(editor); editor.apply(); } public void setCanvasView(View canvasView) { mCanvasView = canvasView; } public void invalidateCanvasView() { if (mCanvasView != null) { mCanvasView.invalidate(); } } public void updateContextMenu() { CanvasView canvasView = (CanvasView) mCanvasView; if (canvasView != null) { canvasView.updateContextMenu(); } } public Context getApplicationContext() { return mApplicationContext; } public Gson gson() { return mGson; } public String projectFileDir() { return mProjectFileRootDir; } public String screenShotDir() { return mScreenShotDir; } public String temporaryDir() { return mTemporaryDir; } public void addToNetworkQueue(Request request) { mRequestQueue.add(request); } public void cancelAllNetworkRequest() { mRequestQueue.cancelAll(mApplicationContext); } public void setCurrentActivity(Activity activity) { mCurrentActivity = activity; } public Activity getCurrentActivity() { return mCurrentActivity; } public void addPreferenceListener(OnPreferenceEvent listener) { // initialize() might be earlier than addPreferenceListener(). Hence, restore at the time of registration. if (listener != null) { mPreferenceManager.add(listener); listener.onRestore(mApplicationContext.getSharedPreferences("BenzenePreference", Context.MODE_PRIVATE)); } } } <file_sep>package com.coldradio.benzene.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PointF; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import com.coldradio.benzene.R; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.Compound; import com.coldradio.benzene.compound.CompoundReactor; import com.coldradio.benzene.compound.funcgroup.*; import com.coldradio.benzene.project.Project; import com.coldradio.benzene.project.ProjectFileManager; import com.coldradio.benzene.util.AppEnv; import com.coldradio.benzene.util.Notifier; import com.coldradio.benzene.view.drawer.AtomDecorationDrawer; import com.coldradio.benzene.view.drawer.GenericDrawer; import com.coldradio.benzene.view.drawer.PaintSet; public class AddToAtomActivity extends AppCompatActivity { private IFunctionalGroup mFuncGroup; private TextView mFuncGroupName; private AddToAtomPreview mPreview; private boolean mDeleteHOfSelectedAtom = true; private void setFuncGroupNameAndPreview() { // assume the mFuncGroup is already assigned mFuncGroupName.setText(mFuncGroup.getName()); mPreview.setFunctionalGroup(mFuncGroup); } @Override protected void onResume() { super.onResume(); AppEnv.instance().setCurrentActivity(this); } @Override protected void onPause() { super.onPause(); AppEnv.instance().setCurrentActivity(null); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_to_atom_main); final Atom attachAtom = Project.instance().getElementSelector().getSelectedAtom(); mFuncGroupName = findViewById(R.id.a2a_tv_func_group_name); if (attachAtom == null) { finish(); Notifier.instance().notification("No Atom Selected"); return; } // setting for Preview ViewGroup previewLayout = findViewById(R.id.a2a_view); if (previewLayout != null) { mPreview = new AddToAtomPreview(this); mPreview.setCenter(attachAtom.getPoint()); previewLayout.addView(mPreview); } // setting for prev next button findViewById(R.id.a2a_btn_attach_form_prev).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mFuncGroup != null) { mFuncGroup.prevForm(); mPreview.invalidate(); } else { Notifier.instance().notification("Select Functional Group First"); } } }); // setting for checkbox delete H of selected Atom ((CheckBox)findViewById(R.id.a2a_cb_delete_H)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mDeleteHOfSelectedAtom = isChecked; } }); findViewById(R.id.a2a_btn_attach_form_next).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mFuncGroup != null) { mFuncGroup.nextForm(); mPreview.invalidate(); } else { Notifier.instance().notification("Select Functional Group First"); } } }); // setting for ok, cancel button findViewById(R.id.a2a_btn_ok).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Compound c = Project.instance().getElementSelector().getSelectedCompound(); ProjectFileManager.instance().pushCompoundChangedHistory(c); CompoundReactor.addFunctionalGroupToAtom(c, attachAtom, mFuncGroup, mDeleteHOfSelectedAtom); finish(); } }); findViewById(R.id.a2a_btn_cancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); // setting for buttons - alkane, alkene, alkyne findViewById(R.id.a2a_btn_c1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new Methyl_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_c2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new Ethyl_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_c3).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new Propyl_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_iso_c3).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new IsoPropyl_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_c4).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new Butyl_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_iso_c4).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new IsoButyl_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_sec_c4).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new SecButyl_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_tert_c4).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new TertButyl_FG(attachAtom); setFuncGroupNameAndPreview(); } }); // settings buttons - cyclic findViewById(R.id.a2a_btn_cyc_c5).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new CycPentyl_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_conj_c5).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new ConjCycPentyl_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_cyc_c6).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new CycHexyl_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_phe).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new Phenyl_FG(attachAtom); setFuncGroupNameAndPreview(); } }); // settings for buttons - oxygen findViewById(R.id.a2a_btn_oh).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new OH_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_o).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new Ketone_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_cho).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new CHO_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_coo).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new COO_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_cooh).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new COOH_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_coch3).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new COCH3_FG(attachAtom); setFuncGroupNameAndPreview(); } }); // nitrogen findViewById(R.id.a2a_btn_no2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new NO2_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_nco).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new NCO_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_nh2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new NH2_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_nme2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new NMe2_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_nmeh).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new NMeH_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_nnn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new NNN_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_conh2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new CONH2_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_ocn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new OCN_FG(attachAtom); setFuncGroupNameAndPreview(); } }); // sulfur findViewById(R.id.a2a_btn_so2oh).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new SO2OH_FG(attachAtom); setFuncGroupNameAndPreview(); } }); findViewById(R.id.a2a_btn_so2me).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFuncGroup = new SO2Me_FG(attachAtom); setFuncGroupNameAndPreview(); } }); } } class AddToAtomPreview extends Preview { private IFunctionalGroup mFunctionalGroup; private AtomDecorationDrawer mAtomDecorationDrawer = new AtomDecorationDrawer(); public AddToAtomPreview(Context context) { super(context); } public void setFunctionalGroup(IFunctionalGroup funcGroup) { mFunctionalGroup = funcGroup; invalidate(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mFunctionalGroup != null) { Paint paint = PaintSet.instance().paint(PaintSet.PaintType.GENERAL); PointF a_atom_point = getCenter(); PointF c1_point = mFunctionalGroup.appendAtom().getPoint(); int color = paint.getColor(); paint.setColor(Color.BLUE); GenericDrawer.drawBondSingleOrDoubleMiddle(a_atom_point, c1_point, mFunctionalGroup.bondType(), canvas, paint); GenericDrawer.draw(mFunctionalGroup.curForm(), canvas, paint); mAtomDecorationDrawer.draw(mFunctionalGroup.curForm(), canvas, paint); paint.setColor(color); } } }<file_sep>package com.coldradio.benzene.util; import java.util.List; import java.util.Locale; public abstract class SearchFilter<T> { protected String mKeyword; public String getKeyword() { return mKeyword; } public abstract List<T> filtered(List<T> list); }<file_sep>package com.coldradio.benzene.library.pubchem; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.toolbox.HttpHeaderParser; import com.coldradio.benzene.compound.Compound; import com.coldradio.benzene.compound.CompoundArranger; import com.coldradio.benzene.compound.CompoundInspector; import com.coldradio.benzene.library.rule.RuleSet; import com.coldradio.benzene.util.AppEnv; import com.coldradio.benzene.util.ScreenInfo; import com.google.gson.JsonSyntaxException; import java.io.UnsupportedEncodingException; import java.util.List; public class PubChemCompoundRequest extends Request<List<Compound>> { private Response.Listener<List<Compound>> mListener; PubChemCompoundRequest(int cid, final Response.Listener<List<Compound>> listener, Response.ErrorListener errorListener) { super(Method.GET, "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/" + String.valueOf(cid) + "/JSON", errorListener); mListener = listener; } @Override protected void deliverResponse(List<Compound> response) { mListener.onResponse(response); } @Override protected Response<List<Compound>> parseNetworkResponse(NetworkResponse response) { try { String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); PC_Compound_JSON compound_json = AppEnv.instance().gson().fromJson(json, CompoundStructure_JSON.class).PC_Compounds.get(0); Compound rawCompound = PubChemCompoundFactory.create(compound_json); // to do alignCenter(), the compound shall be large enough. This is why zoomToStandard shall be called first rawCompound = CompoundArranger.alignCenter(rawCompound, ScreenInfo.instance().centerPoint()); List<Compound> compounds = CompoundInspector.split(rawCompound); for (Compound compound : compounds) { RuleSet.instance().apply(compound); } return Response.success(compounds, HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JsonSyntaxException e) { return Response.error(new ParseError(e)); } } } <file_sep># Benzene Tree This is an organic chemical compound designer running on Android. There already exists many Applications for the same purposes, and the Benzene Tree is one open option for you. ## Goals * Don't design from scratch. Just reuse tons of compounds found in various sources. * Easy to use. ## Documentations * [Full Menu Description](FullMenuDescription.md) * [Benzene Tree Tutorial](BenzeneTreeTutorial.md) ## Version History * Version 1.0.0 at some day of Feb 2019. ## Used Open Source or Libraries * [GSon](https://github.com/google/gson#download) <file_sep>package com.coldradio.benzene.util; import android.Manifest; import android.app.Activity; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; public class PermissionManager { public enum PermissionCode { WRITE_EXTERNAL_STORAGE } private static PermissionManager msInstance = new PermissionManager(); private final String[] PERMISSION_MAP = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}; private boolean[] mPermissionResults = new boolean[]{false}; public static PermissionManager instance() { return msInstance; } public void checkAndRequestPermission(Activity activity, PermissionCode permissionCode) { String permission = PERMISSION_MAP[permissionCode.ordinal()]; if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(activity, new String[]{permission}, permissionCode.ordinal()); } else { mPermissionResults[permissionCode.ordinal()] = true; } } public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (grantResults.length == 0) { return; } if (requestCode == PermissionCode.WRITE_EXTERNAL_STORAGE.ordinal()) { mPermissionResults[requestCode] = (grantResults[requestCode] == PackageManager.PERMISSION_GRANTED); } } public boolean hasPermission(PermissionCode permissionCode) { return mPermissionResults[permissionCode.ordinal()]; } } <file_sep>package com.coldradio.benzene.library.pubchem; import java.util.List; class CompoundProperty_JSON { class PropertyTable_JSON { List<Property_JSON> Properties; } class Property_JSON { int CID; String MolecularFormula; float MolecularWeight; String IUPACName; String Name; // custom property not from JSON } PropertyTable_JSON PropertyTable; } <file_sep>package com.coldradio.benzene.compound.funcgroup; import android.graphics.PointF; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.Compound; import com.coldradio.benzene.compound.CompoundReactor; public class SecButyl_FG extends IsoPropyl_FG { public SecButyl_FG(Atom a_atom) { super(a_atom); Atom c1 = super.appendAtom(); Atom c2 = c1.getSkeletonAtom(); Atom c2_dot = c1.getSkeletonAtomExcept(c2); Compound tmpCompound = CompoundReactor.chainCompound(new PointF[]{c2.getPoint(), c1.getPoint(), c2_dot.getPoint()}); Methyl_FG methyl = new Methyl_FG(tmpCompound.getAtom(2)); // append to the last C CompoundReactor.addFunctionalGroupToAtom(super.getCompound(), c2_dot, methyl, true); } @Override public String getName() { return "s-butyl"; } } <file_sep># Full Menu Description for Benzene Tree * [Go Back to Help Root](README.md) * [Benzen Tree Tutorial](BenzeneTreeTutorial.md) ## Basic Menu This menu shows up when nothing selected. <img src="https://github.com/ktnslt/benzene/blob/images/images/menu/basic.png" height="300"> * Select By Rect: Rectanble based selection * Select By Finger: you can select with your finger in more flexible way * Search Compound: search whatever compound you want ## Compound Menu This menu comes up when you select any compound. <img src="https://github.com/ktnslt/benzene/blob/images/images/menu/compound_menu.png" height="300"> * Saturate with hydrogen: you can add or delete hydrogens to atom based on Atom Number. * show hydrogens: show the hydrogens of the compound. basically hydrogens are hidden. ## Atom Menu This menu shows up when an atom selected. <img src="https://github.com/ktnslt/benzene/blob/images/images/menu/atom_menu.png" height="300"> * Edit: edit the atom such as charge, mark, etc. You can also change the atom type (e.g., change the Carbon to Oxygen) * Saturate with hydrogens * Flip hydrogens: OH or HO * synthesis: make a bond between atoms * Functional Group: add functional groups ## Bond Menu This menu shows up when a bond selected <img src="https://github.com/ktnslt/benzene/blob/images/images/menu/bond_menu.png" height="300"> * Bond Type: single, double, triple bond type * Wedge Up: wedge up * Wedge Down: wedge down * Flip Bond: flip parts of compounds against the bond * Add to Bond: add cyclo compounds to bond <file_sep>package com.coldradio.benzene.compound.funcgroup; import com.coldradio.benzene.compound.Atom; import com.coldradio.benzene.compound.AtomicNumber; import com.coldradio.benzene.compound.CompoundReactor; import com.coldradio.benzene.project.Configuration; import com.coldradio.benzene.util.Geometry; public class NMeH_FG extends NMe2_FG { public NMeH_FG(Atom a_atom) { super(a_atom); Atom c1 = super.appendAtom(); Atom c2 = c1.getSkeletonAtom(); CompoundReactor.deleteAllHydrogen(super.getCompound(), c2); c2.setAtomicNumber(AtomicNumber.H); c2.setPoint(Geometry.pointInLine(c1.getPoint(), c2.getPoint(), Configuration.H_BOND_LENGTH_RATIO)); c1.getAtomDecoration().lettering(true); } @Override public String getName() { return "NMeH"; } } <file_sep>package com.coldradio.benzene.util; import android.graphics.PointF; import android.graphics.RectF; public class ScreenInfo { private RectF mRegion = new RectF(); private PointF mCenterPoint = new PointF(); private static ScreenInfo smInstance = new ScreenInfo(); public static ScreenInfo instance() { return smInstance; } public void setScreen(int x, int y, int w, int h) { mRegion.set(x, y, x + w, y + h); mCenterPoint.set(mRegion.centerX(), mRegion.centerY()); } public PointF centerPoint() { return mCenterPoint; } public RectF region() { return mRegion; } public int screenWidth() { return (int) mRegion.width(); } public int screenHeight() { return (int) mRegion.height(); } } <file_sep>package com.coldradio.benzene.library.pubchem; import android.text.Html; import android.text.Spanned; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.HttpHeaderParser; import com.coldradio.benzene.util.AppEnv; import com.google.gson.JsonSyntaxException; import java.io.UnsupportedEncodingException; class PubChemDescriptionRequest extends Request<Spanned> { private Response.Listener<Spanned> mListener; private Spanned buildDescriptionString(Description_JSON desc) { StringBuilder builder = new StringBuilder(); for (Description_JSON.Information_JSON info : desc.InformationList.Information) { if (info.Description != null && info.DescriptionSourceName != null) { builder.append("<p><b>- Description:</b> "); builder.append(info.Description); builder.append(" <i>from "); builder.append(info.DescriptionSourceName); builder.append("</i></p>"); } } if (builder.length() == 0) { builder.append("No Description for this compound"); } return Html.fromHtml(builder.toString()); } PubChemDescriptionRequest(int cid, final Response.Listener<Spanned> listener) { super(Method.GET, "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/" + cid + "/description/JSON", new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { listener.onResponse(Html.fromHtml("Error. try next time. " + error.toString())); } }); mListener = listener; } @Override protected void deliverResponse(Spanned response) { mListener.onResponse(response); } @Override protected Response<Spanned> parseNetworkResponse(NetworkResponse response) { try { String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); Description_JSON desc = AppEnv.instance().gson().fromJson(json, Description_JSON.class); return Response.success(buildDescriptionString(desc), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JsonSyntaxException e) { return Response.error(new ParseError(e)); } } } <file_sep>package com.coldradio.benzene.view; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import com.coldradio.benzene.R; import com.coldradio.benzene.util.AppEnv; import com.coldradio.benzene.util.Notifier; public class SelectAtomActivity extends AppCompatActivity { private void setTextViewOnClickListener(TableLayout tableLayout) { if (tableLayout == null) { return; } for (int ii = 0; ii < tableLayout.getChildCount(); ++ii) { TableRow tableRow = (TableRow) tableLayout.getChildAt(ii); for (int jj = 0; jj < tableRow.getChildCount(); ++jj) { final TextView textView = (TextView) tableRow.getChildAt(jj); if (textView != null && textView.getId() != View.NO_ID) { textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((TextView)findViewById(R.id.selectedAtom)).setText(textView.getText()); } }); } } } } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.change_atom_main); // attach onClick handler to TextView setTextViewOnClickListener((TableLayout) findViewById(R.id.basic_element_table_layout)); setTextViewOnClickListener((TableLayout) findViewById(R.id.transition_element_table_layout)); setTextViewOnClickListener((TableLayout) findViewById(R.id.unknown_element_table_layout)); // attach Listener to EditText EditText editText = findViewById(R.id.editText); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { TextView selectedAtomTv = findViewById(R.id.selectedAtom); if (selectedAtomTv != null) selectedAtomTv.setText(s); } @Override public void afterTextChanged(Editable s) { } }); // attack listener to buttons findViewById(R.id.cancelBtn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); findViewById(R.id.okBtn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent data = new Intent(); TextView atomName = findViewById(R.id.selectedAtom); if (atomName != null && atomName.getText().length() > 0) { data.putExtra("AtomName", atomName.getText().toString()); setResult(RESULT_OK, data); finish(); } else { Notifier.instance().notification("None Selected"); } } }); } @Override protected void onResume() { super.onResume(); AppEnv.instance().setCurrentActivity(this); } @Override protected void onPause() { super.onPause(); AppEnv.instance().setCurrentActivity(null); } }
6cc5ce522e58902210996638d1c987826032877c
[ "Markdown", "Java" ]
54
Java
ktnslt/benzene
3f810f37621044c91ded2e3b112f8ee056368d99
3a703a2aba6cd1f5ec7e2fded4624c3998d6aca9