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>ton1397/Bitchain<file_sep>/FormPrincipal.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Bitchain
{
public partial class FormPrincipal : Form
{
public static string id_usuario = FormLogin.id_usuario;
public static string id_cliente = "";
//public static string id_usuario = "1";
public FormPrincipal()
{
InitializeComponent();
}
private void FormPrincipal_Load(object sender, EventArgs e)
{
//FAZER UM SELECT NA BASE DE DADOS PARA TRAZER AS INFORMAÇÕES DO USUARIO NA TELA PRINCIPAL
getUserName();
getAllClients();
dgvCliente.ClearSelection();
cmbTipoBusca.SelectedIndex = 0;
}
private void getUserName()
{
string connetionString = "Data Source=DESKTOP-NJTO7KN;Initial Catalog=bitchain;user ID=DESKTOP-NJTO7KN/welli;Integrated Security=true;";
SqlConnection connection = new SqlConnection(connetionString);
SqlCommand command = new SqlCommand();
try
{
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "SELECT NOME FROM USUARIOS WHERE ID_USUARIO=@ID_USUARIO;";
command.Parameters.AddWithValue("@ID_USUARIO", id_usuario);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
string nome = reader["NOME"].ToString();
string[] arr_nome = nome.Split(' ');
lblNome.Text = arr_nome[0].ToString();
}
else
{
MessageBox.Show("nenhum usuario foi encontrado com este id");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
connection.Close();
}
}
public void getAllClients()
{
string connetionString = "Data Source=DESKTOP-NJTO7KN;Initial Catalog=bitchain;user ID=DESKTOP-NJTO7KN/welli;Integrated Security=true;";
SqlConnection connection = new SqlConnection(connetionString);
string query = "SELECT ID_CLIENTE AS ID, " +
"NOME AS Nome, " +
"EMAIL AS Email, " +
"DT_NASCIMENTO AS Nascimento, " +
"USUARIO AS Usuario " +
"FROM CLIENTES;";
SqlCommand command = new SqlCommand();
command.Connection = connection;
try
{
connection.Open();
SqlDataAdapter da = new SqlDataAdapter(query, connetionString);
DataSet ds = new DataSet();
da.Fill(ds, "Clientes");
dgvCliente.AutoGenerateColumns = true;
dgvCliente.DataSource = ds.Tables["Clientes"].DefaultView;
dgvCliente.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
connection.Close();
}
}
private void FormPrincipal_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void lblSair_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Deseja Sair do Sistema?", "", MessageBoxButtons.YesNo);
if (result.ToString() == "Yes")
{
Application.Exit();
}
}
private void lblMinhaConta_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
FormPerfil formPerfil = new FormPerfil();
formPerfil.Show();
}
private void btnCadCliente_Click(object sender, EventArgs e)
{
FormCadCliente formCadCliente = new FormCadCliente();
formCadCliente.ShowDialog();
dgvCliente.DataSource = null;
getAllClients();
}
private void btnAlterarCliente_Click(object sender, EventArgs e)
{
if (dgvCliente.SelectedCells.Count == 1)
{
FormAlterarCliente formAlterarCliente = new FormAlterarCliente();
int row = Convert.ToInt32(dgvCliente.CurrentCell.RowIndex);
string id = dgvCliente.Rows[row].Cells[0].Value.ToString();
id_cliente = id;
formAlterarCliente.ShowDialog();
dgvCliente.DataSource = null;
getAllClients();
}
else if(dgvCliente.SelectedCells.Count > 1)
{
MessageBox.Show("Selecione somente um registro para alterar");
}
else
{
MessageBox.Show("Selecione um registro para alterar");
}
}
private void btnDeletarCliente_Click(object sender, EventArgs e)
{
if (dgvCliente.SelectedRows.Count >= 1)
{
DialogResult result = MessageBox.Show("Deseja realmente deletar esses registros?", "", MessageBoxButtons.YesNo);
if (result.ToString() == "Yes")
{
try
{
foreach (DataGridViewRow row in dgvCliente.SelectedRows)
{
string id = dgvCliente.Rows[row.Index].Cells[0].Value.ToString();
DeletarCliente(id);
}
MessageBox.Show("Dados deletados com sucesso");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
dgvCliente.DataSource = null;
getAllClients();
}
}
}
else
{
MessageBox.Show("Selecione pelo menos uma linha da tabela para deletar. Caso deseje deletar mais de uma linha, pressione o CTRL e selecione as linhas que deseja deletar.");
}
}
private void DeletarCliente(string id)
{
string connetionString = "Data Source=DESKTOP-NJTO7KN;Initial Catalog=bitchain;user ID=DESKTOP-NJTO7KN/welli;Integrated Security=true;";
SqlConnection connection = new SqlConnection(connetionString);
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "DELETE FROM CLIENTES " +
"WHERE ID_CLIENTE=@ID_CLIENTE;";
command.Parameters.AddWithValue("@ID_CLIENTE", id);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
private void btnGerarRelatorio_Click(object sender, EventArgs e)
{
FormRelatorioClientes relatorio_Clientes = new FormRelatorioClientes();
relatorio_Clientes.Show();
}
private void txtNomeCliente_TextChanged(object sender, EventArgs e)
{
int index = cmbTipoBusca.SelectedIndex;
switch (index)
{
case 1:
getSearchClients("NOME");
break;
case 2:
getSearchClients("EMAIL");
break;
case 3:
getSearchClients("USUARIO");
break;
default:
MessageBox.Show("Não foi possivel determinar o indice campo selecionar");
break;
}
}
private void cmbTipoBusca_SelectedIndexChanged(object sender, EventArgs e)
{
txtNomeCliente.Text = "";
if (cmbTipoBusca.SelectedIndex == 0)
{
lblNomeCliente.Enabled = false;
txtNomeCliente.Enabled = false;
}
else
{
lblNomeCliente.Enabled = true;
txtNomeCliente.Enabled = true;
}
}
private void btnLimpaBusca_Click(object sender, EventArgs e)
{
txtNomeCliente.Text = "";
cmbTipoBusca.SelectedIndex = 0;
dgvCliente.DataSource = null;
getAllClients();
}
public void getSearchClients(string tipo)
{
string connetionString = "Data Source=DESKTOP-NJTO7KN;Initial Catalog=bitchain;user ID=DESKTOP-NJTO7KN/welli;Integrated Security=true;";
SqlConnection connection = new SqlConnection(connetionString);
string query = "SELECT ID_CLIENTE AS ID, " +
"NOME AS Nome, " +
"EMAIL AS Email, " +
"DT_NASCIMENTO AS Nascimento, " +
"USUARIO AS Usuario " +
"FROM CLIENTES " +
"WHERE " + tipo + " LIKE '%" + txtNomeCliente.Text + "%';";
SqlCommand command = new SqlCommand();
command.Connection = connection;
try
{
connection.Open();
SqlDataAdapter da = new SqlDataAdapter(query, connetionString);
DataSet ds = new DataSet();
da.Fill(ds, "Clientes");
dgvCliente.AutoGenerateColumns = true;
dgvCliente.DataSource = ds.Tables["Clientes"].DefaultView;
dgvCliente.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
connection.Close();
}
}
}
}
<file_sep>/FormAlterarCliente.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Bitchain
{
public partial class FormAlterarCliente : Form
{
public FormAlterarCliente()
{
InitializeComponent();
}
private void btnVoltar_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnCadastrar_Click(object sender, EventArgs e)
{
if (txtNome.Text == "")
{
MessageBox.Show("Campo nome é obrigatório");
}
else if (txtEmail.Text == "")
{
MessageBox.Show("Campo email é obrigatório");
}
else if (dtpNascimento.Text == "")
{
MessageBox.Show("Campo data de nascimento é obrigatório");
}
else if (txtUsuario.Text == "")
{
MessageBox.Show("Campo usuario é obrigatório");
}
else
{
string connetionString = "Data Source=DESKTOP-NJTO7KN;Initial Catalog=bitchain;user ID=DESKTOP-NJTO7KN/welli;Integrated Security=true;";
SqlConnection connection = new SqlConnection(connetionString);
SqlCommand command = new SqlCommand();
try
{
string nome = txtNome.Text;
string email = txtEmail.Text;
string dt_nascimento = dtpNascimento.Text;
string usuario = txtUsuario.Text;
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE CLIENTES SET " +
"NOME=@NOME, " +
"EMAIL=@EMAIL, " +
"DT_NASCIMENTO=@DT_NASCIMENTO, " +
"USUARIO=@USUARIO " +
"WHERE ID_CLIENTE=@ID_CLIENTE;";
command.Parameters.AddWithValue("@ID_CLIENTE", FormPrincipal.id_cliente);
command.Parameters.AddWithValue("@NOME", nome);
command.Parameters.AddWithValue("@EMAIL", email);
command.Parameters.AddWithValue("@DT_NASCIMENTO", dt_nascimento);
command.Parameters.AddWithValue("@USUARIO", usuario);
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("Dados alterados com sucesso");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
connection.Close();
this.Close();
}
}
}
private void FormAlterarCliente_Load(object sender, EventArgs e)
{
getUserDatails();
txtNome.Focus();
}
private void getUserDatails()
{
string connetionString = "Data Source=DESKTOP-NJTO7KN;Initial Catalog=bitchain;user ID=DESKTOP-NJTO7KN/welli;Integrated Security=true;";
SqlConnection connection = new SqlConnection(connetionString);
SqlCommand command = new SqlCommand();
try
{
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM CLIENTES WHERE ID_CLIENTE=@ID_CLIENTE;";
command.Parameters.AddWithValue("@ID_CLIENTE", FormPrincipal.id_cliente);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
Console.WriteLine(reader);
if (reader.Read())
{
txtNome.Text = reader["NOME"].ToString();
txtEmail.Text = reader["EMAIL"].ToString();
dtpNascimento.Text = reader["DT_NASCIMENTO"].ToString();
txtUsuario.Text = reader["USUARIO"].ToString();
}
else
{
MessageBox.Show("nenhum usuario foi encontrado com este id");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
connection.Close();
}
}
private void lblAlterarSenhaCliente_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
FormAlterarSenhaCliente formAlterarSenhaCliente = new FormAlterarSenhaCliente();
formAlterarSenhaCliente.Show();
}
}
}
<file_sep>/FormLogin.cs
using Microsoft.SqlServer.Server;
using Org.BouncyCastle.Crypto.Tls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Bitchain
{
public partial class FormLogin : Form
{
public static string id_usuario = "";
public FormLogin()
{
InitializeComponent();
}
private void FormLogin_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void lblCriarConta_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
FormCadUsuario formCadUsuario = new FormCadUsuario();
formCadUsuario.Show();
this.Hide();
}
private void btnEntrar_Click(object sender, EventArgs e)
{
string connetionString = "Data Source=DESKTOP-NJTO7KN;Initial Catalog=bitchain;user ID=DESKTOP-NJTO7KN/welli;Integrated Security=true;";
SqlConnection connection = new SqlConnection(connetionString);
SqlCommand command = new SqlCommand();
try
{
string usuario = txtUsuario.Text;
string senha = txtSenha.Text;
senha = ConverterSenhaEmHash(senha);
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "SELECT ID_USUARIO FROM USUARIOS WHERE USUARIO=@USUARIO AND SENHA=@SENHA;";
command.Parameters.AddWithValue("@USUARIO", usuario);
command.Parameters.AddWithValue("@SENHA", senha);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
id_usuario = reader["ID_USUARIO"].ToString();
FormPrincipal formPrincipal = new FormPrincipal();
formPrincipal.Show();
this.Hide();
}
else
{
MessageBox.Show("usuario e/ou senha invalidos.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
connection.Close();
txtUsuario.Text = "";
txtSenha.Text = "";
txtUsuario.Focus();
}
}
private string ConverterSenhaEmHash(string Senha)
{
MD5 md5 = new MD5CryptoServiceProvider();
//compute hash from the bytes of text
md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(Senha));
//get hash result after compute it
byte[] result = md5.Hash;
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < result.Length; i++)
{
//change it into 2 hexadecimal digits
//for each byte
strBuilder.Append(result[i].ToString("x2"));
}
return strBuilder.ToString();
}
private void txtUsuario_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnEntrar_Click(sender, e);
}
}
private void txtSenha_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnEntrar_Click(sender, e);
}
}
}
}
<file_sep>/FormCadUsuario.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace Bitchain
{
public partial class FormCadUsuario : Form
{
public FormCadUsuario()
{
InitializeComponent();
}
private void btnCadastrar_Click(object sender, EventArgs e)
{
if (txtNome.Text == "")
{
MessageBox.Show("Campo nome é obrigatório");
}
else if (txtEmail.Text == "")
{
MessageBox.Show("Campo email é obrigatório");
}
else if (dtpNascimento.Text == "")
{
MessageBox.Show("Campo data de nascimento é obrigatório");
}
else if (txtUsuario.Text == "")
{
MessageBox.Show("Campo usuario é obrigatório");
}
else if (txtSenha.Text == "")
{
MessageBox.Show("Campo senha é obrigatório");
}
else
{
string connetionString = "Data Source=DESKTOP-NJTO7KN;Initial Catalog=bitchain;user ID=DESKTOP-NJTO7KN/welli;Integrated Security=true;";
SqlConnection connection = new SqlConnection(connetionString);
SqlCommand command = new SqlCommand();
try
{
string nome = txtNome.Text;
string email = txtEmail.Text;
string dt_nascimento = dtpNascimento.Text;
string usuario = txtUsuario.Text;
string senha = txtSenha.Text;
senha = ConverterSenhaEmHash(senha);
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO USUARIOS(NOME,EMAIL,DT_NASCIMENTO,USUARIO,SENHA)VALUES(@NOME,@EMAIL,@DT_NASCIMENTO,@USUARIO,@SENHA);";
command.Parameters.AddWithValue("@NOME", nome);
command.Parameters.AddWithValue("@EMAIL", email);
command.Parameters.AddWithValue("@DT_NASCIMENTO", dt_nascimento);
command.Parameters.AddWithValue("@USUARIO", usuario);
command.Parameters.AddWithValue("@SENHA", senha);
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("Usuario cadastrado com sucesso!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
connection.Close();
txtNome.Text = "";
txtEmail.Text = "";
dtpNascimento.Text = "";
txtUsuario.Text = "";
txtSenha.Text = "";
}
}
}
private string ConverterSenhaEmHash(string Senha)
{
MD5 md5 = new MD5CryptoServiceProvider();
//compute hash from the bytes of text
md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(Senha));
//get hash result after compute it
byte[] result = md5.Hash;
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < result.Length; i++)
{
//change it into 2 hexadecimal digits
//for each byte
strBuilder.Append(result[i].ToString("x2"));
}
return strBuilder.ToString();
}
private void FormCadUsuario_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void btnVoltar_Click(object sender, EventArgs e)
{
FormLogin formLogin = new FormLogin();
formLogin.Show();
this.Hide();
}
}
}
<file_sep>/FormAlterarSenha.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Bitchain
{
public partial class FormAlterarSenha : Form
{
public FormAlterarSenha()
{
InitializeComponent();
}
private void btnVoltar_Click(object sender, EventArgs e)
{
this.Hide();
}
private void btnCadastrar_Click(object sender, EventArgs e)
{
if (txtSenhaNova.Text == "")
{
MessageBox.Show("Campo Senha nova é obrigatório");
}
else if (txtConfirmarSenhaNova.Text == "")
{
MessageBox.Show("Campo confirmar senha nova é obrigatório");
}
else if (txtSenhaNova.Text != txtConfirmarSenhaNova.Text)
{
MessageBox.Show("Campo confirmar senha nova e Senha nova não coincidem");
}
else {
string connetionString = "Data Source=DESKTOP-NJTO7KN;Initial Catalog=bitchain;user ID=DESKTOP-NJTO7KN/welli;Integrated Security=true;";
SqlConnection connection = new SqlConnection(connetionString);
SqlCommand command = new SqlCommand();
try
{
string senha_nova = ConverterSenhaEmHash(txtSenhaNova.Text);
string confirmar_senha_nova = ConverterSenhaEmHash(txtConfirmarSenhaNova.Text);
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE USUARIOS SET " +
"SENHA=@SENHA " +
"WHERE ID_USUARIO=@ID_USUARIO;";
command.Parameters.AddWithValue("@ID_USUARIO", FormPrincipal.id_usuario);
command.Parameters.AddWithValue("@SENHA", senha_nova);
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("Dados alterados com sucesso");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
connection.Close();
txtSenhaNova.Text = "";
txtConfirmarSenhaNova.Text = "";
}
}
}
private string ConverterSenhaEmHash(string Senha)
{
MD5 md5 = new MD5CryptoServiceProvider();
//compute hash from the bytes of text
md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(Senha));
//get hash result after compute it
byte[] result = md5.Hash;
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < result.Length; i++)
{
//change it into 2 hexadecimal digits
//for each byte
strBuilder.Append(result[i].ToString("x2"));
}
return strBuilder.ToString();
}
private void txtSenhaAtual_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnCadastrar_Click(sender, e);
}
}
private void txtSenhaNova_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnCadastrar_Click(sender, e);
}
}
private void txtConfirmarSenhaNova_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnCadastrar_Click(sender, e);
}
}
}
}
<file_sep>/FormRelatorioClientes.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 Bitchain
{
public partial class FormRelatorioClientes : Form
{
public FormRelatorioClientes()
{
InitializeComponent();
}
private void FormRelatorioClientes_Load(object sender, EventArgs e)
{
dtpDataInicial.Value = DateTime.Now.AddDays(1 - DateTime.Now.Day).AddMonths(-1);
}
private void btnGerarRelatorio_Click(object sender, EventArgs e)
{
if(txtIdCliente.Text == "")
{
MessageBox.Show("Por favor, insira o código do cliente");
}
else
{
// TODO: esta linha de código carrega dados na tabela 'BitchainDataSet.RELATORIO_CLIENTES'. Você pode movê-la ou removê-la conforme necessário.
this.RELATORIO_CLIENTESTableAdapter.Fill(this.BitchainDataSet.RELATORIO_CLIENTES, int.Parse(txtIdCliente.Text), dtpDataInicial.Value.ToString(), dtpDataFinal.Value.ToString());
this.reportViewer1.RefreshReport();
}
}
}
}
| 2b410e40e5c08b5516efa7e14a52aef198e12e3a | [
"C#"
]
| 6 | C# | ton1397/Bitchain | 1fc2bef51a606e7c9cd31bcda5a72d0b72983dbf | f7ba94dc1651848a2aa85230265c4a9084fbcb29 |
refs/heads/master | <repo_name>alexkuchina/guessingGame<file_sep>/js/main.js
//Variable that creates a random number from 1 to 100
var randomNumber = Math.floor((Math.random() * 100) +1)
//check random number
console.log(randomNumber)
//store user guesses
var guessNumber = 0
function guessGame() {
//variable that stores user's input
var userGuess = document.getElementById('userGuess')
//variable stores message for a user after guessing a number
var message = document.getElementById('message')
if (!userGuess.value || userGuess.value > 100 || userGuess.value < 0){
message.textContent = 'Try again'
userGuess.value = ""
return
}
if(userGuess.value == randomNumber) {
message.textContent = 'Congratulations, You guessed right!'
return
} else if(userGuess.value > randomNumber) {
message.textContent = 'Guess a lower number'
} else {
message.textContent = "Guess a higher number"
}
}
var submitGuess = document.getElementById('subButton')
submitGuess.addEventListener('click', guessGame, false)
| b87d2ae9f5f8e2b83ee349c54fbc9581e3d18add | [
"JavaScript"
]
| 1 | JavaScript | alexkuchina/guessingGame | 718be8808ebb05bef518e0fa4f6a840f8fcea0e1 | 7118cfc3ef2f256114e10dd25a1ac934368f3d87 |
refs/heads/master | <file_sep>#include<stdio.h>
int main()
{
unsigned int i = 1;
char *c = (char*)&i;
if (*c)
printf("Little");
else
printf("Big");
getchar();
return 0;
}
<file_sep>git remote -v
git push origin master
git remote add origin master https://github.com/jetman360/comp264hw3.git
git push origin master
push -u origin master
git push -u origin master
s
ls
datalab-f15-handout
ls
nano bits.c
ls
cd datalab-f15-handout
ls
nano bits.c
ls
cd.
cd .
cd
ls
rm -r comp264hw3
y
ls
rm -r hw3_test
ls
mkdir comp264hw3
ls
cd comp264hw3
chmod go -rwx .
chmod go-rwx .
ls
cd ..
ls
rm -r comp264hw3
ls
mkdir comp264hw3
cd comp264hw3
chmod go-rwx .
cp ~rig/public/c264/datalab-handout.tar
cp ~rig/public/c264/datalab-handout.tar .
tar xvr datalab-handout.tar
ls
tar xvf datalab-handout.tar
ls
rm datalab-handout.tar
ls
git init
git add .
git commit -m "first commit"
git remote add origin https://github.com/jetman360/comp264hw3.git
git remote -v
git push origin master
ls
cd datalab-f15-handout
ls
nano bits.c
clear
make
./btest
git push origin bitNor
cd ..
git push origin bitNor
git push origin master
ls
git add .
ls
git commit -m "bitNor"
git push -u origin bitNor
git push -u origin master
ls
ls
cd datalab-f15-handout
ls
nano bits.c
make
./btest
cd .
cd ..
git push origin master
git commit -m "bitXor"
git push origin master
git commit -a
ls
git commit -m "bitXor"
git add
git add .
git commit -m "bitXor"
git push origin master
cd datalab-f15-handout
nano bits.c
make
./btest
clear
nano bits.c
make
./btest
nano bits.c
make
./btest
nano bits.c
make
./btest
nano bits.c
make
./btest
nano bits.c
make
./btest
nano bits.c
make
./btest
nano bits.c
make
./btest
nano bits.c
ls
make
./btest
nano bits.c
make
./btest
git commit -m "all but replacebyte"
cd ..
git commit -m "all but replacebyte"
git add ..
git add .
git commit -m "all but replacebtye"
git push origin master
./drive.pl
cd datalab-f15-handout
./drive.pl
./dlc bits.c
./dlc -e bits.c
ls
cd comp264hw3
ls
cd datalab-f15-handout
ls
nano bits.c
nano bits.c
clear
make
make
./btest
vi bits.c
cd comp264hw3
cd datalab-f15-handout
nano bits.c
make
./btest
pico bits.c
make
make
..btest
./btest
nano bits.c
cd comp264hw3
ls
cd datalab-f15-handout
nano bits.c
make
nano bits.c
make
./btest
nano bits.c
make
./btest
nano bits.c
make
./btest
cd comp264hw3
ls
cd datalab-f15-handout
ls
make
./btest
nano bits.c
./driver.pl
nano bits.c
clear
nano bits.c
/* <<NAME> <EMAIL>>
*/
#if 0
n" statement in each function with one
or more lines of C code that implements the function. Your code
must conform to the following style:
int Funct(arg1, arg2, ...) {
/* brief description of how your implementation works */
int var1 = Expr1;
...
int varM = ExprM;
varJ = ExprJ;
...
varN = ExprN;
return ExprR;
}
Each "Expr" is an exp/* <<NAME> <EMAIL>>
*/
#if 0
n" statement in each function with one
or more lines of C code that implements the function. Your code
must conform to the following style:
int Funct(arg1, arg2, ...) {
/* brief description of how your implementation works */
int var1 = Expr1;
...
int varM = ExprM;
varJ = ExprJ;
...
varN = ExprN;
return ExprR;
}
Each "Expr" is an expclear
cd comp264hw3
cd datalab-f15-handout
ls
cp bits.c ~rig/c264hw3sub/[email protected]
ls -l ~rig/c264hw3sub/[email protected]
ls
cd comp264hw1
git
init
git init
git commit -m "first commit"
git add -A
git remote add origin https:github.com/jetman360/COMP-264.git
git add
git add .
git commit -m "first commit"
mkdir hw1
chmod go-rwx .
cp comp265hw1 hw1
cp -r comp265hw1 hw1
cd
cp -r comp265hw1 hw1
ls
comp264hw1
ls
cd comp264hw1
ls
rm -d hw1
rm--help
rm --helpgh
rm --help
rm -r hw1
ls
cd
ls
clear
mkdir hw1
chmod go-rwx .
chmod go-rwx hw1
ls -l
cp -r comp264hw1 hw1
ls
cd hw1
ls
cd ..
rm -r hw1
yes
ls
cd comp264h21
cd comp264hw1
ls
cd ..
mkdir hw1
chmod go-rwx hw1
git init
git commit -m "first commit"
cd hw1
git init
cd ..
clear
cd comp264hw1
ls
cd ..
cd comp264hw1
cp hello hello.c hello.i hello.o hello.s hello.zip hw1
cd ..
ls
cp hello ..
cd comp264hw1
cp hello ..
cd .
cd ..
ls
mv hello hw1
ls
cd
cd
cd hw1
ls
cd ..
cd comp264hw1
ls
cp hello.c hello.i. hello.o hello.s hello.zip ..
ls
cd ..
ls
mv hello.c hello.o hello.s. hello.zip hw1
la
ls
cp hello.s hw1
ls
cd hw1
ls
git init
git add _A
git add -A
git commit -m "first commit"
git remote add origin https:github.com/jetman360/COMP-264.git
git -u push
git -u push origin master
git push origin master
ls's
ls
cd/
gj o;e
..
cd.
clear
clear
end
pico
aset
emd
--help\
cd hw1
ls
git init
git commit -m "first commit"
git add -A
git commit -m "first commit"
git push -u origin master
git remote add origin https://github.com/jetman360/COMP-264.git
git push -u origin master
cd ..
rm -r hw1
mkdir hw1
chmod go-rwx hw1
mkdir hw211
mkdir hw31
chmod go-rwx hw2
chmod go-rwx hw3
cd hw1
cd ..
ls
cd hw1
ls
cd //
cd ..
cd comp264hw1
cd comp265hw1
ccd comp264hw1
cd comp264hw1
ls
cd hw1
cd home
ls
cd usr
cd ..
cd
ls
cd comp264hw1
ls
cp hello hello.c hello.i hello.o hello.s hellozip hw1
cp hello hello.c hello.i hello.o hello.s hellozip ..
cp hello.zip ..
cd ..
ls
cp hello hello.c hello.i hello.o hello.s hello.zip hw1
ls
cd hw1
ls
cd ..
ls
rm -r comp264hw1
ls
rm hello hello.c
ls
rm hello.i hello.o hello.s hello.zip
ls
cd comp264hw2
ls
cp <EMAIL>-15SEPT15.c edtest ..
cd ..
ls
cp <EMAIL>-15SEPT15.c edtest hw2
ls
cd hw2
ls
cd ..
ls
rm <EMAIL>-15SEPT15 edtest
ls
rm <EMAIL>-15SEPT15.c edtest
ls
rm -r comp264hw2
ls
cd hw2
ls
cd ..
ls
cd comp264hw3
ls
cp datalab-f15-handout ..
cd ..
ls
cp-r datalab-f15-handout ..
cp --help
ls
cd comp264hw3
ls
mv ..
mv --help
ls
cp cp datalab-f15-handout ..
cp -r datalab-f15-handout ..
ls
cd ..
ls
cp -r datalab-f15-handout hw3
ls
cd hw3
ls
cd datalab-f15-handout
ls
cd ..
cd..
cd ..
ls
rm -r comp264hw1 datalab-f15-handout
ls
rm -r comp264hw3
y
ls
cd hw3
cd ..
hw1
cd hw1
ls
git init
cd ..
git init
add -A
git add -A
git commit -m "first commit"
git remote add origin https://github.com/jetman360/COMP-264.goit
git remote add origin https://github.com/jetman360/COMP-264.git
git push -u origin master
git remote -v
git remote set-url origin https://github.com/jetman360/COMP-264.git
git remote -v
git push -u origin master
ls
cd hw3
cd ..
cd hw2
ls
ls
mkdir hw4
chmod go-rwx .
cd hw4
nano decode4.c
cd hw4
ls
nano decode.c
clear
ls
gcc- o decode.c decode
gcc -o decode decode.c
nano decode.c
nano decode.c
clear
gcc -o decode decode.c
nano decode.c
celar
clear
gcc -o decode.c
gcc -o decode decode.c
ls
./decode
gcc -S decode.c -o codetest
ls
nano codetest
lear
clear
ls
rm decode
ls
cp decodetest ~rig/c264hw4sub/[email protected]
cp codetest ~rig/c264hw4sub/[email protected]
ls
ls -l ~rig/c264hw4sub/[email protected]
<file_sep>#include <stdio.h>
main(){
long x,y,z;
x=y+x;
x=z*x;
return x;
x>>=15;
x<<=31;
x&&x;
return;
}
<file_sep>/*Hello World Program */
#include<stdio.h>
int
main(void)
{
printf("Hello world is a program used by hackers to test programs.");
return 0;
}
<file_sep># When an interactive shell that is not a login shell is started, bash
# reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if
# these files exist.
# The standard /etc/profile on our system for login shells actually
# also sources /etc/bash.bashrc , and if you've copied my recommended
# ~/.bash_profile for login shells, that sources ~/.bashrc . So I
# recommend that you copy this file to your ~/.bashrc to execute its
# content for *all* interactive shells.
# With this setup, though, you have to be careful about some
# apparently interactive shells such as scp and rcp that can't
# tolerate any output. The immediately following code tests for a
# truly interactive shell. There is no need to set anything past this
# point for scp and rcp, and it's important to refrain from outputting
# anything in those cases.
if [[ $- != *i* ]] ; then
# Shell is non-interactive. Be done now!
return
fi
# Now you should be able to safely put what you want here. The
# following three lines at least are recommended.
alias rm='rm -i'
alias mv='mv -i'
alias cp='cp -i'
| d6c4c1cc41c047aa5db1c9321b02c81adc95dfcd | [
"C",
"Shell"
]
| 5 | C | jetman360/COMP-264 | dded8cf6de4fafd2cac29336582cc1bdb09755fa | d0144810041acbf83fb8b87a50ea1af0972eb4d8 |
refs/heads/master | <file_sep><?php
class Cms59148813c5431506906009_55ccb44d7b398451032b387869d4f49aClass extends \Cms\Classes\PageCode
{
}
<file_sep><?php
class Cms59148848a6ec8784975080_d73a1417f7f5736183e6249ec5454d86Class extends \Cms\Classes\PageCode
{
}
<file_sep><?php
class Cms5914884bd507c773494690_adccf17142ca1d68319da37042ef4a7cClass extends \Cms\Classes\PageCode
{
}
<file_sep><?php
class Cms5914880111253249308494_4d674bfac811112896157c702ed5d988Class extends \Cms\Classes\PageCode
{
}
<file_sep><?php
class Cms5914880110744049336952_4f99ce46df93e37a2cdc5e768dca0170Class extends \Cms\Classes\LayoutCode
{
}
<file_sep><?php
class Cms5914880131587533019164_61cb93b06c46e436a1797090a847522aClass extends \Cms\Classes\PartialCode
{
}
<file_sep><?php
class Cms5914884e97ad6797349873_d05265f9a4b998dd28aa9754b38b03deClass extends \Cms\Classes\PageCode
{
}
| 7d529102e4775ba998f9391b6d5e33468d3de1a9 | [
"PHP"
]
| 7 | PHP | PuHaoran/sys.octo.com | e4adf739dfbcf25ab35ab72cad829db507792008 | dee9935b4ec21670d42d2d1ebc7a72df91d4aeb8 |
refs/heads/master | <repo_name>jamesmacwhite/craftnet<file_sep>/web/craftnetresources/id/src/js/store/modules/cart.js
import Vue from 'vue'
import Vuex from 'vuex'
import api from '../../api/cart'
import CartHelper from '../../helpers/cart'
Vue.use(Vuex)
/**
* State
*/
const state = {
cart: null,
selectedExpiryDates: {},
}
/**
* Getters
*/
const getters = {
cartTotal() {
return 0
},
cartTotalItems(state) {
if(state.cart && state.cart.lineItems) {
return state.cart.lineItems.length;
}
return 0
},
cartItems(state, getters, rootState) {
let cartItems = []
if (state.cart) {
const lineItems = state.cart.lineItems
lineItems.forEach(lineItem => {
let cartItem = {}
cartItem.id = lineItem.id
cartItem.lineItem = lineItem
if (lineItem.purchasable.type === 'plugin-edition') {
cartItem.plugin = rootState.pluginStore.plugins.find(p => p.handle === lineItem.purchasable.plugin.handle)
}
cartItems.push(cartItem)
})
}
return cartItems
},
cartItemsData(state) {
return CartHelper.getCartItemsData(state.cart)
}
}
/**
* Actions
*/
const actions = {
getCart({dispatch, commit, rootState, state}) {
return new Promise((resolve, reject) => {
if (!state.cart) {
dispatch('getOrderNumber')
.then(orderNumber => {
if (orderNumber) {
api.getCart(orderNumber, response => {
if (!response.error) {
commit('updateCart', {response})
resolve(response)
} else {
// Couldn’t get cart for this order number? Try to create a new one.
const data = {
email: rootState.account.currentUser.email
}
api.createCart(data, response2 => {
commit('updateCart', {response: response2})
dispatch('saveOrderNumber', {orderNumber: response2.cart.number})
resolve(response)
}, response => {
reject(response)
})
}
}, response => {
if(response.response.data.message && response.response.data.message === 'Cart Already Completed') {
const data = {
email: rootState.account.currentUser.email
}
api.createCart(data, response2 => {
commit('updateCart', {response: response2})
dispatch('saveOrderNumber', {orderNumber: response2.cart.number})
resolve(response)
}, response => {
reject(response)
})
} else {
reject(response)
}
})
} else {
// No order number yet? Create a new cart.
const data = {
email: rootState.account.currentUser.email
}
api.createCart(data, response => {
commit('updateCart', {response})
dispatch('saveOrderNumber', {orderNumber: response.cart.number})
resolve(response)
}, response => {
reject(response)
})
}
})
} else {
resolve()
}
})
},
saveCart({commit, state}, data) {
return new Promise((resolve, reject) => {
const cart = state.cart
api.updateCart(cart.number, data, response => {
if (!response.errors) {
commit('updateCart', {response})
resolve(response)
} else {
reject(response)
}
}, response => {
reject(response)
})
})
},
resetCart({commit, dispatch}) {
return new Promise((resolve, reject) => {
commit('resetCart')
dispatch('resetOrderNumber')
dispatch('getCart')
.then(response => {
resolve(response)
})
.catch(response => {
reject(response)
})
})
},
resetOrderNumber() {
api.resetOrderNumber()
},
// eslint-disable-next-line
checkout({}, data) {
return new Promise((resolve, reject) => {
api.checkout(data)
.then(response => {
resolve(response)
})
.catch(response => {
reject(response)
})
})
},
getOrderNumber({state}) {
return new Promise((resolve, reject) => {
if (state.cart && state.cart.number) {
const orderNumber = state.cart.number
resolve(orderNumber)
} else {
api.getOrderNumber(orderNumber => {
resolve(orderNumber)
}, response => {
reject(response)
})
}
})
},
// eslint-disable-next-line
saveOrderNumber({}, {orderNumber}) {
api.saveOrderNumber(orderNumber)
},
addToCart({commit, state, dispatch}, newItems) {
return new Promise((resolve, reject) => {
dispatch('getCart')
.then(() => {
const cart = state.cart
let items = CartHelper.getCartItemsData(cart)
newItems.forEach(newItem => {
let item = {...newItem}
if (!item.expiryDate) {
item.expiryDate = '1y'
}
items.push(item)
})
let data = {
items,
}
api.updateCart(cart.number, data, response => {
commit('updateCart', {response})
resolve(response)
}, response => {
reject(response)
})
})
.catch(reject)
})
},
removeFromCart({commit, dispatch}, lineItemKey) {
return new Promise((resolve, reject) => {
dispatch('getCart')
.then(() => {
const cart = state.cart
let items = CartHelper.getCartItemsData(cart)
items.splice(lineItemKey, 1)
let data = {
items,
}
api.updateCart(cart.number, data, response => {
commit('updateCart', {response})
resolve(response)
}, response => {
reject(response)
})
})
.catch(reject)
})
},
updateItem({commit, state}, {itemKey, item}) {
return new Promise((resolve, reject) => {
const cart = state.cart
let items = CartHelper.getCartItemsData(cart)
items[itemKey] = item
let data = {
items,
}
api.updateCart(cart.number, data, response => {
commit('updateCart', {response})
resolve(response)
}, response => {
reject(response)
})
})
},
}
/**
* Mutations
*/
const mutations = {
updateCart(state, {response}) {
state.cart = response.cart
state.stripePublicKey = response.stripePublicKey
const selectedExpiryDates = {}
state.cart.lineItems.forEach(lineItem => {
selectedExpiryDates[lineItem.id] = lineItem.options.expiryDate
})
state.selectedExpiryDates = selectedExpiryDates
},
resetCart(state) {
state.cart = null
},
updateSelectedExpiryDates(state, selectedExpiryDates) {
state.selectedExpiryDates = selectedExpiryDates
},
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
<file_sep>/web/craftnetresources/id/src/js/mixins/helpers.js
import get from 'lodash/get'
import update from 'lodash/update'
export default {
methods: {
/**
* Clones an object without references or bindings.
* Optionally accepts a filtered property list with dot-syntax
* for nested properties.
*
* Example:
* ```
* let obj = {
* test: 'value',
* foo: {
* bar: {
* baz: 'one',
* boo: 'two'
* }
* }
* }
*
* // an existing value and a missing value, with default
* let clone = simpleClone(obj, [
* 'foo.bar.baz',
* ['aList', []]
* ])
*
* clone == {foo: {bar: {baz: 'hello'}}, aList: []} // true
* ```
*
* @param {Object} obj
* @param {Array} propertyList
*/
simpleClone(obj, propertyList) {
let clone = JSON.parse(JSON.stringify(obj))
if (!propertyList) {
return clone
}
let filteredClone = {}
for (let i = 0; i < propertyList.length; i++) {
const path = propertyList[i];
if (typeof path === 'object') {
update(filteredClone, path, () => get(clone, path[0], path[1]))
} else {
update(filteredClone, path, () => get(clone, path, null))
}
}
return filteredClone;
},
/**
* Returns a static image URL.
*
* @param {String} url
* @returns {String}
*/
staticImageUrl(url) {
if (process.env.NODE_ENV === 'development') {
return process.env.BASE_URL + 'img/static/' + url;
}
return '/craftnetresources/id/dist/img/static/' + url;
},
/**
* Returns the Craft Plugins URL.
*
* @returns {String}
*/
craftPluginsUrl() {
return process.env.VUE_APP_CRAFT_PLUGINS_URL;
}
}
}
<file_sep>/web/craftnetresources/id/src/js/app.js
// import './../sass/app.scss';
import Vue from 'vue';
import store from './store'
import {currency} from './filters/currency';
import {formatCmsLicense, formatPluginLicense} from './filters/licenses';
import {capitalize} from './filters/capitalize';
import App from './App.vue';
import './plugins/craftui'
Vue.filter('currency', currency);
Vue.filter('formatCmsLicense', formatCmsLicense);
Vue.filter('formatPluginLicense', formatPluginLicense);
Vue.filter('capitalize', capitalize);
Vue.use(require('vue-moment'));
import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)
window.craftIdApp = new Vue({
store,
render: h => h(App),
data() {
return {
}
},
methods: {
/**
* Connect app callback.
*
* @param apps
*/
connectAppCallback(apps) {
this.$store.dispatch('account/connectAppCallback', apps);
this.$store.dispatch('app/displayNotice', 'App connected.');
},
},
}).$mount('#app')
<file_sep>/web/craftnetresources/id/src/js/store/modules/licenses.js
import Vue from 'vue'
import Vuex from 'vuex'
import licensesApi from '../../api/licenses';
Vue.use(Vuex)
Vue.use(require('vue-moment'))
var VueApp = new Vue();
/**
* State
*/
const state = {
cmsLicenses: [],
pluginLicenses: [],
}
/**
* Getters
*/
const getters = {
expiresSoon() {
return license => {
if(!license.expiresOn) {
return false
}
const today = new Date()
let expiryDate = new Date()
expiryDate.setDate(today.getDate() + 45)
const expiresOn = new Date(license.expiresOn.date)
if(expiryDate > expiresOn) {
return true
}
return false
}
},
daysBeforeExpiry() {
return license => {
const today = new Date()
const expiresOn = new Date(license.expiresOn.date)
const diff = expiresOn.getTime() - today.getTime()
const diffDays = Math.round(diff / (1000 * 60 * 60 * 24))
return diffDays;
}
},
expiringCmsLicenses(state, getters) {
return state.cmsLicenses.filter(license => {
if (license.expired) {
return false
}
if (license.autoRenew) {
return false
}
return getters.expiresSoon(license)
})
},
expiringPluginLicenses(state, getters) {
return state.pluginLicenses.filter(license => {
if (license.expired) {
return false
}
if (license.autoRenew) {
return false
}
return getters.expiresSoon(license)
})
},
renewableLicenses(state, getters, rootState) {
return (license, renew) => {
let renewableLicenses = []
// CMS license
const expiryDateOptions = rootState.pluginStore.licenseExpiryDateOptions.cmsLicenses[license.id]
let expiryDate = expiryDateOptions[renew][1]
renewableLicenses.push({
type: 'cms-renewal',
key: license.key,
description: 'Craft ' + license.editionDetails.name,
renew: renew,
expiryDate: expiryDate,
expiresOn: license.expiresOn,
edition: license.editionDetails,
})
// Plugin licenses
if (license.pluginLicenses.length > 0) {
// Renewable plugin licenses
const renewablePluginLicenses = state.pluginLicenses.filter(pluginLicense => {
// Only keep plugin licenses related to this CMS license
if (pluginLicense.cmsLicenseId !== license.id) {
return false
}
// Plugin licenses with no `expiresOn` are not renewable
if (!pluginLicense.expiresOn) {
return false
}
// Ignore the plugin license if it expires after the CMS license
if (!pluginLicense.expired) {
const pluginExpiresOn = VueApp.$moment(pluginLicense.expiresOn.date)
const expiryDateObject = VueApp.$moment(expiryDate)
if(expiryDateObject.diff(pluginExpiresOn) < 0) {
return false
}
}
return true
})
// Add renewable plugin licenses to the `renewableLicenses` array
renewablePluginLicenses.forEach(function(renewablePluginLicense) {
renewableLicenses.push({
type: 'plugin-renewal',
key: renewablePluginLicense.key,
description: renewablePluginLicense.plugin.name,
expiryDate: expiryDate,
expiresOn: renewablePluginLicense.expiresOn,
edition: renewablePluginLicense.edition,
})
})
}
return renewableLicenses
}
},
}
/**
* Actions
*/
const actions = {
// eslint-disable-next-line
claimCmsLicense({}, licenseKey) {
return new Promise((resolve, reject) => {
licensesApi.claimCmsLicense(licenseKey, response => {
if (response.data && !response.data.error) {
resolve(response);
} else {
reject(response);
}
}, response => {
reject(response);
})
})
},
// eslint-disable-next-line
claimCmsLicenseFile({}, licenseFile) {
return new Promise((resolve, reject) => {
licensesApi.claimCmsLicenseFile(licenseFile, response => {
if (response.data && !response.data.error) {
resolve(response);
} else {
reject(response);
}
}, response => {
reject(response);
})
})
},
// eslint-disable-next-line
claimLicensesByEmail({}, email) {
return new Promise((resolve, reject) => {
licensesApi.claimLicensesByEmail(email, response => {
if (response.data && !response.data.error) {
resolve(response);
} else {
reject(response);
}
}, response => {
reject(response);
})
})
},
// eslint-disable-next-line
claimPluginLicense({}, licenseKey) {
return new Promise((resolve, reject) => {
licensesApi.claimPluginLicense(licenseKey, response => {
if (response.data && !response.data.error) {
resolve(response);
} else {
reject(response);
}
}, response => {
reject(response);
})
})
},
getCmsLicenses({commit}) {
return new Promise((resolve, reject) => {
licensesApi.getCmsLicenses(response => {
if (response.data && !response.data.error) {
commit('updateCmsLicenses', {cmsLicenses: response.data});
resolve(response);
} else {
reject(response);
}
}, response => {
reject(response);
})
})
},
getPluginLicenses({commit}) {
return new Promise((resolve, reject) => {
licensesApi.getPluginLicenses(response => {
if (response.data && !response.data.error) {
commit('updatePluginLicenses', {pluginLicenses: response.data});
resolve(response);
} else {
reject(response);
}
}, response => {
reject(response);
})
})
},
releaseCmsLicense({commit}, licenseKey) {
return new Promise((resolve, reject) => {
licensesApi.releaseCmsLicense(licenseKey, response => {
if (response.data && !response.data.error) {
commit('releaseCmsLicense', {licenseKey});
resolve(response);
} else {
reject(response);
}
}, response => {
reject(response);
})
})
},
releasePluginLicense({commit}, {pluginHandle, licenseKey}) {
return new Promise((resolve, reject) => {
licensesApi.releasePluginLicense({pluginHandle, licenseKey}, response => {
if (response.data && !response.data.error) {
commit('releasePluginLicense', {licenseKey});
resolve(response);
} else {
reject(response);
}
}, response => {
reject(response);
})
})
},
saveCmsLicense({commit}, license) {
return new Promise((resolve, reject) => {
licensesApi.saveCmsLicense(license, response => {
if (response.data && !response.data.error) {
commit('saveCmsLicense', { license: response.data.license });
resolve(response);
} else {
reject(response);
}
}, response => {
reject(response);
})
})
},
savePluginLicense({commit}, license) {
return new Promise((resolve, reject) => {
licensesApi.savePluginLicense(license, response => {
if (response.data && !response.data.error) {
commit('savePluginLicense', {license});
resolve(response);
} else {
reject(response);
}
}, response => {
reject(response);
})
})
},
}
/**
* Mutations
*/
const mutations = {
updateCmsLicenses(state, {cmsLicenses}) {
state.cmsLicenses = cmsLicenses;
},
updatePluginLicenses(state, {pluginLicenses}) {
state.pluginLicenses = pluginLicenses;
},
releaseCmsLicense(state, {licenseKey}) {
state.cmsLicenses.find((l, index, array) => {
if (l.key === licenseKey) {
array.splice(index, 1);
return true;
}
return false;
});
},
releasePluginLicense(state, {licenseKey}) {
state.pluginLicenses.find((l, index, array) => {
if (l.key === licenseKey) {
array.splice(index, 1);
return true;
}
return false;
});
},
saveCmsLicense(state, {license}) {
let stateLicense = state.cmsLicenses.find(l => l.key == license.key);
for (let attribute in license) {
switch(attribute) {
case 'autoRenew':
stateLicense[attribute] = license[attribute] === 1 || license[attribute] === '1' ? true : false
break
default:
stateLicense[attribute] = license[attribute];
}
}
},
savePluginLicense(state, {license}) {
let stateLicense = state.pluginLicenses.find(l => l.key == license.key);
for (let attribute in license) {
switch(attribute) {
case 'autoRenew':
stateLicense[attribute] = license[attribute] === 1 || license[attribute] === '1' ? true : false
break
default:
stateLicense[attribute] = license[attribute];
}
}
},
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
| 7e82143ff632947e6fb195a15643f5e855a3a2d5 | [
"JavaScript"
]
| 4 | JavaScript | jamesmacwhite/craftnet | 89d310d1b6ffd63858a26be6a2114a424a195dac | bd39809bad3b06d36dfd1c31ca74ec2efd9f2f9b |
refs/heads/main | <repo_name>Stefania9797/js-jsnacks-blocco-5<file_sep>/snack-3/main.js
/*Snack 3:
Scrivi una funzione che accetti una stringa come argomento e la ritorni girata (es. Ciao -> oaiC)*/
/**
* Questa funzione rovescia la stringa inserita.
* La stringa viene prima divisa in singoli caratteri, poi rovesciata ed infine riconvertita in stringa
* @param {String} stringa //accetta una stringa come argomento
* @return {String} //La stringa rovesciata
*/
function reverse(stringa){
return stringa.split("").reverse().join("");
}
//esempi
console.log(reverse("ciao"));
console.log(reverse("giallo"));
console.log(reverse("libro"));<file_sep>/snack-2/main.js
//Snack 2:
//Crea 10 oggetti che rappresentano una zucchina.
var Zucchine = [
{varietà:"Zucchina bolognese", peso: 70, lunghezza:8},
{varietà:"Zucchina scura", peso: 100, lunghezza:10},
{varietà:"Zucchina chiara", peso: 40, lunghezza:15},
{varietà:"Zucchina milanese", peso: 61, lunghezza:4},
{varietà:"Zucchina romanesca", peso: 30, lunghezza:6},
{varietà:"Zucchina fiorentina", peso: 50, lunghezza:13},
{varietà:"Zucchina friulana", peso: 63, lunghezza:6},
{varietà:"Zucchina gialla", peso: 89, lunghezza:11},
{varietà:"Zucchina messicana", peso: 31, lunghezza:17},
{varietà:"Zucchina bolognese", peso: 59, lunghezza:14},
]
//Dividi in due array separati le zucchine che misurano meno o più di 15cm.
var zucchineCorte=[];
var zucchineLunghe=[];
for (var i = 0; i < Zucchine.length; i++) {
if(Zucchine[i].lunghezza<15){
zucchineCorte.push(Zucchine[i])
}
else if(Zucchine[i].lunghezza>=15){
zucchineLunghe.push(Zucchine[i])
}
}
console.log(zucchineCorte);
console.log(zucchineLunghe);
//Infine stampa separatamente quanto pesano i due gruppi di zucchine.
function pesoTotale(array) {
var pesoTotale = 0;
for (var i = 0; i < array.length; i++) {
pesoTotale += array[i].peso;
}
return pesoTotale;
}
console.log("Il peso totale delle zucchine corte è "+pesoTotale(zucchineCorte)+" kg");
console.log("Il peso totale delle zucchine lunghe "+pesoTotale(zucchineLunghe)+" kg");
<file_sep>/snack-5/main.js
/*Snack 5:
Scrivi una funzione che accetti tre argomenti:
un array e due numeri (“a” più piccolo di “b” e “b”
grande al massimo quanto il numero di elementi dell’array).
La funzione ritornerà un nuovo array con i valori che hanno
la posizione compresa tra “a” e “b”*/
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
function GetNewArray(array,a,b){
var newArray=[];
for(var i=0; i<array.length;i++){
if(array[i]>=a && array[i]<=b){
newArray.push(array[i])
}
}
return newArray
}
//numeri a e b
var randomArray= [1,2,3,4,5,6,7,8,9,10]
var a=getRandomNumber(1,randomArray.length)
var b=getRandomNumber((a+1),randomArray.length)
console.log(a,b);
console.log(GetNewArray(randomArray,a,b)); | c9e8a96c9e166f5236fc719d45cab4d66dc3998c | [
"JavaScript"
]
| 3 | JavaScript | Stefania9797/js-jsnacks-blocco-5 | 31bcb19cded0eb6fe3e1b56f5439055b44ad9350 | 312a3fbad644d161d2c29bc6e17d453b4a266252 |
refs/heads/master | <file_sep>rootProject.name = 'UITestFramework'
<file_sep>package pages;
import org.openqa.selenium.By;
import utils.Reporter;
import wrappers.OpentapsWrappers;
/**
* Created by Udhayakumar PC2 on 23-05-2016.
*/
public class BookHotelConfirmationPage extends OpentapsWrappers {
public BookedItineraryPage clickMyItinerary() {
clickById(prop.getProperty("Home.Myitinerary.id"));
return new BookedItineraryPage();
}
public BookHotelConfirmationPage clickLogout() {
clickByXpath(prop.getProperty("LogoutPage.Logout.Link"));
return this;
}
public BookHotelConfirmationPage verifyTotelPrice(String price){
if(!verifyTextboxValueById(prop.getProperty("bookconfirmation.totalprice.id"),price))
Reporter.reportStep("Price Not Matched with the Entered Data ","FAIL");
return this ;
}
public BookHotelConfirmationPage verifyHotelName(String name) {
if(!verifyTextboxValueById(prop.getProperty("bookconfirmation.hotelName.id"), name))
Reporter.reportStep("entered hotel name does not match with the hotel name shown in the search results", "FAIL");
return this;
}
public BookHotelConfirmationPage verifyRoomType(String roomType){
if(!verifyTextboxValueById(prop.getProperty("bookconfirmation.roomType.id"),roomType))
Reporter.reportStep("Room type not match with the room type entered in search hotel ","FAIL");
return this ;
}
public BookHotelConfirmationPage arrivalDate(String arrivalDate){
if(!verifyTextboxValueById(prop.getProperty("bookconfirmation.arrivalDate.id"), arrivalDate))
Reporter.reportStep(" Arrival Date does not match with the Dates Entered in Search Hotel", "FAIL");
return this ;
}
public BookHotelConfirmationPage depatureDate(String depatureDate){
if(!verifyTextboxValueById(prop.getProperty("bookconfirmation.depatureDate.id"), depatureDate))
Reporter.reportStep(" Depature Date does not match with the Dates Entered in Search Hotel", "FAIL");
return this ;
}
public BookHotelConfirmationPage verifyRoomCount(String roomCount){
if(!verifyTextboxValueById(prop.getProperty("bookconfirmation.roomCount.id"),roomCount))
Reporter.reportStep(" Room count not match with the no of room entered in the search hotel page","FAIL");
return this ;
}
public BookHotelConfirmationPage verifyAdultcount(String adult){
if(!verifyTextboxValueById(prop.getProperty("bookconfirmation.adultperRoom.id"), adult))
Reporter.reportStep(" Adult count not matched with existing data", "FAIL");
return this ;
}
public BookHotelConfirmationPage verifyChildrenCount(String children){
if(!verifyTextboxValueById(prop.getProperty("bookconfirmation.childrenperRoom.id"),children))
Reporter.reportStep(" Children count not matched with existing data","FAIL");
return this ;
}
public BookHotelConfirmationPage verifyOrderNumber() throws InterruptedException {
boolean boolan = driver.findElement(By.id("order_no")).isEnabled();
System.out.print(boolan);
Thread.sleep(10000);
Reporter.reportStep("order number not generated","FAIL");
return this ;
}
}
<file_sep>package pages;
import utils.Reporter;
import wrappers.OpentapsWrappers;
/**
* Created by Udhayakumar PC2 on 23-05-2016.
*/
public class BookHotelPage extends OpentapsWrappers {
public BookHotelPage verifyTotelPrice(String price){
if(!verifyTextboxValueById(prop.getProperty("Bookhotel.price.id"),price))
Reporter.reportStep("Price Not Matched with the Entered Data ","FAIL");
return this ;
}
public BookHotelPage enterFirstname(String fname) {
enterById(prop.getProperty("Home.firstName.Id"),fname);
return this;
}
public BookHotelPage enterLasttname(String lname) {
enterById(prop.getProperty("Home.lastName.Id"),lname);
return this;
}
public BookHotelPage enterAddress(String address) {
enterById(prop.getProperty("Home.billngAddress.id"),address);
return this;
}
public BookHotelPage enterCCNumber(String ccno) {
enterById(prop.getProperty("home.ccno.id"),ccno);
return this;
}
public BookHotelPage enterCCType(String type) {
selectById(prop.getProperty("Home.cctype.id"),type);
return this;
}
public BookHotelPage enterexpmonth(String expMonth) {
selectById(prop.getProperty("Home.expmonth.id"),expMonth);
return this;
}
public BookHotelPage enterExpYear(String expYear) {
selectById(prop.getProperty("Home.expyear.id"),expYear);
return this;
}
public BookHotelPage enterCvvNumber(String cvv) {
enterById(prop.getProperty("Home.cvv.id"),cvv);
return this;
}
public BookHotelConfirmationPage clickBooknow() throws InterruptedException {
clickById(prop.getProperty("home.booknow.id"));
Thread.sleep(10000);
String orderNumber = getTextById(prop.getProperty("Book.Confirm.OrderNumber"));
// System.out.print("ord" + orderNumber);
Reporter.reportStep("Order has been generated. Order Number is " + orderNumber,"PASS");
if(orderNumber==null)
Reporter.reportStep("Order is not created", "FAIL");
return new BookHotelConfirmationPage();
}
public BookHotelPage verifyHotelName(String name) {
if(!verifyTextboxValueById(prop.getProperty("bookhotel.hotelname.id"), name))
Reporter.reportStep("entered location name does not match with the location shown in the search results", "FAIL");
return this;
}
public BookHotelPage verifyHotelLocation(String location) {
if(!verifyTextboxValueById(prop.getProperty("Bookhotel.verifylocation.id"), location))
Reporter.reportStep("entered location name does not match with the location shown in the search results", "FAIL");
return this;
}
public BookHotelPage verifyRoomType(String roomType){
if(!verifyTextboxValueById(prop.getProperty("bookhotel.verifyroomtype.id"),roomType))
Reporter.reportStep("Room type not match with the room type entered in search hotel ","FAIL");
return this ;
}
public BookHotelPage verifyTotalDay(String totalDays){
if(!verifyTextboxValueById(prop.getProperty("bookhotel.verifytotalday.id"),totalDays))
Reporter.reportStep("Room type not match with the room type entered in search hotel ","FAIL");
return this ;
}
public BookHotelPage verifyPriceperNight(String priceperNight){
if(!verifyTextboxValueById(prop.getProperty("bookhotel.verifypricepernight.id"),priceperNight))
Reporter.reportStep("Room type not match with the room type entered in search hotel ","FAIL");
return this ;
}
public BookHotelPage verifyFinalbilledPrice(String finalBill){
if(!verifyTextboxValueById(prop.getProperty("bookhotel.verifyfinalbill.id"),finalBill))
Reporter.reportStep("Room type not match with the room type entered in search hotel ","FAIL");
return this ;
}
}
| 70757b8406d1ba38de763bb8dc984b2093cfd83e | [
"Java",
"Gradle"
]
| 3 | Gradle | gunaphysics/UITestFramework | 15642ca14ac57fc1d66ff95eac11d09334d42cca | 3f222e52cd60358874671c361f845c83e67e44fb |
refs/heads/master | <file_sep>import os
from os import listdir
from os.path import isfile, join
import sys
import h5py
import numpy as np
import pandas as pd
from pandas import DataFrame as df
import matplotlib.pyplot as plt
import cmath
import igor.igorpy as igor
import re
import yaml
import struct
from lmfit import model, Model
from lmfit.models import GaussianModel, SkewedGaussianModel, VoigtModel, ConstantModel, LinearModel, QuadraticModel, PolynomialModel
##### Data Tools #####
class DataTools :
def __init__(self) :
pass
def FileList(self,FolderPath,Filter) :
FileList = [f for f in listdir(FolderPath) if isfile(join(FolderPath, f))]
for i in range(len(Filter)):
FileList = [k for k in FileList if Filter[i] in k]
for i in range(len(FileList)):
FileList[i] = FileList[i].replace('.yaml','')
return FileList
def LoadBinnedData(self,DataFile,par) :
# Check file
f = h5py.File(par['FolderPath'] + '/' + DataFile, 'r')
if not 'BinnedData/xas_bins' in f :
raise Exception('Energy data missing')
if not 'BinnedData/delay_bins' in f :
raise Exception('Delay data missing')
if not 'BinnedData/XAS_2dmatrix' in f :
raise Exception('Intensity data missing')
if not 'BinnedData/XAS_2dmatrix_err' in f :
raise Exception('Error bar data missing')
# Load data
Energy = f['BinnedData/xas_bins'][...]
Delay = f['BinnedData/delay_bins'][...]
Signal = f['/BinnedData/XAS_2dmatrix'][...]
ErrorBars = f['/BinnedData/XAS_2dmatrix_err'][...]
f.close()
# Energy offset
Energy = Energy + par['xOffset']
# Create data frame
Data = df(data=np.transpose(Signal),columns=Delay)
Data.index = Energy
ErrorBars = df(data=np.transpose(ErrorBars),columns=Delay,index=Energy)
# Remove empty data sets
Data = Data.dropna(axis=1, how='all')
ErrorBars = ErrorBars.dropna(axis=1, how='all')
return Data, ErrorBars
def LoadHDF(self,Folder,File) :
Store = pd.HDFStore(Folder + '/' + File)
Data = {'File': File}
for key in Store.keys() :
Data[str.replace(key,'/','')] = Store.get(key)
Store.close()
return Data
def TrimData(self,Data,xRange) :
# Trim data
Mask = np.all([Data.index.values>min(xRange),Data.index.values<max(xRange)],axis=0)
Data = Data[Mask]
return Data
def SubtractBackground(self,Data,ErrorBars,Background,Background_ErrorBars,par,ShowPlot=True) :
Min = max(min(Data.index),min(Background.index))
Max = min(max(Data.index),max(Background.index))
Data = self.TrimData(Data,[Min,Max])
ErrorBars = self.TrimData(ErrorBars,[Min,Max])
Background = self.TrimData(Background,[Min,Max])
Background_ErrorBars = self.TrimData(Background_ErrorBars,[Min,Max])
if np.array_equal(Data.index,Background.index) :
Data = Data.subtract(Background.values)
print('Background Successfully subtracted from data')
ErrorBars = ErrorBars**2
ErrorBars = ErrorBars.add((Background_ErrorBars**2).values)
ErrorBars = ErrorBars**0.5
else :
print('Warning: Energy axes do not match')
print('Warning: Background subtraction cancelled')
if ShowPlot :
plt.errorbar(Background.index, Background.values, yerr=Background_ErrorBars.iloc[:,0], fmt='o', color='black')
plt.xlabel('Energy (eV)'), plt.ylabel('Intensity (au)')
plt.title('Background: '+par['Background'])
plt.show()
return Data, ErrorBars
##### Fit Tools #####
class FitTools :
def __init__(self,Data,ErrorBars,par,Name='') :
self.Data = Data
self.ErrorBars = ErrorBars
self.par = par
self.Name = Name
def SetModel(self) :
par = self.par
Data = self.Data
ModelString = list()
for Peak in par['Models'] :
ModelString.append((Peak,par['Models'][Peak]['model']))
for Model in ModelString :
try :
FitModel
except :
if Model[1] == 'Constant' :
FitModel = ConstantModel(prefix=Model[0]+'_')
if Model[1] == 'Linear' :
FitModel = LinearModel(prefix=Model[0]+'_')
if Model[1] == 'Gaussian' :
FitModel = GaussianModel(prefix=Model[0]+'_')
if Model[1] == 'SkewedGaussian' :
FitModel = SkewedGaussianModel(prefix=Model[0]+'_')
if Model[1] == 'Voigt' :
FitModel = VoigtModel(prefix=Model[0]+'_')
else :
if Model[1] == 'Constant' :
FitModel = FitModel + ConstantModel(prefix=Model[0]+'_')
if Model[1] == 'Linear' :
FitModel = FitModel + LinearModel(prefix=Model[0]+'_')
if Model[1] == 'Gaussian' :
FitModel = FitModel + GaussianModel(prefix=Model[0]+'_')
if Model[1] == 'SkewedGaussian' :
FitModel = FitModel + SkewedGaussianModel(prefix=Model[0]+'_')
if Model[1] == 'Voigt' :
FitModel = FitModel + VoigtModel(prefix=Model[0]+'_')
ModelParameters = FitModel.make_params()
FitsParameters = df(index=ModelParameters.keys(),columns=Data.columns.values)
self.FitModel = FitModel
self.ModelParameters = ModelParameters
self.FitsParameters = FitsParameters
def SetParameters(self, Value=None) :
par = self.par
ModelParameters = self.ModelParameters
FitsParameters = self.FitsParameters
ParameterList = ['intercept','offset','amplitude','center','sigma']
Parameters = {'Standard': par['Models']}
if 'Cases' in par and Value != None:
for Case in par['Cases'] :
if Value >= min(par['Cases'][Case]['zRange']) and Value <= max(par['Cases'][Case]['zRange']) :
Parameters[Case] = par['Cases'][Case]
for Dictionary in Parameters :
for Peak in Parameters[Dictionary] :
for Parameter in Parameters[Dictionary][Peak] :
if Parameter in ParameterList :
for Key in Parameters[Dictionary][Peak][Parameter] :
if Key != 'set' :
exec('ModelParameters["'+Peak+'_'+Parameter+'"].'+Key+'='+str(Parameters[Dictionary][Peak][Parameter][Key]))
else :
exec('ModelParameters["'+Peak+'_'+Parameter+'"].'+Key+str(Parameters[Dictionary][Peak][Parameter][Key]))
self.ModelParameters = ModelParameters
def Fit(self,**kwargs) :
for kwarg in kwargs :
if kwarg == 'fit_x':
fit_x = kwargs[kwarg]
if kwarg == 'NumberPoints':
NumberPoints = kwargs[kwarg]
dt = DataTools()
self.SetModel()
Data = self.Data
Name = self.Name
par = self.par
ModelParameters = self.ModelParameters
FitModel = self.FitModel
FitsParameters = self.FitsParameters
if 'xRange' in par :
Data = dt.TrimData(Data,[par['xRange'][0],par['xRange'][1]])
x = Data.index.values
try:
fit_x
except :
try :
NumberPoints
except :
fit_x = x
else :
fit_x = np.zeros((NumberPoints))
for i in range(NumberPoints) :
fit_x[i] = min(x) + i * (max(x) - min(x)) / (NumberPoints - 1)
Fits = df(index=fit_x,columns=Data.columns.values)
FitsResults = list()
FitsComponents = list()
for idx,Column in enumerate(Data) :
self.SetParameters(Value=Column)
y = Data[Column].values
FitResults = FitModel.fit(y, ModelParameters, x=x, nan_policy='omit')
fit_comps = FitResults.eval_components(FitResults.params, x=fit_x)
fit_y = FitResults.eval(x=fit_x)
ParameterNames = [i for i in FitResults.params.keys()]
for Parameter in (ParameterNames) :
FitsParameters[Column][Parameter] = FitResults.params[Parameter].value
Fits[Column] = fit_y
FitsResults.append(FitResults)
FitsComponents.append(fit_comps)
sys.stdout.write(("\rFitting %i out of "+str(Data.shape[1])) % (idx+1))
sys.stdout.flush()
self.Fits = Fits
self.FitsParameters = FitsParameters
self.FitsResults = FitsResults
self.FitsComponents = FitsComponents
def ShowFits(self,xLabel='Energy (eV)',yLabel='Intensity (au)') :
Data = self.Data
ErrorBars = self.ErrorBars
Fits = self.Fits
par = self.par
FitsParameters = self.FitsParameters
FitsComponents = self.FitsComponents
for idx,Column in enumerate(Data) :
plt.figure(figsize = [6,4])
plt.errorbar(Data.index, Data[Column], yerr=ErrorBars[Column],label='Data', fmt='o', color='black')
plt.plot(Fits.index, Fits[Column], 'r-', label='Fit')
for Component in FitsComponents[idx] :
if not isinstance(FitsComponents[idx][Component],float) :
plt.fill(Fits.index, FitsComponents[idx][Component], '--', label=Component[:-1], alpha=0.5)
plt.legend(frameon=False, loc='upper center', bbox_to_anchor=(1.2, 1), ncol=1)
plt.xlabel(xLabel), plt.ylabel(yLabel)
plt.title(str(Column))
plt.show()
Peaks = list()
for Parameter in FitsParameters.index :
Name = Parameter.split('_')[0]
if Name not in Peaks :
Peaks.append(Name)
string = ''
for Peak in Peaks :
string = string + Peak + ' | '
for Parameter in FitsParameters.index :
if Peak == Parameter.split('_')[0] :
string = string + Parameter.split('_')[1] + ': ' + str(round(FitsParameters[Column][Parameter],3))
string = string + ', '
string = string[:-2] + '\n'
print(string)
print(75*'_')<file_sep>import numpy as np
import scipy
import pandas as pd
from pandas import DataFrame as df
import yaml
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import seaborn as sns
import plotly.express as px
import ipywidgets as widgets
from ipywidgets import Button, Layout
from lmfit import model, Model
import re
import os
from os import listdir
from os.path import isfile, join, dirname
import sys
from IPython.display import clear_output
import AnalysisTools
from pylab import rc
##### Plotly settings #####
import plotly.graph_objects as go
import plotly.io as pio
pio.renderers.default = 'notebook+plotly_mimetype'
pio.templates.default = 'simple_white'
pio.templates[pio.templates.default].layout.update(dict(
title_y = 0.95,
title_x = 0.5,
title_xanchor = 'center',
title_yanchor = 'top',
legend_x = 0,
legend_y = 1,
legend_traceorder = "normal",
legend_bgcolor='rgba(0,0,0,0)',
margin=go.layout.Margin(
l=0, #left margin
r=0, #right margin
b=0, #bottom margin
t=50, #top margin
)
))
Folders = {}
Folders['Parameters'] = os.getcwd()+'/../Parameters'
Folders['Fits'] = os.getcwd()+'/../Fits'
Folders['Figures'] = os.getcwd()+'/../Figures'
Folders['Binned'] = os.getcwd()+'/../Binned/BT2'
class Fit :
def __init__(self) :
self.Folders = Folders
def LoadData(self,ParametersFile,DataFile,xRange=[-float('inf'),float('inf')]) :
self.DataFile = DataFile
with open(ParametersFile[0]+'/'+ParametersFile[1]+'.yaml', 'r') as stream:
par = yaml.safe_load(stream)
dt = AnalysisTools.DataTools()
Data, ErrorBars = dt.LoadBinnedData(DataFile,par)
##### Scale Data #####
if 'Scaling' in par :
if par['Scaling']['Type'] == 'Data' :
Data = Data * par['Scaling']['Factor']
ErrorBars = ErrorBars * par['Scaling']['Factor']
print('Scaling data by ' + str(par['Scaling']['Factor']))
##### Background Subtraction #####
if 'Background' in par :
BackgroundFile = par['Background']
string = DataFile.replace('.h5','')
string = string.split('_')[1:]
for segment in string :
if segment[0] == 'E' :
BackgroundFile += '_'+segment+'.h5'
if os.path.isfile(par['FolderPath']+'/'+BackgroundFile) :
Background, Background_ErrorBars = dt.LoadBinnedData(BackgroundFile,par)
Background = dt.TrimData(Background,xRange)
Background_ErrorBars = dt.TrimData(Background_ErrorBars,xRange)
if 'Scaling' in par and par['Scaling']['Type'] == 'Background' :
Background = Background * par['Scaling']['Factor']
Background_ErrorBars = Background_ErrorBars * par['Scaling']['Factor']
print('Scaling background by ' + str(par['Scaling']['Factor']))
Data, ErrorBars = dt.SubtractBackground(Data,ErrorBars,Background,Background_ErrorBars,par)
else:
print('Background file not found. Background subtraction canceled.')
self.ParametersFile = ParametersFile
self.DataFile = DataFile
self.par = par
self.Data = Data
self.ErrorBars = ErrorBars
def Fit(self,Region) :
Data = self.Data
ErrorBars = self.ErrorBars
par = self.par
DataFile = self.DataFile
dt = AnalysisTools.DataTools()
print(par['Description'])
Data = dt.TrimData(Data, par['Spectra'][Region]['xRange'])
ErrorBars = dt.TrimData(ErrorBars,par['Spectra'][Region]['xRange'])
##### Peak Assignments #####
PeakList = list()
AssignmentList = list()
for Peak in par['Spectra'][Region]['Models'] :
PeakList.append(Peak)
if 'assignment' in par['Spectra'][Region]['Models'][Peak] :
AssignmentList.append(par['Spectra'][Region]['Models'][Peak]['assignment'])
else :
AssignmentList.append(Peak)
FitsAssignments = df(AssignmentList,index=PeakList,columns=['Assignment'])
##### Fit Data #####
print('\nFitting Data...')
fit = AnalysisTools.FitTools(Data,ErrorBars,par['Spectra'][Region])
fit.Fit(NumberPoints=501)
fit.ShowFits()
Fits = fit.Fits
FitsParameters = fit.FitsParameters
##### Convert FitsComponents to DataFrame #####
FitsComponents = pd.DataFrame(fit.FitsComponents)
FitsComponents.index = Data.columns
for key in FitsComponents :
FitsComponents = FitsComponents.rename(columns={key:str.replace(key,'_','')})
print('\nDone fitting data')
##### Plot 2D Data & Fits #####
plt.figure(figsize = [16,6])
plt.subplot(1, 2, 1)
x = Data.index.values
y = Data.columns.values
z = np.transpose(Data.values)
plt.ylabel('Delay (fs)', fontsize=16)
plt.tick_params(axis = 'both', which = 'major', labelsize = 16)
plt.title(str.split(DataFile,".")[0]+' - Data', fontsize=16)
pcm = plt.pcolor(x, y, z, cmap='jet', shading='auto')
plt.subplot(1, 2, 2)
x = Fits.index.values
y = Fits.columns.values
z = np.transpose(Fits.values)
plt.xlabel('Wavenumber (cm$^-$$^1$)', fontsize=16)
plt.ylabel('Delay (fs)', fontsize=16)
plt.tick_params(axis = 'both', which = 'major', labelsize = 16)
plt.title(str.split(DataFile,".")[0]+' - Fits', fontsize=16)
pcm = plt.pcolor(x, y, z, cmap='jet', shading='auto')
plt.show()
##### Plot Trends #####
FitsParameters = FitsParameters.T
UniqueParameters = ('amplitude','center','sigma')
for uniqueParameter in UniqueParameters :
fig = go.Figure()
for parameter in FitsParameters :
if uniqueParameter in parameter :
Name = parameter.split('_')[0]
if 'assignment' in par['Spectra'][Region]['Models'][Name] :
Name = par['Spectra'][Region]['Models'][Name]['assignment']
fig.add_trace(go.Scatter(x=FitsParameters.index,y=FitsParameters[parameter],name=Name,mode='lines+markers'))
fig.update_layout(xaxis_title='Delay (fs)',yaxis_title=uniqueParameter,title=str.split(DataFile,".")[0],legend_title='',width=800,height=400)
fig.show()
##### Store Fits ####
self.Fits = Fits
self.FitsParameters = FitsParameters
self.FitsComponents = FitsComponents
self.FitsAssignments = FitsAssignments
self.FitsData = Data
self.FitsErrorBars = ErrorBars
##### GUI #####
def CopyData_Clicked(b) :
Data.to_clipboard()
CopyData = widgets.Button(description="Copy Data")
CopyData.on_click(CopyData_Clicked)
def CopyFits_Clicked(b) :
Fits.to_clipboard()
CopyFits = widgets.Button(description="Copy Fits")
CopyFits.on_click(CopyFits_Clicked)
def CopyParameters_Clicked(b) :
FitsParameters.to_clipboard()
CopyParameters = widgets.Button(description="Copy Parameters")
CopyParameters.on_click(CopyParameters_Clicked)
def Save2File_Clicked(b) :
os.makedirs(Folders['Fits'], exist_ok=True)
FitsFile = Folders['Fits'] +'/' + self.ParametersFile[1] + ' - ' + str.replace(self.DataFile,'.h5','') + ' - ' + self.Region.value + '.hdf'
Data.to_hdf(FitsFile,'Data',mode='w')
ErrorBars.to_hdf(FitsFile,'ErrorBars',mode='a')
Fits.to_hdf(FitsFile,'Fits',mode='a')
FitsParameters.to_hdf(FitsFile,'Fits_Parameters',mode='a')
FitsComponents.to_hdf(FitsFile,'Fits_Components',mode='a')
FitsAssignments.to_hdf(FitsFile,'Fits_Assignments',mode='a')
Save2File = widgets.Button(description="Save to File")
Save2File.on_click(Save2File_Clicked)
display(widgets.Box([CopyData,CopyFits,CopyParameters,Save2File]))
def UI(self) :
dt = AnalysisTools.DataTools()
out = widgets.Output()
##### Button Functions #####
def UpdateFiles_Clicked(b):
with open(Folders['Parameters']+'/'+self.ParametersFiles.value+'.yaml', 'r') as stream:
par = yaml.safe_load(stream)
self.DataFiles.options = dt.FileList(par['FolderPath'],[par['Runs']])
UpdateFiles = widgets.Button(description="Update",layout = Layout(width='10%'))
UpdateFiles.on_click(UpdateFiles_Clicked)
def FitData_Clicked(b):
with out :
clear_output(True)
self.LoadData([Folders['Parameters'],self.ParametersFiles.value],self.DataFiles.value)
self.Fit(self.Region.value)
FitData = widgets.Button(description="Fit",layout = Layout(width='10%'))
FitData.on_click(FitData_Clicked)
##### Widgets #####
self.ParametersFiles = widgets.Dropdown(
options=dt.FileList(Folders['Parameters'],['.yaml']),
description='Parameter File',
layout=Layout(width='70%'),
style = {'description_width': '150px'},
disabled=False,
)
self.Region = widgets.Dropdown(
options = ['Pi Star','Middle','Shape Resonance'],
description = 'Select Region',
layout = Layout(width='40%'),
style = {'description_width': '150px'},
disabled = False,
)
with open(Folders['Parameters']+'/'+self.ParametersFiles.value+'.yaml', 'r') as stream:
par = yaml.safe_load(stream)
self.DataFiles = widgets.Dropdown(
options=dt.FileList(par['FolderPath'],[par['Runs']]),
description='Data File',
layout=Layout(width='50%'),
style = {'description_width': '150px'},
disabled=False,
)
display(widgets.Box([self.ParametersFiles,UpdateFiles]))
display(self.DataFiles)
display(self.Region)
display(FitData)
display(out)
class Trends :
def __init__(self) :
self.Folders = Folders
def LoadData(self,ParametersFile,DataFile) :
dt = AnalysisTools.DataTools()
# Load Data
Data = dt.LoadHDF(DataFile[0],DataFile[1])
Data = Data['Fits_Parameters']
Data['Precursor 1'] = Data['Precursor10_amplitude'] + Data['Precursor11_amplitude']
Data['Precursor 2'] = Data['Precursor20_amplitude'] + Data['Precursor21_amplitude']
Data = Data.rename({'Precursor2_amplitude': 'Precursor 2', 'Adsorbed_amplitude': 'Adsorbed', 'Unknown_amplitude': 'Unknown'}, axis=1)
Data = Data.reindex(columns=['Adsorbed','Precursor 1','Precursor 2','Unknown'])
# Load Parameters
with open(ParametersFile[0]+'/'+ParametersFile[1]+'.yaml', 'r') as stream:
par = yaml.safe_load(stream)
self.Data = Data
self.DataFile = DataFile
self.par = par
def Fit(self) :
Data = self.Data
DataFile = self.DataFile
linewidth=2
fontsize = 20
def func(t,a,b,t0,sigma):
return a*scipy.special.erf((t-t0)/sigma)+a+b
FitsResults = list()
FitModel = Model(func)
FitParameters = FitModel.make_params()
FitParameters['b'].min = 0
FitParameters['t0'].min = 0
FitParameters['sigma'].min = 0
TempData = Data[Data.index<=max(self.par['Trends']['xRange'])]
TempData = TempData[TempData.index>=min(self.par['Trends']['xRange'])]
Parameters = self.par['Trends']['Fits']
Fits_TrendFits = df(index=np.linspace(min(TempData.index),max(TempData.index),101))
Fits_TrendParameters = df(index=['a','b','t0','sigma'])
sns.set_theme(style="ticks")
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot()
Fit = True
Normalize = False
for idx,column in enumerate(TempData.columns) :
if Normalize :
Min = min(TempData[column])
TempData[column] = TempData[column]-Min
Max = max(TempData[column])
TempData[column] = TempData[column]/Max
if column in Parameters :
if 'a' in Parameters[column] :
FitParameters['a'].value = Parameters[column]['a']
if 'b' in Parameters[column] :
FitParameters['b'].value = Parameters[column]['b']
if 't0' in Parameters[column] :
FitParameters['t0'].value = Parameters[column]['t0']
if 'sigma' in Parameters[column] :
FitParameters['sigma'].value = Parameters[column]['sigma']
y = TempData[column].values.astype('float64')
t = TempData.index.values
FitResults = FitModel.fit(y, FitParameters, t=t)
FitsResults.append(FitResults)
fit_y = FitResults.eval(t=Fits_TrendFits.index)
Fits_TrendFits[column] = fit_y
Fits_TrendParameters[column] = np.array((FitResults.params['a'].value,FitResults.params['b'].value,FitResults.params['t0'].value,FitResults.params['sigma'].value))
plt.scatter(t,y,label=column)
plt.plot(Fits_TrendFits.index,fit_y)
ax.tick_params(axis = 'both', which = 'major', labelsize = fontsize)
plt.xlabel('Time (fs)',fontsize=fontsize)
plt.ylabel('Amplitude *au()',fontsize=fontsize)
plt.legend(frameon=False, fontsize=fontsize, bbox_to_anchor=(1,0.8), loc="upper left")
plt.show()
display(Fits_TrendParameters)
def FitsAppend2File_Clicked(b) :
Data.to_hdf(DataFile[0] + '/' + DataFile[1],'Fits_TrendData',mode='a')
Fits_TrendFits.to_hdf(DataFile[0] + '/' + DataFile[1],'Fits_TrendFits',mode='a')
Fits_TrendParameters.to_hdf(DataFile[0] + '/' + DataFile[1],'Fits_TrendParameters',mode='a')
FitsAppend2File = widgets.Button(description="Append to File")
FitsAppend2File.on_click(FitsAppend2File_Clicked)
display(FitsAppend2File)
def UI(self) :
dt = AnalysisTools.DataTools()
out = widgets.Output()
##### Button Functions #####
def UpdateFiles_Clicked(b):
with open(Folders['Parameters']+'/'+self.ParametersFiles.value+'.yaml', 'r') as stream:
par = yaml.safe_load(stream)
self.DataFiles.options = dt.FileList(Folders['Fits'],[par['Runs']])
UpdateFiles = widgets.Button(description="Update",layout = Layout(width='10%'))
UpdateFiles.on_click(UpdateFiles_Clicked)
def FitData_Clicked(b):
with out :
clear_output(True)
self.LoadData([Folders['Parameters'],self.ParametersFiles.value],[Folders['Fits'],self.DataFiles.value])
self.Fit()
FitData = widgets.Button(description="Fit",layout = Layout(width='10%'))
FitData.on_click(FitData_Clicked)
##### Widgets #####
self.ParametersFiles = widgets.Dropdown(
options=dt.FileList(Folders['Parameters'],['.yaml']),
description='Parameter File',
layout=Layout(width='70%'),
style = {'description_width': '150px'},
disabled=False,
)
with open(Folders['Parameters']+'/'+self.ParametersFiles.value+'.yaml', 'r') as stream:
par = yaml.safe_load(stream)
self.DataFiles = widgets.Dropdown(
options=dt.FileList(Folders['Fits'],[par['Runs']]),
description='Data File',
layout=Layout(width='50%'),
style = {'description_width': '150px'},
disabled=False,
)
display(widgets.Box([self.ParametersFiles,UpdateFiles]))
display(self.DataFiles)
display(FitData)
display(out)
class Angles :
def __init__(self) :
Folders['Parameters'] = os.getcwd()+'/../Parameters'
Folders['Fits'] = os.getcwd()+'/../Fits'
Folders['Figures'] = os.getcwd()+'/../Figures'
Folders['Binned'] = os.getcwd()+'/../Binned/BT2'
def LoadData(self,HorFile,VerFile) :
dt = AnalysisTools.DataTools()
# Load Data
HorData = dt.LoadHDF(HorFile[0],HorFile[1])
VerData = dt.LoadHDF(VerFile[0],VerFile[1])
self.HorData = HorData
self.VerData = VerData
def Calculate(self) :
HorData = self.HorData
VerData = self.VerData
# Plot formatting
symbols = 5*['.','+','x','^','*','_','o']
linestyle = 5*['solid','dotted','dashed','dashdot',(0,(3,3,1,3,1,3)),(0,(1,5)),(0,(5,10))]
colors = 5*['black','blue','red','green','orange','purple','gray']
markersize = 150
linewidth=2
fontsize = 16
# Amplitudes
HorFitsPars = HorData['Fits_Parameters']
HorAmpCols = [col for col in HorFitsPars.columns if 'amp' in col]
VerFitsPars = VerData['Fits_Parameters']
VerAmpCols = [col for col in VerFitsPars.columns if 'amp' in col]
CommonCols = [x for x in VerAmpCols if x in HorAmpCols]
HorAmp = HorFitsPars[CommonCols]
VerAmp = VerFitsPars[CommonCols]
CommonDelays = [x for x in VerAmp.index if x in HorAmp.index]
HorAmp = HorAmp.filter(items=CommonDelays,axis=0)
VerAmp = VerAmp.filter(items=CommonDelays,axis=0)
# Plot horizontal amplitudes
plt.figure(figsize=(10, 5))
ax = plt.subplot()
for column in HorAmp :
plt.plot(HorAmp.index,HorAmp[column],marker='o')
plt.xlabel('Time (fs)',fontsize=fontsize)
plt.ylabel('Intensity (au)',fontsize=fontsize)
ax.tick_params(axis = 'both', which = 'major', labelsize = fontsize)
plt.title('Horizontal',fontsize=fontsize+4)
plt.show()
# Plot vertical amplitudes
plt.figure(figsize=(10, 5))
ax = plt.subplot()
for column in VerAmp :
plt.plot(VerAmp.index,VerAmp[column],marker='o')
plt.xlabel('Time (fs)',fontsize=fontsize)
plt.ylabel('Intensity (au)',fontsize=fontsize)
ax.tick_params(axis = 'both', which = 'major', labelsize = fontsize)
plt.title('Vertical',fontsize=fontsize+4)
plt.show()
# Define functions
pi = np.pi
def cos(theta) :
return np.cos(theta/180*pi)
def sin(theta) :
return np.sin(theta/180*pi)
def OutOfPlane(theta,phi,gamma) :
I = 1 - cos(theta)**2 * cos(gamma)**2 - sin(theta)**2 * sin(gamma)**2 * cos(phi)**2 - 2*sin(gamma)*cos(gamma)*sin(theta)*cos(theta)*cos(phi)
return I
def InPlane(theta,phi,gamma) :
I = 1 - sin(gamma)**2 * sin(phi)**2
return I
def I(theta, gamma) :
I_OP = OutOfPlane(theta,45,gamma)
I_IP = InPlane(theta,45,gamma)
return gamma, I_OP, I_IP
# Simplified angle function: same as new analysis when x-ray angle (theta) set to zero
def AngleFunction(theta) :
return (np.sin((theta)/180*np.pi))**2 / (0.5+((np.cos((theta)/180*np.pi))**2/2))
# Calculate and plot ratio versus angles
Gamma = np.linspace(0,90,9001)
x, OP, IP = I(3,Gamma)
RatiosRef = OP/IP
fontsize = 20
sns.set_theme(style="ticks")
fig, ax = plt.subplots(figsize=(10,5))
sns.lineplot(x=x,y=OP, color='black', label='$I_{OP}$')
sns.lineplot(x=x,y=IP, color='red', label='$I_{IP}$')
sns.lineplot(x=x,y=RatiosRef, color='blue', label='$\\frac{I_{OP}}{I_{IP}}$')
ax.lines[0].set_linestyle("dashed")
ax.lines[1].set_linestyle("dotted")
ax.set_xlabel('CO-Surface Angle (Degrees)',fontsize=fontsize)
ax.set_ylabel('Intensity (norm)',fontsize=fontsize)
ax.tick_params(axis = 'both', which = 'major', labelsize = fontsize)
ax.tick_params(axis = 'both', which = 'minor', labelsize = fontsize)
plt.legend(frameon=False, fontsize=fontsize)
plt.show()
# Calculate ratios
Ratios = VerAmp/HorAmp.replace({ 0 : np.nan })
Ratios = VerAmp/HorAmp.replace({ 0 : np.nan })
Ratios['Precursor 1'] = Ratios['Precursor10_amplitude'] + Ratios['Precursor11_amplitude']
Ratios['Precursor 2'] = Ratios['Precursor20_amplitude'] + Ratios['Precursor21_amplitude']
Ratios = Ratios.rename({'Precursor2_amplitude': 'Precursor 2', 'Adsorbed_amplitude': 'Adsorbed'}, axis=1)
Ratios = Ratios.reindex(columns=['Adsorbed','Precursor 1','Precursor 2'])
# Calculate angles from surface normal
Angles = pd.DataFrame(index=Ratios.index,columns=Ratios.columns)
for Energy in Ratios :
for Delay in Ratios[Energy].index.values :
index = (np.abs(RatiosRef - Ratios[Energy].loc[Delay])).argmin()
Angles[Energy].loc[Delay] = Gamma[index]
# Plot function
def Data2Plot(Data) :
for idx,column in enumerate(Data) :
label = column
x = Data.index
y = Data[column].values.astype('float64')
sns.scatterplot(x=x,y=y,label=label,marker=symbols[idx],color=cm.Set1(idx),s=markersize)
sns.lineplot(x=x,y=y,label='_',marker=symbols[idx],color=cm.Set1(idx),linewidth=linewidth)
idx += 1
# Ratio plot
sns.set_theme(style="ticks")
fig = plt.figure(figsize=(10, 5))
rc('axes', linewidth=linewidth)
ax = fig.add_subplot(1, 1, 1)
Data2Plot(Ratios)
ax.tick_params(axis='both',which='both',labelsize = fontsize)
plt.ylabel('$I_{OP}/I_{IP}$',fontsize=fontsize)
plt.xlabel('Delay (fs)',fontsize=fontsize)
plt.title('Ratios',fontsize=fontsize+4)
plt.legend(frameon=False, fontsize=fontsize, bbox_to_anchor=(1,0.65), loc="upper left")
plt.show()
# Angles plot
sns.set_theme(style="ticks")
fig = plt.figure(figsize=(10, 5))
rc('axes', linewidth=linewidth)
ax = fig.add_subplot(1, 1, 1)
Data2Plot(Angles)
ax.tick_params(axis='both',which='both',labelsize = fontsize)
plt.ylabel('Angle (Degrees)',fontsize=fontsize)
plt.xlabel('Delay (fs)',fontsize=fontsize)
plt.title('Angles',fontsize=fontsize+4)
plt.legend(frameon=False, fontsize=fontsize, bbox_to_anchor=(1,0.65), loc="upper left")
plt.show()
# Interactive angles plot
fig = px.scatter(Angles)
fig.update_traces(mode='lines+markers')
fig.update_layout(xaxis_title='Delay (fs)',yaxis_title='Angle (Degrees)',legend_title='',height=500)
fig.show()
self.HorAmp = HorAmp
self.VerAmp = VerAmp
self.Ratios = Ratios
self.Angles = Angles
Filename = widgets.Text(
value='Angles',
placeholder='Filename',
description='Filename:',
disabled=False
)
def Angles2File_Clicked(b) :
os.makedirs(Folders['Fits'], exist_ok=True)
Angles.to_hdf(Folders['Fits']+'/'+Filename.value+'.hdf','Angles')
Angles2File = widgets.Button(description="Save to File")
Angles2File.on_click(Angles2File_Clicked)
display(widgets.Box([Angles2File,Filename]))
def UI(self) :
dt = AnalysisTools.DataTools()
out = widgets.Output()
##### Button Functions #####
def UpdateFiles_Clicked(b):
self.HorFiles.options = dt.FileList(Folders['Fits'],['Hor'])
self.VerFiles.options = dt.FileList(Folders['Fits'],['Ver'])
UpdateFiles = widgets.Button(description="Update",layout = Layout(width='10%'))
UpdateFiles.on_click(UpdateFiles_Clicked)
def Calculate_Clicked(b):
with out :
clear_output(True)
self.LoadData([Folders['Fits'],self.HorFiles.value],[Folders['Fits'],self.VerFiles.value])
self.Calculate()
Calculate = widgets.Button(description="Calculate",layout = Layout(width='10%'))
Calculate.on_click(Calculate_Clicked)
##### Widgets #####
self.ParametersFiles = widgets.Dropdown(
options=dt.FileList(Folders['Parameters'],['.yaml']),
description='Parameter File',
layout=Layout(width='70%'),
style = {'description_width': '150px'},
disabled=False,
)
with open(Folders['Parameters']+'/'+self.ParametersFiles.value+'.yaml', 'r') as stream:
par = yaml.safe_load(stream)
self.HorFiles = widgets.Dropdown(
options=dt.FileList(Folders['Fits'],['Hor']),
description='Horizontal',
layout=Layout(width='50%'),
style = {'description_width': '150px'},
disabled=False,
)
self.VerFiles = widgets.Dropdown(
options=dt.FileList(Folders['Fits'],['Ver']),
description='Vertical',
layout=Layout(width='50%'),
style = {'description_width': '150px'},
disabled=False,
)
display(widgets.Box([self.HorFiles,UpdateFiles]))
display(self.VerFiles)
display(Calculate)
display(out) | d86ddb12670afdd353c1c3effcf459c258cbf815 | [
"Python"
]
| 2 | Python | CUCatLab/FermiAnalysis_2017 | d7b812509e4ce8f4f459742ab837a582a2e312a7 | 0bc82a837c0afdddc14d82b6b6a4e2c351f140b4 |
refs/heads/master | <repo_name>GSCrawley/contractor<file_sep>/tests.py
# tests.py
from unittest import TestCase, main as unittest_main, mock
from bson.objectid import ObjectId
from app import app
sample_guitar_id = ObjectId('5da005918edd63f14c355675')
sample_guitar = {
'title': 'Gretsch White Falcon',
'description': 'electric',
'price': '$850',
'jpgs':
'https://www.dawsons.co.uk/media/catalog/product/cache/1/image/1200x/6b9ffbf72458f4fd2d3cb995d92e8889/g/i/gibson_les_paul_classic_electric_guitar_-_heritage_cherry_sunburst_-_front.jpg',
}
sample_form_data = {
'title': sample_guitar['title'],
'description': sample_guitar['description'],
'price': sample_guitar['price'],
'jpgs': '\n'.join(sample_guitar['jpgs'])
}
class contractorTests(TestCase):
"""Flask tests."""
def setUp(self):
"""Stuff to do before every test."""
# Get the Flask test client
self.client = app.test_client()
# Show Flask errors that happen during tests
app.config['TESTING'] = True
def test_index(self):
"""Test the contractor homepage."""
result = self.client.get('/')
self.assertEqual(result.status, '200 OK')
self.assertIn(b'guitar', result.data)
def test_new(self):
"""Test the new creation page."""
result = self.client.get('/guitars/new')
self.assertEqual(result.status, '200 OK')
self.assertIn(b'New Guitar', result.data)
@mock.patch('pymongo.collection.Collection.update_one')
def test_edit_guitar(self, mock_update):
"""Test editing a single guitar entry."""
mock_update.return_value = sample_guitar
result = self.client.get(f'/guitars/{sample_guitar_id}')
self.assertEqual(result.status, '200 OK')
self.assertIn(b'Edit Guitar', result.data)
@mock.patch('pymongo.collection.Collection.delete_one')
def test_delete_guitar(self, mock_delete):
form_data = {'_method': 'DELETE'}
result = self.client.post(f'/guitars/{sample_guitar_id}/delete', data=form_data)
self.assertEqual(result.status, '302 FOUND')
mock_delete.assert_called_with({'_id': sample_guitar_id})
if __name__ == '__main__':
unittest_main()
<file_sep>/app.py
import os
from pymongo import MongoClient
from bson.objectid import ObjectId
from flask import Flask, render_template, request, redirect, url_for
# from flask_session import Session
# import json
host = os.environ.get('MONGODB_URI', 'mongodb://127.0.0.1:27017/Contractor')
client = MongoClient(host=f'{host}?retryWrites=false')
db = client.get_default_database()
guitars = db.guitars
comments = db.comments
# cart_items = db.cart_items
app = Flask(__name__)
@app.route('/')
def guitars_index():
"""Show all guitars."""
return render_template('guitars_index.html', guitars=guitars.find())
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/guitars/new')
def guitars_new():
"""Create a custom guitar store."""
return render_template('guitars_new.html', guitar={}, title='Discount Guitars')
@app.route('/guitars', methods=['POST'])
def guitars_submit():
guitar = {
'title': request.form.get('title'),
'description': request.form.get('description'),
'price': request.form.get('price'),
'jpgs': request.form.get('jpgs')
}
guitars.insert_one(guitar)
return redirect(url_for('guitars_index'))
@app.route('/guitars/<guitar_id>/edit', methods=['POST'])
def guitars_edit(guitar_id):
"""Show the edit form for a guitar."""
guitar = guitars.find_one({'_id': ObjectId(guitar_id)})
return render_template('guitars_edit.html', guitar=guitar, title='Edit guitar')
@app.route('/guitars/<guitar_id>/save_edit', methods=['POST'])
def save_edit(guitar_id):
"""Update New Guitar"""
guitar = {
'title': request.form.get('title'),
'description': request.form.get('description'),
'price': request.form.get('price'),
'jpgs': request.form.get('jpgs')
}
guitars.update_one({'_id': ObjectId(guitar_id)},{"$set":guitar})
return redirect(url_for('guitars_index'))
@app.route('/guitars/<guitar_id>/delete', methods=['POST'])
def guitars_delete(guitar_id):
"""Delete one guitar."""
guitars.delete_one({'_id': ObjectId(guitar_id)})
return redirect(url_for('guitars_index'))
@app.route('/acoustic_guitars/show')
def acoustic_guitars():
"""Display Acoustic Guitars"""
return render_template('acoustic_guitars.html')
@app.route('/electric_guitars/show')
def electric_guitars():
"""Display Electric Guitars"""
return render_template('electric_guitars.html')
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=os.environ.get('PORT', 5000))
<file_sep>/templates/electric_guitars.html
{% extends 'base.html' %}
{% block content %}
<p>
<title> Electric Guitars </title>
</p>
<p>
<h1> Gibson SG Standard '61 Maestro Vibrola - Vintage Cherry - $1100 </h1>
<h2> Solidbody Electric Guitar with Mahogany Body and Neck, Rosewood Fretboard,
2 Humbucking Pickups, and Vibrola Tailpiece - Vintage Cherry </h2>
<img src = https://media.sweetwater.com/api/i/f-webp__q-82__ha-902157bc5494490e__hmac-85ee1fd357633919c0aa59efc6327e96bc782deb/images/guitars/SG61VVENH/124890022/124890022-body-large.jpg />
</p>
<p>
<h1> Fender Sandblasted Stratocaster - $950 </h1>
<h2> Solidbody Electric Guitar with Ash Body, Maple Neck, Rosewood Fingerboard,
and 3 Single-coil Pickups - 3-tone Sunburst </h2>
<img src = https://media.sweetwater.com/api/i/f-webp__q-82__ha-f921840fa3e808ae__hmac-da21509cfa27a1be5b2aa33187566dab48519bbb/images/guitars/StratSBR3TSB/US19083589/US19083589-body-large.jpg />
</p>
<p>
<h1> Epiphone Les Paul Standard Plustop Pro - Heritage Cherry Sunburst - $875 </h1>
<h2> Solidbody Electric Guitar with Mahogany Body, Flame Maple Veneer Top,
<NAME>, Pau Ferro Fingerboard, and 2 Humbucking Pickups - Heritage Cherry </h1>
<img src = https://media.sweetwater.com/api/i/f-webp__q-82__ha-820e9c0ba04473a9__hmac-d39b493672a44871c0b44f3845440f83cb55f618/images/guitars/ENLPHSNH/19011519411/19011519411-body-large.jpg />
</p>
<!-- <form action="/checkout_cart" method="POST">
<button class='btn btn-primary' type='submit'>Add To Cart</button>
<input type = "hidden" name="make_model" value="Epiphone Les Paul">
<input type = "hidden" name="type" value="Electric">
<input type = "hidden" name="cost" value="875">
</form> -->
{% endblock %}
<file_sep>/README.md
# contractor
# The Contractor project is a very rudimentary example of a website built using the Pymongo database and Jinja 2 html templates. It's got full CRUD functionality in that the user can Add an item, View that item, Edit that item, and Delete that item.
#All tests work except edit_guitar. keep getting a 404 error no matter what i do.
| d794e1da181a6b32d12cf0b9849a2feca7d35902 | [
"Markdown",
"Python",
"HTML"
]
| 4 | Python | GSCrawley/contractor | 8d057fdaf88032ae1432123ed2a1c78707cafb4b | a14491b3b94be0a929c9af7d2b3661eada6672a6 |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using veriT;
namespace OTEL254
{
public partial class profil : Form
{
public profil()
{
InitializeComponent();
}
private void profil_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Hide();
programAyarlari.fmain.Show();
}
private void profil_Load(object sender, EventArgs e)
{
programAyarlari.formBasligi(this, tSAciklama);// Form başlığını yazdırdık.
}
private void bDuzenle_Click(object sender, EventArgs e)
{
if (tEskiSifre.Text == "" && tYeniSifre.Text != "") tYeniSifre.Text = "";
if (tEskiSifre.Text != "" && tYeniSifre.Text == "") tEskiSifre.Text = "";
if (tEskiSifre.Text != "" && tYeniSifre.Text != "") // Eski şifre ile yeni şifre doluysa kontrol edilecek
if (tEskiSifre.Text != programAyarlari.kSifre) programAyarlari.hataVer("Hata", "Eski şifrenizi yanlış girdiniz.\nLütfen kontrol edip tekrar deneyiniz.");
else { islemler.varsaKosulluVeriGuncelle("KULLANICILAR", "K_KADI = '" + tKAdi.Text + "',K_SIFRE = '" + tYeniSifre.Text + "',K_ADI_SOYADI = '" + tAdiSoyadi.Text + "',K_DOGUM_TARIHI = '" + dTpDogumTarihi.Text + "',K_TEL = '" + tTel.Text + "',K_ADRES = '" + tAdres.Text + "',K_KISISEL_BILGILER = '" + tKisiselBilgiler.Text + "',K_RESIM = '" + pResim.ImageLocation.ToString() + "'", "K_TC = '" + lTC.Text + "'"); } // eski şifreyi doğru yazdıysa yeni şifre aktif olacak
else
{ // Eğer telefon numarasının başına sıfır yazıldıysa hata versin.
if (tTel.Text.Substring(0, 1) == "0") { programAyarlari.hataVer("Hata", "Lütfen telefon numarasını başında sıfır olmadan yazınız.\nÖrnek : 5123457890"); }
else islemler.varsaKosulluVeriGuncelle("KULLANICILAR", "K_KADI = '" + tKAdi.Text + "',K_ADI_SOYADI = '" + tAdiSoyadi.Text + "',K_DOGUM_TARIHI = '" + dTpDogumTarihi.Text + "',K_TEL = '" + tTel.Text + "',K_ADRES = '" + tAdres.Text + "',K_KISISEL_BILGILER = '" + tKisiselBilgiler.Text + "',K_RESIM = '" + pResim.ImageLocation.ToString() + "'", "K_TC = '" + lTC.Text + "'");
}
programAyarlari.kTC = programAyarlari.fprofil.lTC.Text;
programAyarlari.kAdiSoyadi = programAyarlari.fprofil.tAdiSoyadi.Text;
programAyarlari.kDogumTarihi = programAyarlari.fprofil.dTpDogumTarihi.Text;
programAyarlari.kTel = programAyarlari.fprofil.tTel.Text;
programAyarlari.kAdres = programAyarlari.fprofil.tAdres.Text;
programAyarlari.kKisiselBilgiler = programAyarlari.fprofil.tKisiselBilgiler.Text;
programAyarlari.kResim = programAyarlari.fprofil.pResim.ImageLocation;
tYeniSifre.Text = tEskiSifre.Text = "";
}
string resimPath = ""; // Resim yolu değişkenimizi tanımladık.
private void bResimSec_Click(object sender, EventArgs e)
{
// p.ImageLocation == @"resimler/default.png";
// p.ImageLocation = veritabani.dr["film_resmi"].ToString(); // Ve picturebox a veritabanında ki film_in resmini ekranda gösterttik.
ofd.Title = "Resim Aç";
ofd.Filter = "Jpeg Dosyası (*.jpg)|*.jpg|Gif Dosyası (*.gif)|*.gif|Png Dosyası (*.png)|*.png|Tif Dosyası (*.tif)|*.tif";
if (ofd.ShowDialog() == DialogResult.OK)
{
pResim.Image = Image.FromFile(ofd.FileName);
resimPath = ofd.FileName.ToString();
}
}
private void tTel_KeyPress(object sender, KeyPressEventArgs e)
{
// Düzenlenecek telefon girilirken silme tuşu ve digit karakterler kullanılacak diğerleri kullanılmayacak.
if (char.IsLetter(e.KeyChar)) e.Handled = true; // Bazı özel karakterler girilmesini engelledik.
else if (e.KeyChar == ' ' || e.KeyChar == '+' || e.KeyChar == '-' || e.KeyChar == '*' || e.KeyChar == '/' || e.KeyChar == '.' || e.KeyChar == ',' || e.KeyChar == '?' || e.KeyChar == '-' || e.KeyChar == '_' || e.KeyChar == '^' || e.KeyChar == '=' || e.KeyChar == '|') e.Handled = true; // Ve bu karakterleride biz engelledik.
else e.Handled = false;
}
private void tAdiSoyadi_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar)) e.Handled = true;
else e.Handled = false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using veriT;
namespace OTEL254
{
public partial class main : Form
{
public main()
{
InitializeComponent();
}
private void main_Load(object sender, EventArgs e)
{
programAyarlari.formBasligi(this, tSAciklama);// Form başlığını yazdırdık.
}
private void main_FormClosing(object sender, FormClosingEventArgs e)
{
this.Dispose();
Application.ExitThread();
}
PictureBox p;
void miniFormislemleri(string pName,Color renk,string olay, Form miniForm)
{
if (p.Name == pName)
{
if (olay == "pMouseMove") { p.BackColor = renk; miniForm.Location = new Point(MousePosition.X + 20, MousePosition.Y); }
else if (olay == "pMouseLeave") { p.BackColor = renk; miniForm.Hide(); }
else if (olay == "pHover" || olay == "pClick") miniForm.Show();
}
}
private void pMouseMove(object sender, MouseEventArgs e)
{
p = sender as PictureBox;
miniFormislemleri("pOda", Color.SeaGreen, "pMouseMove", programAyarlari.fminiOda);
miniFormislemleri("pRezervasyon", Color.Orange, "pMouseMove", programAyarlari.fminiRezervasyon);
miniFormislemleri("pMusteri", Color.MediumVioletRed, "pMouseMove", programAyarlari.fminiMusteri);
miniFormislemleri("pKayitlar", Color.CadetBlue, "pMouseMove", programAyarlari.fminiKayitlar);
miniFormislemleri("pTel", Color.Goldenrod, "pMouseMove", programAyarlari.fminiTel);
miniFormislemleri("pProgramHk", Color.Firebrick, "pMouseMove", programAyarlari.fminiProgramHK);
}
private void pMouseLeave(object sender, EventArgs e)
{
miniFormislemleri("pOda", Color.DarkGreen, "pMouseLeave", programAyarlari.fminiOda);
miniFormislemleri("pRezervasyon", Color.DarkOrange, "pMouseLeave", programAyarlari.fminiRezervasyon);
miniFormislemleri("pMusteri", Color.DarkMagenta, "pMouseLeave", programAyarlari.fminiMusteri);
miniFormislemleri("pKayitlar", Color.SteelBlue, "pMouseLeave", programAyarlari.fminiKayitlar);
miniFormislemleri("pTel", Color.DarkGoldenrod, "pMouseLeave", programAyarlari.fminiTel);
miniFormislemleri("pProgramHk", Color.DarkRed, "pMouseLeave", programAyarlari.fminiProgramHK);
}
private void pHover(object sender, EventArgs e)
{
miniFormislemleri("pOda", Color.SeaGreen, "pHover", programAyarlari.fminiOda);
if (p.Name == "pOda") programAyarlari.miniOdaDegerGetir();
miniFormislemleri("pRezervasyon", Color.DarkOrange, "pHover", programAyarlari.fminiRezervasyon);
miniFormislemleri("pMusteri", Color.DarkMagenta, "pHover", programAyarlari.fminiMusteri);
if (p.Name == "pMusteri")
programAyarlari.fminiMusteri.lMusteriSayisi.Text = (programAyarlari.musteriSayisi).ToString();
miniFormislemleri("pKayitlar", Color.SteelBlue, "pHover", programAyarlari.fminiKayitlar);
miniFormislemleri("pTel", Color.DarkGoldenrod, "pHover", programAyarlari.fminiTel);
miniFormislemleri("pProgramHk", Color.DarkRed, "pHover", programAyarlari.fminiProgramHK);
}
private void pClick(object sender, EventArgs e)
{
miniFormislemleri("pOda", Color.SeaGreen, "pClick", programAyarlari.fodalar);
if (p.Name == "pOda") { programAyarlari.secilenOda = ""; programAyarlari.fodalar.lSecilenOda.Text = "Son seçilen oda : "; }
miniFormislemleri("pRezervasyon", Color.DarkOrange, "pClick", programAyarlari.frezervasyonlar);
if (p.Name == "pRezervasyon")
{
islemler.kosulsuzVeriGetir("Select O_NU from ODA");
while (degiskenler.oku.Read())
{ programAyarlari.frezervasyonlar.cOda.Items.Add(degiskenler.oku["O_NU"].ToString()); }
degiskenler.baglan.Close();
programAyarlari.frezervasyonlar.cOda.SelectedIndex = 0;
// REZERVASYON KODLARI BAŞLANGIÇ
programAyarlari.tabloDoldur("REZERVASYON", programAyarlari.frezervasyonlar.dGvTumRezervasyon);
islemler.bagKontrol(); // Bağlantı kontrolü
programAyarlari.ds3.Clear(); // dataset temizle
degiskenler.adaptor = new OleDbDataAdapter("Select * from REZERVASYON where R_BASLANGIC_TARIHI=@rBaslangic", degiskenler.baglan);// Sorguda ki tablo verilerini koşul varsa getir yoksa koşul boşsa tüm veriler.
degiskenler.adaptor.SelectCommand.Parameters.Add("@rBaslangic", DateTime.Now.ToShortDateString());
degiskenler.adaptor.Fill(programAyarlari.ds3, "REZERVASYON"); // dataseti tabloadına göre doldur
programAyarlari.frezervasyonlar.dGvRezervasyonuOlanKisiler.DataSource = programAyarlari.ds3.Tables["REZERVASYON"];
degiskenler.baglan.Close();
programAyarlari.frezervasyonlar.dGvRezervasyonuOlanKisiler.ClearSelection();
programAyarlari.tabloDoldur("REZERVASYON where R_O_NU =" + programAyarlari.frezervasyonlar.cOda.Text, programAyarlari.frezervasyonlar.dGvSecilenOdaRezervasyonlari);
dGvisimleri(programAyarlari.frezervasyonlar.dGvRezervasyonuOlanKisiler);
dGvisimleri(programAyarlari.frezervasyonlar.dGvSecilenOdaRezervasyonlari);
dGvisimleri(programAyarlari.frezervasyonlar.dGvTumRezervasyon);
// REZERVASYON KODLARI BİTTİ
}
miniFormislemleri("pMusteri", Color.DarkMagenta, "pClick", programAyarlari.fmusteriler);
if (p.Name == "pMusteri") programAyarlari.fmusteriler.dGvMusteri.DataSource = degiskenler.ds.Tables["MUSTERI"];
miniFormislemleri("pKayitlar", Color.SteelBlue, "pClick", programAyarlari.fkayitlar);
if (p.Name == "pKayitlar")
{
programAyarlari.tabloDoldur("GIRIS_RAPOR", programAyarlari.fkayitlar.dGvGirisK);
programAyarlari.tabloDoldur("CIKIS_RAPOR", programAyarlari.fkayitlar.dGvCikisK);
programAyarlari.fkayitlar.dGvGirisK.Columns[0].HeaderText = "Giriş tarihi";
programAyarlari.fkayitlar.dGvGirisK.Columns[1].HeaderText = "TC Kimlik";
programAyarlari.fkayitlar.dGvGirisK.Columns[2].HeaderText = "Oda Numarası";
programAyarlari.fkayitlar.dGvGirisK.Columns[3].HeaderText = "Başlangıç tarihi";
programAyarlari.fkayitlar.dGvCikisK.Columns[0].HeaderText = "Çıkış tarihi";
programAyarlari.fkayitlar.dGvCikisK.Columns[1].HeaderText = "TC Kimlik";
programAyarlari.fkayitlar.dGvCikisK.Columns[2].HeaderText = "Oda Numarası";
programAyarlari.fkayitlar.dGvCikisK.Columns[3].HeaderText = "Toplam tutarı";
}
miniFormislemleri("pTel", Color.DarkGoldenrod, "pClick", programAyarlari.ftelefonlar);
if (p.Name == "pTel") programAyarlari.musteriGetir("TELEFON_NU", programAyarlari.ftelefonlar.dGvTelefon, "");
miniFormislemleri("pProgramHk", Color.DarkRed, "pClick", programAyarlari.fprogramHK);
this.Hide();
}
void dGvisimleri(DataGridView d)
{
d.Columns[0].HeaderText = "Başlangıç tarihi";
d.Columns[1].HeaderText = "Oda Numarası";
d.Columns[2].HeaderText = "Müşteri TC'si";
d.Columns[3].HeaderText = "Bitiş tarihi";
d.ClearSelection();
}
private void tSCikis_Click(object sender, EventArgs e) // Profilin orda çıkışa tıklanırsa
{
this.Hide();
programAyarlari.fgiris.Show();
}
private void tSProfil_Click(object sender, EventArgs e)
{
programAyarlari.fprofil.lTC.Text = programAyarlari.kTC;
programAyarlari.fprofil.tAdiSoyadi.Text = programAyarlari.kAdiSoyadi;
programAyarlari.fprofil.dTpDogumTarihi.Text = programAyarlari.kDogumTarihi;
programAyarlari.fprofil.tTel.Text = programAyarlari.kTel;
programAyarlari.fprofil.tAdres.Text = programAyarlari.kAdres;
programAyarlari.fprofil.tKisiselBilgiler.Text = programAyarlari.kKisiselBilgiler;
programAyarlari.fprofil.pResim.ImageLocation = programAyarlari.kResim;
this.Hide();
programAyarlari.fprofil.Show();
}
private void tSAyarlar_Click(object sender, EventArgs e)
{
// Değişkenlere ekle
programAyarlari.fayarlar.tPAdi.Text = programAyarlari.pAdi;
programAyarlari.fayarlar.tSurumu.Text = programAyarlari.pSurumu;
programAyarlari.fayarlar.tYapimci.Text = programAyarlari.pYapimci;
programAyarlari.fayarlar.tTel.Text = programAyarlari.pYapimciTel;
programAyarlari.fayarlar.tWebSite.Text = programAyarlari.pWebSite;
this.Hide();
programAyarlari.fayarlar.Show();
}
private void tSMusteriler_Click(object sender, EventArgs e)
{
programAyarlari.fmusteriler.dGvMusteri.DataSource = degiskenler.ds.Tables["MUSTERI"];
programAyarlari.fmusteriler.Show();
this.Hide();
}
private void tSKullanicilar_Click(object sender, EventArgs e)
{
programAyarlari.fkullanicilar.pResim.ImageLocation = @"resimler/default.png";
programAyarlari.fkullanicilar.dGvKullanici.DataSource = degiskenler.ds.Tables["KULLANICILAR"];
programAyarlari.fkullanicilar.Show();
this.Hide();
}
private void tSYetki_Click(object sender, EventArgs e)
{
programAyarlari.fyetki.cBxYetki.Items.Clear();
islemler.kosulsuzVeriGetir("Select Y_ADI from YETKI");
while (degiskenler.oku.Read())
{ programAyarlari.fyetki.cBxYetki.Items.Add(degiskenler.oku["Y_ADI"].ToString()); }
degiskenler.baglan.Close();
programAyarlari.fyetki.cBxYetki.SelectedIndex = 0;
programAyarlari.fyetki.Show();
this.Hide();
}
private void menu_Hover(object sender, EventArgs e)
{
ToolStripMenuItem ts = sender as ToolStripMenuItem;
ts.ForeColor = Color.Black;
}
private void menu_Leave(object sender, EventArgs e)
{
ToolStripMenuItem ts = sender as ToolStripMenuItem;
ts.ForeColor = Color.WhiteSmoke;
}
private void tSProfil_MouseMove(object sender, MouseEventArgs e)
{
ToolStripDropDownItem ts = sender as ToolStripDropDownItem;
tSHosgeldiniz.ForeColor = Color.Black;
}
private void tsDropİtem_Leave(object sender, EventArgs e)
{
tSHosgeldiniz.ForeColor = Color.WhiteSmoke;
}
private void f1YardımToolStripMenuItem_Click(object sender, EventArgs e)
{
programAyarlari.fprogramHK.Show();
this.Hide();
}
private void programHakkındaToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void tsOda_Click(object sender, EventArgs e)
{
programAyarlari.tabloDoldur("ODA", programAyarlari.fodaAyarlari.dGvOdaAyarlari);
programAyarlari.fodaAyarlari.Show();
this.Hide();
}
private void tSAciklama_Click(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using veriT;
using System.Data.OleDb;
namespace OTEL254
{
public partial class yetki : Form
{
public yetki()
{
InitializeComponent();
}
private void yetki_FormClosing(object sender, FormClosingEventArgs e)
{
sifirla();
e.Cancel = true;
this.Hide();
programAyarlari.fmain.Show();
}
private void yetki_Load(object sender, EventArgs e)
{
programAyarlari.formBasligi(this, tSAciklama);// Form başlığını yazdırdık.
cBxYetki.SelectedIndex = 0;
}
string yetkiAdi;
private void cBxYetki_SelectedIndexChanged(object sender, EventArgs e)
{
if (cBxYetki.SelectedIndex > -1)
{
yetkiAdi = cBxYetki.Text;
islemler.kosulsuzVeriGetir("Select * from YETKI where Y_ADI='" + yetkiAdi + "'");
while (degiskenler.oku.Read())
{
cHduzenProgramDuzeni.Checked = Convert.ToBoolean(degiskenler.oku["PROGRAM_DUZENI"].ToString());
cHduzenKullanıcı.Checked = Convert.ToBoolean(degiskenler.oku["KULLANICI_ISLEMLERI"].ToString());
cHduzenOdaAyarlari.Checked = Convert.ToBoolean(degiskenler.oku["ODA_ISLEMLERI"].ToString());
cHduzenMusteriAyarlari.Checked = Convert.ToBoolean(degiskenler.oku["MUSTERI_ISLEMLERI"].ToString());
cHduzenGirisCikisKayitlari.Checked = Convert.ToBoolean(degiskenler.oku["GIRIS_CIKIS_KAYITLARI"].ToString());
cHduzenHasilatRaporlari.Checked = Convert.ToBoolean(degiskenler.oku["HASILAT_R_OKUMA"].ToString());
cHduzenYetkiEkleme.Checked = Convert.ToBoolean(degiskenler.oku["YETKI_AYARLARI"].ToString());
}
degiskenler.baglan.Close();
}
}
public static void sifirla()
{
programAyarlari.fyetki.cHduzenProgramDuzeni.Checked = programAyarlari.fyetki.cHduzenKullanıcı.Checked = programAyarlari.fyetki.cHduzenOdaAyarlari.Checked = programAyarlari.fyetki.cHduzenMusteriAyarlari.Checked = programAyarlari.fyetki.cHduzenGirisCikisKayitlari.Checked = programAyarlari.fyetki.cHduzenHasilatRaporlari.Checked = programAyarlari.fyetki.cHduzenYetkiEkleme.Checked = programAyarlari.fyetki.cHekleYetkiEkleme.Checked = programAyarlari.fyetki.cHekleProgramDuzeni.Checked = programAyarlari.fyetki.cHekleOdaAyarlari.Checked = programAyarlari.fyetki.cHekleMusteri.Checked = programAyarlari.fyetki.cHekleKullaniciYetkileri.Checked = programAyarlari.fyetki.cHekleHasilatRaporlari.Checked = programAyarlari.fyetki.cHekleGirisCikis.Checked = false;
programAyarlari.fyetki.textBox1.Text = "";
programAyarlari.fyetki.cBxYetki.Items.Clear();
islemler.kosulsuzVeriGetir("Select Y_ADI from YETKI");
while (degiskenler.oku.Read())
{ programAyarlari.fyetki.cBxYetki.Items.Add(degiskenler.oku["Y_ADI"].ToString()); }
degiskenler.baglan.Close();
programAyarlari.fyetki.cBxYetki.SelectedIndex = 0;
}
private void cBxYetki_TextChanged(object sender, EventArgs e)
{
if (cBxYetki.Text == "") sifirla();
}
private void button2_Click(object sender, EventArgs e)
{
try
{
if (cBxYetki.Text != "Founder" || cBxYetki.Text != "")
{
programAyarlari.fkullanicilar.cYetki.Items.Remove(cBxYetki.Text);
degiskenler.komut = new OleDbCommand("Delete * from YETKI where Y_ADI=@y_adi", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@kosul1", cBxYetki.Text);
islemler.kosulluVeriSil(degiskenler.komut);
MessageBox.Show("Yetki silindi!", "Başarı");
sifirla();
}
else programAyarlari.hataVer("Bu yetkiyi silemezsiniz.", "Kurucu yetkisi silinemez.");
}
catch (Exception)
{
programAyarlari.hataVer("Bu yetki şuanda silinemiyor.", "Bu yetki şuan bir veya birden fazla kullanıcı da bulunuyor.\nLütfen önce bu kullanıcıların yetkilerini değiştiriniz.");
}
}
private void bAyarlariUygula_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
try
{
islemler.veriEkle("YETKI", "Y_ADI,GIRIS_CIKIS_KAYITLARI,HASILAT_R_OKUMA,KULLANICI_ISLEMLERI,MUSTERI_ISLEMLERI,ODA_ISLEMLERI,PROGRAM_DUZENI,YETKI_AYARLARI", "'" + textBox1.Text + "'," + cHekleGirisCikis.Checked + "," + cHekleHasilatRaporlari.Checked + "," + cHekleKullaniciYetkileri.Checked + "," + cHekleMusteri.Checked + "," + cHekleOdaAyarlari.Checked + "," + cHekleProgramDuzeni.Checked + "," + cHekleYetkiEkleme.Checked + "");
MessageBox.Show("Başarıyla eklendi!", "Başarı");
programAyarlari.fkullanicilar.cYetki.Items.Add(textBox1.Text);
sifirla();
}
catch (Exception ex)
{
programAyarlari.hataVer("Bu yetki şuanda eklenemiyor.", "Bu yetki şuan bir yetkiyle aynı ismi taşıyor." + ex);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
if (cBxYetki.SelectedIndex > -1)
{
try
{
if (cBxYetki.Text != "Founder")
{
islemler.varsaKosulluVeriGuncelle("YETKI", "PROGRAM_DUZENI = " + cHduzenProgramDuzeni.Checked + ",YETKI_AYARLARI = " + cHduzenYetkiEkleme.Checked + ",GIRIS_CIKIS_KAYITLARI=" + cHduzenGirisCikisKayitlari.Checked + ",HASILAT_R_OKUMA=" + cHduzenHasilatRaporlari.Checked + ",KULLANICI_ISLEMLERI=" + cHduzenKullanıcı.Checked + ",MUSTERI_ISLEMLERI=" + cHduzenMusteriAyarlari.Checked + ",ODA_ISLEMLERI =" + cHduzenOdaAyarlari.Checked, "Y_ADI = '" + cBxYetki.Text + "'");
MessageBox.Show("Yetki düzenlendi!", "Başarı");
sifirla();
} else programAyarlari.hataVer("Bu yetki düzenlenemiyor.", "Kurucu yetkileri değiştirilemez.");
}
catch (Exception)
{
programAyarlari.hataVer("Bu yetki şuanda düzenlenemiyor.", "Bu yetki şuan bir veya birden fazla kullanıcı da bulunuyor.\nLütfen önce bu kullanıcıların yetkilerini değiştiriniz.");
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using veriT;
namespace OTEL254
{
public partial class musteriEkle : Form
{
public musteriEkle()
{
InitializeComponent();
}
private void musteriEkle_Load(object sender, EventArgs e)
{
programAyarlari.formBasligi(this, tSAciklama);// Form başlığını yazdırdık.
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked == true) groupBox1.Visible = false;
else groupBox1.Visible = true;
}
private void bArkaPlan_Click(object sender, EventArgs e)
{
this.Hide();
programAyarlari.fodalar.Show();
}
private void musteriEkle_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Hide();
labelRezervasyon.Text = "Oda rezervasyonu bulunmamaktadır.";
programAyarlari.fodalar.Show();
}
void odaSat()
{
foreach (Control item in programAyarlari.fodalar.panel2.Controls) // panel2 deki elemanları kontrol ediyoruz.
{
if (item is PictureBox) // eğer eleman picturebox ise
{
PictureBox yeniP = item as PictureBox; // bu elemanı pictureboxa aktardık
if (item.Name.ToString() == "p" + programAyarlari.secilenOda)
{
yeniP.ImageLocation = @"resimler/doluOda.png"; // eğer elemanın namesi doluodanumarasına eşitse resmini değiştirdik.
}
}
else if (item is Button) // eğer eleman Button ise
if (item.Name.ToString() == "b" + programAyarlari.secilenOda)
{
item.BackColor = Color.Red; // arkaplanını kırmızı yaptık.
item.Text = programAyarlari.secilenOda + " - Dolu";
}
}
}
void siradakiMusteriRezervasyonTarihi()
{
// Bir sonraki rezervasyonu getiriyoruz.
DateTime ilkRez = DateTime.Parse("28.12.2999 00:00");
programAyarlari.rezervasyonBtarihi = "28.12.2999";
degiskenler.komut = new System.Data.OleDb.OleDbCommand("select * from REZERVASYON where R_O_NU=@odaNu", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@odaNu", programAyarlari.secilenOda);
islemler.kosulluVeriGetir(degiskenler.komut);
while (degiskenler.oku.Read())
{
if (ilkRez > Convert.ToDateTime(degiskenler.oku["R_BASLANGIC_TARIHI"])) ilkRez = Convert.ToDateTime(degiskenler.oku["R_BASLANGIC_TARIHI"]);
programAyarlari.rezervasyonBtarihi = ilkRez.ToShortDateString();
programAyarlari.fmusteriEkle.labelRezervasyon.Text = "Bu odanın en yakın rezervasyon tarihi : " + programAyarlari.rezervasyonBtarihi;
}
if (programAyarlari.rezervasyonBtarihi == "28.12.2999")
programAyarlari.fmusteriEkle.labelRezervasyon.Text = "Oda rezervasyonu bulunmamaktadır.";
degiskenler.baglan.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked == false)
{
if (tAdiSoyadi.Text == "" || tMusteriTC.Text == "" || tTel.Text == "") programAyarlari.hataVer("Dikkat", "Gerekli alanları boş bırakmayınız.");
else
{
bool rezervasyonVarMi = false;
degiskenler.komut = new System.Data.OleDb.OleDbCommand("Select * from REZERVASYON where R_BASLANGIC_TARIHI=@rBaslangic and R_O_NU=@odaNu and R_M_TC=@m_tc", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@rBaslangic", DateTime.Now.ToShortDateString());
degiskenler.komut.Parameters.Add("@odaNu", programAyarlari.secilenOda);
degiskenler.komut.Parameters.Add("@m_tc", tMusteriTC.Text);
islemler.kosulluVeriGetir(degiskenler.komut);
if (degiskenler.oku.Read()) rezervasyonVarMi = true;
degiskenler.baglan.Close();
if (rezervasyonVarMi == true)
{
degiskenler.komut = new System.Data.OleDb.OleDbCommand("Delete * from REZERVASYON where R_BASLANGIC_TARIHI=@rBaslangic and R_O_NU=@odaNu and R_M_TC=@m_tc", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@rBaslangic", DateTime.Now.ToShortDateString());
degiskenler.komut.Parameters.Add("@odaNu", programAyarlari.secilenOda);
degiskenler.komut.Parameters.Add("@m_tc", tMusteriTC.Text);
islemler.kosulluVeriSil(degiskenler.komut);
}
siradakiMusteriRezervasyonTarihi();
if (dTpCikisTarihi.Value > Convert.ToDateTime(programAyarlari.rezervasyonBtarihi))
{
programAyarlari.hataVer("Çıkış tarihi ile ilgili bir hata oldu", "Çıkış tarihi sırada ki randevulu müşterinin giriş tarihinden büyük.\nLütfen çıkış tarihinizi sırada ki müşterininkine göre ayarlayınız.");
dTpCikisTarihi.Value = DateTime.Now;
}
else
{
try
{
islemler.veriEkle("MUSTERI", "M_TC,M_ADI_SOYADI,M_TEL,M_ADRES,M_KAYIT_TARIHI,M_BERABERINDEKILER", "'" + tMusteriTC.Text + "','" + tAdiSoyadi.Text + "','" + tTel.Text + "','" + tAdres.Text + "','" + DateTime.Now.ToShortDateString() + "','" + tBeraberindekiler.Text + "'");
islemler.veriEkle("ODA_MUSTERI", "OM_O_NU,OM_M_TC,OM_GIRIS_TARIHI,OM_CIKIS_TARIHI", "'" + programAyarlari.secilenOda + "','" + tMusteriTC.Text + "','" + DateTime.Now.ToShortDateString() + "','" + dTpCikisTarihi.Value.ToShortDateString() + "'");
islemler.veriEkle("GIRIS_RAPOR", "GR_O_NU,GR_M_TC,GR_TARIH_SAAT", "'" + programAyarlari.secilenOda + "','" + tMusteriTC.Text + "','" + DateTime.Now + "'");
odaSat();
programAyarlari.bosOdaS -= 1; // label doluya yazdık
programAyarlari.doluOdaS += 1;
programAyarlari.fodalar.lBos.Text = "Boş oda : " + programAyarlari.bosOdaS.ToString(); // label doluya yazdık odalar Formundaki
programAyarlari.fodalar.lDolu.Text = "Dolu oda : " + programAyarlari.doluOdaS.ToString(); // label doluya yazdık
programAyarlari.fodalar.Show();
programAyarlari.rezervasyonBtarihi = DateTime.Now.ToShortDateString();
MessageBox.Show("Müşteri " + programAyarlari.secilenOda + " numaralı odaya başarıyla eklenmiştir.", "Başarı");
}
catch (Exception) { programAyarlari.hataVer("Dikkat", "Müşteri zaten kayıtlı.\n'Müşteri kayıtlı ise işaretleyiniz.' onay kutusu sizin için seçiliyor."); checkBox1.Checked = true; }
}
}
}
else
{
if (tMusteriTC.Text == "") programAyarlari.hataVer("Dikkat", "Gerekli alanları boş bırakmayınız.");
else
{
bool rezervasyonVarMi = false;
degiskenler.komut = new System.Data.OleDb.OleDbCommand("Select * from REZERVASYON where R_BASLANGIC_TARIHI=@rBaslangic and R_O_NU=@odaNu and R_M_TC=@m_tc", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@rBaslangic", DateTime.Now.ToShortDateString());
degiskenler.komut.Parameters.Add("@odaNu", programAyarlari.secilenOda);
degiskenler.komut.Parameters.Add("@m_tc", tMusteriTC.Text);
islemler.kosulluVeriGetir(degiskenler.komut);
if (degiskenler.oku.Read()) rezervasyonVarMi = true;
degiskenler.baglan.Close();
if (rezervasyonVarMi == true)
{
degiskenler.komut = new System.Data.OleDb.OleDbCommand("Delete * from REZERVASYON where R_BASLANGIC_TARIHI=@rBaslangic and R_O_NU=@odaNu and R_M_TC=@m_tc", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@rBaslangic", DateTime.Now.ToShortDateString());
degiskenler.komut.Parameters.Add("@odaNu", programAyarlari.secilenOda);
degiskenler.komut.Parameters.Add("@m_tc", tMusteriTC.Text);
islemler.kosulluVeriSil(degiskenler.komut);
}
siradakiMusteriRezervasyonTarihi();
if (dTpCikisTarihi.Value > Convert.ToDateTime(programAyarlari.rezervasyonBtarihi))
{
programAyarlari.hataVer("Çıkış tarihi ile ilgili bir hata oldu.", "Çıkış tarihi sırada ki randevulu müşterinin giriş tarihine eş değer.\nLütfen çıkış tarihinizi sırada ki müşterininkine göre ayarlayınız.");
dTpCikisTarihi.Value = DateTime.Now;
}
else
{
islemler.veriEkle("ODA_MUSTERI", "OM_O_NU,OM_M_TC,OM_GIRIS_TARIHI,OM_CIKIS_TARIHI", "'" + programAyarlari.secilenOda + "','" + tMusteriTC.Text + "','" + DateTime.Now.ToShortDateString() + "','" + dTpCikisTarihi.Value.ToShortDateString() + "'");
islemler.veriEkle("GIRIS_RAPOR", "GR_O_NU,GR_M_TC,GR_TARIH_SAAT", "'" + programAyarlari.secilenOda + "','" + tMusteriTC.Text + "','" + DateTime.Now + "'");
odaSat();
this.Hide();
programAyarlari.bosOdaS -= 1; // label doluya yazdık
programAyarlari.doluOdaS += 1;
programAyarlari.fodalar.lBos.Text = "Boş oda : " + programAyarlari.bosOdaS.ToString(); // label doluya yazdık odalar Formundaki
programAyarlari.fodalar.lDolu.Text = "Dolu oda : " + programAyarlari.doluOdaS.ToString(); // label doluya yazdık
programAyarlari.fodalar.Show();
programAyarlari.rezervasyonBtarihi = DateTime.Now.ToShortDateString();
MessageBox.Show("Müşteri " + programAyarlari.secilenOda + " numaralı odaya başarıyla eklenmiştir.", "Başarı");
}
}
}
}
private void dTpCikisTarihi_ValueChanged(object sender, EventArgs e)
{
if (dTpCikisTarihi.Value < DateTime.Now)
{
dTpCikisTarihi.Value = DateTime.Now;
MessageBox.Show("Geçmiş döneme ait giriş yapamazsınız.", "Hata");
}
/* else
{
bool rezervasyonVarMi = false;
degiskenler.komut = new System.Data.OleDb.OleDbCommand("Select * from REZERVASYON where R_BASLANGIC_TARIHI=@rBaslangic and R_O_NU=@odaNu and R_M_TC=@m_tc", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@rBaslangic", DateTime.Now.ToShortDateString());
degiskenler.komut.Parameters.Add("@odaNu", programAyarlari.secilenOda);
degiskenler.komut.Parameters.Add("@m_tc", tMusteriTC.Text);
islemler.kosulluVeriGetir(degiskenler.komut);
if (degiskenler.oku.Read()) rezervasyonVarMi = true;
degiskenler.baglan.Close();
if (rezervasyonVarMi == true)
{
// Kendisine ait rezervasyonu siliyoruz
degiskenler.komut = new System.Data.OleDb.OleDbCommand("Delete * from REZERVASYON where R_BASLANGIC_TARIHI=@rBaslangic and R_O_NU=@odaNu and R_M_TC=@m_tc", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@rBaslangic", DateTime.Now.ToShortDateString());
degiskenler.komut.Parameters.Add("@odaNu", programAyarlari.secilenOda);
degiskenler.komut.Parameters.Add("@m_tc", tMusteriTC.Text);
islemler.kosulluVeriSil(degiskenler.komut);
// Bir sonraki rezervasyonu getiriyoruz.
DateTime ilkRez = DateTime.Parse("28.12.2999 00:00");
degiskenler.komut = new System.Data.OleDb.OleDbCommand("select * from REZERVASYON where R_O_NU=@odaNu", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@odaNu", programAyarlari.secilenOda);
islemler.kosulluVeriGetir(degiskenler.komut);
while (degiskenler.oku.Read())
{
if (ilkRez > Convert.ToDateTime(degiskenler.oku["R_BASLANGIC_TARIHI"])) ilkRez = Convert.ToDateTime(degiskenler.oku["R_BASLANGIC_TARIHI"]);
programAyarlari.rezervasyonBtarihi = ilkRez.ToShortDateString();
programAyarlari.fmusteriEkle.labelRezervasyon.Text = "Bu odanın en yakın rezervasyon tarihi : " + programAyarlari.rezervasyonBtarihi;
}
if (dTpCikisTarihi.Value > Convert.ToDateTime(programAyarlari.rezervasyonBtarihi))
{
MessageBox.Show("Çıkışı bu tarihe alamazsınız.");
dTpCikisTarihi.Value = DateTime.Now;
}
}
else // o gün için rezervasyon yoksa
{
// Bir sonraki rezervasyonu getiriyoruz.
DateTime ilkRez = DateTime.Parse("28.12.2999 00:00");
degiskenler.komut = new System.Data.OleDb.OleDbCommand("select * from REZERVASYON where R_O_NU=@odaNu", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@odaNu", programAyarlari.secilenOda);
islemler.kosulluVeriGetir(degiskenler.komut);
while (degiskenler.oku.Read())
{
if (ilkRez > Convert.ToDateTime(degiskenler.oku["R_BASLANGIC_TARIHI"])) ilkRez = Convert.ToDateTime(degiskenler.oku["R_BASLANGIC_TARIHI"]);
programAyarlari.rezervasyonBtarihi = ilkRez.ToShortDateString();
programAyarlari.fmusteriEkle.labelRezervasyon.Text = "Bu odanın en yakın rezervasyon tarihi : " + programAyarlari.rezervasyonBtarihi;
}
if (dTpCikisTarihi.Value > Convert.ToDateTime(programAyarlari.rezervasyonBtarihi))
{
MessageBox.Show("Çıkışı bu tarihe alamazsınız.");
dTpCikisTarihi.Value = DateTime.Now;
}
}
}*/
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using veriT;
namespace OTEL254
{
public partial class ayarlar : Form
{
public ayarlar()
{
InitializeComponent();
}
private void ayarlar_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
programAyarlari.fmain.Show();
e.Cancel = true;
}
private void ayarlar_Load(object sender, EventArgs e)
{
programAyarlari.formBasligi(this, tSAciklama);// Form başlığını yazdırdık.
}
private void bArkaPlan_Click(object sender, EventArgs e)
{
colorDialog1.ShowDialog();
}
private void bSifirla_Click(object sender, EventArgs e)
{
tPAdi.Text = "Otel Takip Programı";
tSurumu.Text = " ";
tYapimci.Text = "Güneş Yazılım";
tTel.Text = "05453715731";
tWebSite.Text = "nurullahgunes.com";
}
private void bAyarlariUygula_Click(object sender, EventArgs e)
{
islemler.varsaKosulluVeriGuncelle("PROGRAM", "P_ADI = '" + tPAdi.Text + "',P_SURUMU = '" + tSurumu.Text + "',P_YAYIMCISI = '" + tYapimci.Text + "',P_YAYIMCISI_TEL = '" + tTel.Text + "',P_WEBSITE = '" + tWebSite.Text + "'","");
programAyarlari.pAdi = programAyarlari.fayarlar.tPAdi.Text;
programAyarlari.pSurumu = programAyarlari.fayarlar.tSurumu.Text;
programAyarlari.pYapimci = programAyarlari.fayarlar.tYapimci.Text;
programAyarlari.pYapimciTel = programAyarlari.fayarlar.tTel.Text;
programAyarlari.pWebSite = programAyarlari.fayarlar.tWebSite.Text;
MessageBox.Show("Ayarlar güncellendi. Güncelleme başarılı.", "Ayarlar değişti.", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void bGeri_Click(object sender, EventArgs e)
{
this.Hide();
programAyarlari.fmain.Show();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OTEL254
{
public partial class programHK : Form
{
public programHK()
{
InitializeComponent();
}
private void programHK_Load(object sender, EventArgs e)
{
programAyarlari.formBasligi(this, tSAciklama);
}
private void programHK_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Hide();
programAyarlari.fmain.Show();
}
private void button1_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void statusStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using veriT;
namespace OTEL254
{
public partial class rezervasyonlar : Form
{
public rezervasyonlar()
{
InitializeComponent();
}
private void rezervasyonlar_Load(object sender, EventArgs e)
{
programAyarlari.formBasligi(this, tSAciklama);// Form başlığını yazdırdık.
}
private void rezervasyonlar_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Hide();
programAyarlari.fmain.Show();
}
private void button1_Click(object sender, EventArgs e)
{
programAyarlari.fmusteriler.Show();
this.Hide();
programAyarlari.fmusteriler.tAra.Text = tTC.Text;
if (programAyarlari.fmusteriler.tAra.Text == "")
{
programAyarlari.fmusteriler.dGvMusteri.DataSource = degiskenler.ds.Tables["MUSTERI"];
programAyarlari.fmusteriler.dGvMusteri.Refresh();
} // Boşsa tüm veriler gelecek
else // Doluysa arama yapılacak.
{
OleDbDataAdapter oDataA = new OleDbDataAdapter("Select * From MUSTERI where M_TC like '%" + programAyarlari.fmusteriler.tAra.Text + "%' or M_ADI_SOYADI like '%" + programAyarlari.fmusteriler.tAra.Text + "%'", degiskenler.baglan);
programAyarlari.kosulluMusteriGetir("MUSTERI", programAyarlari.fmusteriler.dGvMusteri, oDataA);
programAyarlari.fmusteriler.dGvMusteri.ClearSelection();
//programAyarlari.musteriGetir("MUSTERI", programAyarlari.fmusteriler.dGvMusteri, "M_TC like '%" + tAra.Text + "%' or M_ADI_SOYADI like '%" + tAra.Text + "%'");
}
}
private void cOda_SelectedIndexChanged(object sender, EventArgs e)
{
if (cOda.SelectedIndex > -1)
{
if (programAyarlari.fmusteriler.tAra.Text == "")
{
dGvSecilenOdaRezervasyonlari.DataSource = degiskenler.ds.Tables["MUSTERI"];
dGvSecilenOdaRezervasyonlari.Refresh();
} // Boşsa tüm veriler gelecek
else // Doluysa arama yapılacak.
{
OleDbDataAdapter oDataA = new OleDbDataAdapter("Select * From REZERVASYON where R_O_NU =" + cOda.Text, degiskenler.baglan);
programAyarlari.kosulluMusteriGetir("REZERVASYON", dGvSecilenOdaRezervasyonlari, oDataA);
dGvSecilenOdaRezervasyonlari.ClearSelection();
}
}
}
private void dGvSecilenOdaRezervasyonlari_CellClick(object sender, DataGridViewCellEventArgs e)
{
bMusteriEkle.Enabled = false;
bMusteriSil.Enabled = bDuzenle.Enabled = true;
DataGridView d = sender as DataGridView;
try
{
dTpBitis.Text = d.SelectedRows[0].Cells[3].Value.ToString();
dTpBaslangic.Text = d.SelectedRows[0].Cells[0].Value.ToString();
cOda.Text = d.SelectedRows[0].Cells[1].Value.ToString();
tTC.Text = d.SelectedRows[0].Cells[2].Value.ToString();
}
catch (Exception) { }
}
void rGetir()
{
tTC.Text = "";
programAyarlari.tabloDoldur("REZERVASYON", dGvTumRezervasyon);
islemler.bagKontrol(); // Bağlantı kontrolü
programAyarlari.ds3.Clear(); // dataset temizle
degiskenler.adaptor = new OleDbDataAdapter("Select * from REZERVASYON where R_BASLANGIC_TARIHI=@rBaslangic", degiskenler.baglan);// Sorguda ki tablo verilerini koşul varsa getir yoksa koşul boşsa tüm veriler.
degiskenler.adaptor.SelectCommand.Parameters.Add("@rBaslangic", DateTime.Now.ToShortDateString());
degiskenler.adaptor.Fill(programAyarlari.ds3, "REZERVASYON"); // dataseti tabloadına göre doldur
dGvRezervasyonuOlanKisiler.DataSource = programAyarlari.ds3.Tables["REZERVASYON"];
degiskenler.baglan.Close();
dGvRezervasyonuOlanKisiler.ClearSelection();
programAyarlari.tabloDoldur("REZERVASYON where R_O_NU =" + cOda.Text, dGvSecilenOdaRezervasyonlari);
}
private void bDuzenle_Click(object sender, EventArgs e)
{
bMusteriEkle.Enabled = true;
bMusteriSil.Enabled = bDuzenle.Enabled = false;
}
private void bMusteriSil_Click(object sender, EventArgs e)
{
bMusteriEkle.Enabled = true;
bMusteriSil.Enabled = bDuzenle.Enabled = false;
try
{
degiskenler.komut = new OleDbCommand("DELETE * FROM REZERVASYON where R_BASLANGIC_TARIHI=@rBaslagic and R_O_NU=@rOdaNu and R_M_TC=@rMTC and R_BITIS_TARIHI=@rBitis",degiskenler.baglan);
degiskenler.komut.Parameters.Add("@rBaslagic", dTpBaslangic.Value.ToShortDateString());
degiskenler.komut.Parameters.Add("@rOdaNu", cOda.Text);
degiskenler.komut.Parameters.Add("@rMTC", tTC.Text);
degiskenler.komut.Parameters.Add("@rBitis", dTpBitis.Value.ToShortDateString());
islemler.kosulluVeriSil(degiskenler.komut);
rGetir();
MessageBox.Show("Müşteri rezervasyonu başarıyla silinmiştir.","Başarılı");
}
catch (Exception) { programAyarlari.hataVer("Kayıt bulunamadı","Lütfen silmek istediğiniz müşteri rezervasyonuna tıklayın ve sil tuşuna tekrar basın."); }
}
private void bMusteriEkle_Click(object sender, EventArgs e)
{
try
{ // eğer bu odaya ait rezervasyonlar içerisinde dTpBaslangic tarihinden büyük bir başlangıç tarihi VE dTpBitis tarihinden küçük bir rezervasyon varsa rezervasyonu o tarihler arasına alınmayacak.
islemler.veriEkle("REZERVASYON", "R_BASLANGIC_TARIHI,R_O_NU,R_M_TC,R_BITIS_TARIHI", "'" + dTpBaslangic.Value.ToShortDateString() + "','" + cOda.Text + "','" + tTC.Text + "','" + dTpBitis.Value.ToShortDateString() + "'");
MessageBox.Show("Müşteri rezervasyonu başarıyla alınmıştır.", "Başarılı");
rGetir();
}
catch (Exception) { programAyarlari.hataVer("Rezervasyon alınamadı. ", "Lütfen müşteri numarasını kontrol ediniz."); }
}
private void dTpBitis_ValueChanged(object sender, EventArgs e)
{
// if (dTpBitis.Value < dTpBaslangic.Value) { programAyarlari.hataVer("Hata", "Lütfen çıkış tarihini ileri bir tarih seçiniz."); dTpBitis.Value = DateTime.Now; }
// if (dTpBitis.Value < DateTime.Now) { programAyarlari.hataVer("Hata", "Geçmiş döneme ait rezervasyon alamazsınız."); dTpBitis.Value = DateTime.Now; }
}
private void dTpBaslangic_ValueChanged(object sender, EventArgs e)
{
// if (dTpBaslangic.Value > dTpBitis.Value) { programAyarlari.hataVer("Hata", "Lütfen başlangıç tarihini geri bir tarih seçiniz."); dTpBaslangic.Value = DateTime.Now; }
// if (dTpBaslangic.Value < DateTime.Now) { programAyarlari.hataVer("Hata", "Geçmiş döneme ait rezervasyon alamazsınız."); dTpBaslangic.Value = DateTime.Now; }
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using veriT;
namespace OTEL254
{
public partial class odalar : Form
{
public odalar()
{
InitializeComponent();
}
private void odalar_FormClosing(object sender, FormClosingEventArgs e)
{
bRezervasyon.Enabled = bTemizeGec.Enabled = bMusteriCikisi.Enabled = bMusteriEkle.Enabled = false;
e.Cancel = true;
this.Hide();
programAyarlari.fmain.Show();
}
private void odalar_Load(object sender, EventArgs e)
{
programAyarlari.formBasligi(this, tSAciklama);// Form başlığını yazdırdık.
}
private void panel2_Resize(object sender, EventArgs e)
{
int konumX = 0;
int konumY = 20;
int bWBoyutu = (panel2.Width / 10) - 2;
PictureBox p = new PictureBox();
Button b = new Button();
foreach (Control item in panel2.Controls)
{
if (konumX == 10)
{
konumX = 0;
konumY += (bWBoyutu / 2) + (bWBoyutu / 4) + 30;
}
if (item is PictureBox)
{
p = item as PictureBox;
p.Size = new Size(bWBoyutu, (bWBoyutu / 2) + (bWBoyutu / 4)); // boyutu yarısının çeyrek fazlası
item.Location = new Point((konumX * bWBoyutu) + 10, konumY);
}
else if (item is Button)
{
b = item as Button;
b.Size = new Size(bWBoyutu, 30);
item.Location = new Point((konumX * bWBoyutu) + 10, p.Location.Y + (bWBoyutu / 2) + (bWBoyutu / 4));
konumX++;
}
}
}
private void bMusteriEkle_Click(object sender, EventArgs e)
{
programAyarlari.fmusteriEkle.dTpCikisTarihi.Value = DateTime.Now;
DateTime ilkRez = DateTime.Parse("28.12.2999 00:00");
programAyarlari.rezervasyonBtarihi = "28.12.2999";
degiskenler.komut = new OleDbCommand("select * from REZERVASYON where R_O_NU=@odaNu", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@odaNu", programAyarlari.secilenOda);
islemler.kosulluVeriGetir(degiskenler.komut);
while (degiskenler.oku.Read())
{
if (ilkRez > Convert.ToDateTime(degiskenler.oku["R_BASLANGIC_TARIHI"])) ilkRez = Convert.ToDateTime(degiskenler.oku["R_BASLANGIC_TARIHI"]);
programAyarlari.rezervasyonBtarihi = ilkRez.ToShortDateString();
programAyarlari.fmusteriEkle.labelRezervasyon.Text = "Bu odanın en yakın rezervasyon tarihi : " + programAyarlari.rezervasyonBtarihi;
}
degiskenler.baglan.Close();
if (programAyarlari.rezervasyonBtarihi == "28.12.2999")
programAyarlari.fmusteriEkle.labelRezervasyon.Text = "Oda rezervasyonu bulunmamaktadır.";
programAyarlari.fmusteriEkle.labelOdaNu.Text = "Oda numarası " + programAyarlari.secilenOda;
programAyarlari.fmusteriEkle.Show();
this.Hide();
}
private void bTemizeGec_Click(object sender, EventArgs e)
{
if (programAyarlari.secilen.Text == programAyarlari.secilenOda + " - Kirli")
{
try
{
degiskenler.komut = new OleDbCommand("Delete * from ODA_MUSTERI where OM_O_NU=@odaNu", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@odaNu", programAyarlari.secilenOda);
islemler.kosulluVeriSil(degiskenler.komut);
programAyarlari.bosOdaS += 1; // label doluya yazdık
programAyarlari.doluOdaS -= 1;
programAyarlari.fodalar.lBos.Text = "Boş oda : " + programAyarlari.bosOdaS.ToString(); // label doluya yazdık odalar Formundaki
programAyarlari.fodalar.lDolu.Text = "Dolu oda : " + programAyarlari.doluOdaS.ToString(); // label doluya yazdık
foreach (Control item in programAyarlari.fodalar.panel2.Controls) // panel2 deki elemanları kontrol ediyoruz.
{
if (item is PictureBox) // eğer eleman picturebox ise
{
PictureBox yeniP = item as PictureBox; // bu elemanı pictureboxa aktardık
if (item.Name.ToString() == "p" + programAyarlari.secilenOda)
{
yeniP.ImageLocation = @"resimler/bosOda.png"; // eğer elemanın namesi doluodanumarasına eşitse resmini değiştirdik.
}
}
else if (item is Button) // eğer eleman Button ise
if (item.Name.ToString() == "b" + programAyarlari.secilenOda)
{
item.BackColor = Color.Green; // arkaplanını kırmızı yaptık.
item.Text = programAyarlari.secilenOda;
}
}
}
catch (Exception)
{
throw;
}
}
}
private void bMusteriCikisi_Click(object sender, EventArgs e)
{
DialogResult diaRes = MessageBox.Show("Dikkat çıkış yapılacak.\n" + programAyarlari.secilenOda + " numaralı oda " + ((programAyarlari.gun == 0) ? programAyarlari.gun + 1 : programAyarlari.gun) + " Gün kalınmış.\n" + (programAyarlari.odaFiyati * ((programAyarlari.gun == 0) ? programAyarlari.gun + 1 : programAyarlari.gun)).ToString() + " ₺ Oda ücreti bulunuyor.\nKayıtlara geçilmesini ve çıkış yapılmasını onaylıyor musunuz ?", "Uyarı: Bu işlem geri alınamaz. Lütfen dikkatli kullanınız.", MessageBoxButtons.YesNo);
if (programAyarlari.secilen.Text == programAyarlari.secilenOda + " - Dolu" && diaRes == DialogResult.Yes)
{
try
{
degiskenler.komut = new OleDbCommand("Delete * from ODA_MUSTERI where OM_O_NU=@odaNu", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@odaNu", programAyarlari.secilenOda);
islemler.kosulluVeriSil(degiskenler.komut);
// ÇIKIŞ RAPORU
islemler.veriEkle("CIKIS_RAPOR", "CR_TARIH_SAAT,CR_M_TC,CR_O_NU,CR_TOPLAM_TUTAR", "'" + DateTime.Now + "','" + programAyarlari.secilenOda + "','" + programAyarlari.secilenOda + "','" + programAyarlari.sOdaTutari + "'");
foreach (Control item in programAyarlari.fodalar.panel2.Controls) // panel2 deki elemanları kontrol ediyoruz.
{
if (item is PictureBox) // eğer eleman picturebox ise
{
PictureBox yeniP = item as PictureBox; // bu elemanı pictureboxa aktardık
if (item.Name.ToString() == "p" + programAyarlari.secilenOda)
{
yeniP.ImageLocation = @"resimler/doluOda.png"; // eğer elemanın namesi doluodanumarasına eşitse resmini değiştirdik.
}
}
else if (item is Button) // eğer eleman Button ise
if (item.Name.ToString() == "b" + programAyarlari.secilenOda)
{
item.BackColor = Color.Red; // arkaplanını kırmızı yaptık.
item.Text = programAyarlari.secilenOda + " - Kirli";
}
}
bMusteriCikisi.Enabled = false;
bTemizeGec.Enabled = true;
}
catch (Exception ex) { programAyarlari.hataVer("Bir şeyler ters gitti.", "Beklenmedik bir hata gerçekleşti.\nHata ayrıntılarına aşağıdan ulaşabilirsiniz.\n" + ex.ToString()); } // Hata mesajı
}
}
private void button1_Click(object sender, EventArgs e)
{
islemler.kosulsuzVeriGetir("Select O_NU from ODA");
while (degiskenler.oku.Read())
{ programAyarlari.frezervasyonlar.cOda.Items.Add(degiskenler.oku["O_NU"].ToString()); }
degiskenler.baglan.Close();
programAyarlari.frezervasyonlar.cOda.Text = programAyarlari.secilenOda;
programAyarlari.frezervasyonlar.Show();
this.Hide();
programAyarlari.tabloDoldur("REZERVASYON", programAyarlari.frezervasyonlar.dGvTumRezervasyon);
islemler.bagKontrol(); // Bağlantı kontrolü
programAyarlari.ds3.Clear(); // dataset temizle
degiskenler.adaptor = new OleDbDataAdapter("Select * from REZERVASYON where R_BASLANGIC_TARIHI=@rBaslangic", degiskenler.baglan);// Sorguda ki tablo verilerini koşul varsa getir yoksa koşul boşsa tüm veriler.
degiskenler.adaptor.SelectCommand.Parameters.Add("@rBaslangic", DateTime.Now.ToShortDateString());
degiskenler.adaptor.Fill(programAyarlari.ds3, "REZERVASYON"); // dataseti tabloadına göre doldur
programAyarlari.frezervasyonlar.dGvRezervasyonuOlanKisiler.DataSource = programAyarlari.ds3.Tables["REZERVASYON"];
degiskenler.baglan.Close();
programAyarlari.tabloDoldur("REZERVASYON where R_O_NU =" + programAyarlari.secilenOda, programAyarlari.frezervasyonlar.dGvSecilenOdaRezervasyonlari);
dGvisimleri(programAyarlari.frezervasyonlar.dGvRezervasyonuOlanKisiler);
dGvisimleri(programAyarlari.frezervasyonlar.dGvSecilenOdaRezervasyonlari);
dGvisimleri(programAyarlari.frezervasyonlar.dGvTumRezervasyon);
}
void dGvisimleri(DataGridView d)
{
d.Columns[0].HeaderText = "Başlangıç tarihi";
d.Columns[1].HeaderText = "Oda Numarası";
d.Columns[2].HeaderText = "Müşteri TC'si";
d.Columns[3].HeaderText = "Bitiş tarihi";
d.ClearSelection();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using veriT;
namespace OTEL254
{
public partial class giris : Form
{
public giris()
{
InitializeComponent();
}
void yetkiKontrol(bool yetkiDegiskeni,string veriAdi,ToolStripMenuItem t) // Main sayfasında bazı bölümleri yetki kontrol ile kontrol ettik.
{
if (Convert.ToBoolean(degiskenler.oku[veriAdi]) == true) t.Visible = true; // yetki değişkeni true ise toolstripmenüitemi gösterttik değilse gizledik.
else t.Visible = false;
}
private void bGiris_Click(object sender, EventArgs e)
{
degiskenler.baglan.Close();// Giriş yapıldığında textboxlar boşsa uyarı verilsin değilse giriş için sorgu kontrolü yapılsın.
if (tKullaniciAdi.Text == "" || tSifre.Text == "") MessageBox.Show("Lütfen kullanıcı adı veya şifre alanını boş bırakmayınız.", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
{
programAyarlari.kAdi = programAyarlari.fprofil.tKAdi.Text = tKullaniciAdi.Text.Replace(" ", "").ToLower(); // Kullanıcı adı ve şifre yi baglanti da ki değişkenlere atadık boşluk varsa sildik.
programAyarlari.kSifre = tSifre.Text.Trim();
degiskenler.komut = new OleDbCommand("SELECT * FROM KULLANICILAR INNER JOIN YETKI ON KULLANICILAR.K_Y_ADI = YETKI.Y_ADI where K_KADI=@kAdi and K_SIFRE=@kSifre", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@kAdi", programAyarlari.kAdi);
degiskenler.komut.Parameters.Add("@kSifre", programAyarlari.kSifre);
islemler.kosulluVeriGetir(degiskenler.komut);
if (degiskenler.oku.Read())
{
//string degerBurayaGelecek = degiskenler.oku["sütunAdiniGirmenizGerekli"].ToString();
tKullaniciAdi.Text = "<NAME>"; // textboxı sıfırlıyoruz.
tSifre.Text = "Şifre"; // textboxı sıfırlıyoruz.
/* Giriş yapan kullanıcıların yetkileri */
programAyarlari.kRutbe = degiskenler.oku["K_Y_ADI"].ToString(); // Rütbesi
programAyarlari.kTC = degiskenler.oku["K_TC"].ToString();
programAyarlari.kAdiSoyadi = degiskenler.oku["K_ADI_SOYADI"].ToString();
programAyarlari.kDogumTarihi = degiskenler.oku["K_DOGUM_TARIHI"].ToString();
programAyarlari.kTel = degiskenler.oku["K_TEL"].ToString();
programAyarlari.kAdres = degiskenler.oku["K_ADRES"].ToString();
programAyarlari.kKisiselBilgiler = degiskenler.oku["K_KISISEL_BILGILER"].ToString();
if (degiskenler.oku["K_RESIM"].ToString() == "") programAyarlari.kResim = @"resimler/default.png";
else programAyarlari.kResim = degiskenler.oku["K_RESIM"].ToString();
yetkiKontrol(programAyarlari.programDuzeni, "PROGRAM_DUZENI", programAyarlari.fmain.tSAyarlar);
yetkiKontrol(programAyarlari.yetkiLer, "YETKI_AYARLARI", programAyarlari.fmain.tSYetki);
yetkiKontrol(programAyarlari.kullaniciIslemleri, "KULLANICI_ISLEMLERI", programAyarlari.fmain.tSKullanicilar);
yetkiKontrol(programAyarlari.odaIslemleri, "ODA_ISLEMLERI", programAyarlari.fmain.tsOda);
yetkiKontrol(programAyarlari.musteriIslemleri, "MUSTERI_ISLEMLERI", programAyarlari.fmain.tSMusteriler);
//yetkiKontrol(programAyarlari.girisCikisIslemleri, "GIRIS_CIKIS_KAYITLARI", programAyarlari.fmain.tSGirisKayitlari); // Giriş çıkış kayıtları
//yetkiKontrol(programAyarlari.girisCikisIslemleri, "GIRIS_CIKIS_KAYITLARI", programAyarlari.fmain.tSCikisKayitlari); // Giriş çıkış kayıtları
yetkiKontrol(programAyarlari.hasilatRaporuIslemleri, "HASILAT_R_OKUMA", programAyarlari.fmain.tSHasilat);
// main formuna kullanıcının rütbesini ve kullanıcı adını yazdırdık ve formu gösterip bu formu kapattık.
programAyarlari.fmain.tSHosgeldiniz.Text = programAyarlari.kAdi;
programAyarlari.fmain.Show();
this.Hide();
}
//Eğer başarılı değilse hata ver bilgilendirme yap.
else programAyarlari.hataVer("Giriş yapılamadı. Bilgileri kontrol edip tekrar deneyiniz.", "Lütfen kullanıcı adı veya şifrenizi kontrol edin.\nEğer doğru olduğuna eminseniz daha sonra tekrar deneyiniz.\nŞifrenizi unuttuysanız şifre mi unuttumu deneyebilirsiniz.");
degiskenler.baglan.Close();
}
}
private void giris_Load(object sender, EventArgs e)
{
degiskenler.baglan = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath.ToString() + "\\OTEL254veriTabani.mdb");
islemler.kosulsuzVeriGetir("Select * from PROGRAM");
while (degiskenler.oku.Read()) // Eğer okunuyorsa başarılıysa programAyarlarını belirle
{
programAyarlari.pAdi = degiskenler.oku["P_ADI"].ToString();
programAyarlari.pSurumu = degiskenler.oku["P_SURUMU"].ToString();
programAyarlari.pYapimci = degiskenler.oku["P_YAYIMCISI"].ToString();
programAyarlari.pYapimciTel = degiskenler.oku["P_YAYIMCISI_TEL"].ToString();
programAyarlari.pWebSite = degiskenler.oku["P_WEBSITE"].ToString();
programAyarlari.pYenilikler = degiskenler.oku["P_YENILIKLER"].ToString();
}
degiskenler.baglan.Close(); // Bağlantıyı kapattık
programAyarlari.formBasligi(this, tSAciklama);
odalar();
degiskenler.ds.Clear();
programAyarlari.musteriGetir("KULLANICILAR", programAyarlari.fkullanicilar.dGvKullanici, ""); // Datagridviewlere müşterileri çektik.
programAyarlari.musteriGetir("MUSTERI", programAyarlari.fmusteriler.dGvMusteri, ""); // Datagridviewlere müşterileri çektik.
programAyarlari.musteriSayisi = programAyarlari.fmusteriler.dGvMusteri.Rows.Count;
dGvSutunlariAdlandirma(programAyarlari.fmusteriler.dGvMusteri);
dGvSutunlariAdlandirma(programAyarlari.fkullanicilar.dGvKullanici);
programAyarlari.tabloDoldur("ODA", programAyarlari.fodaAyarlari.dGvOdaAyarlari);
dGvSutunlariAdlandirma(programAyarlari.fodaAyarlari.dGvOdaAyarlari);
}
Button b;
PictureBox pic;
public void odalar()
{
programAyarlari.toplamOdaS = programAyarlari.doluOdaS = 0; // işlem bitiminde bunları sıfırladık.
try
{
int konumX = 0;
int konumY = 20;
int bWBoyutu = (programAyarlari.fodalar.panel2.Width / 10) - 2;
islemler.kosulsuzVeriGetir("SELECT * from ODA");
while (degiskenler.oku.Read())
{
b = new Button();
pic = new PictureBox();
b.Size = new Size(bWBoyutu, 30);
pic.Size = new Size(bWBoyutu, (bWBoyutu / 2) + (bWBoyutu / 4)); // boyutu yarısının çeyrek fazlası
b.FlatStyle = FlatStyle.Popup;
b.ForeColor = Color.White;
if (konumX == 10)
{
konumX = 0;
konumY += (bWBoyutu / 2) + (bWBoyutu / 4) + 30;
}
b.Name = "b" + degiskenler.oku["O_NU"].ToString();
pic.Name = "p" + degiskenler.oku["O_NU"].ToString();
b.Text = degiskenler.oku["O_NU"].ToString();
pic.ImageLocation = @"resimler/bosOda.png";
pic.BackColor = Color.Transparent;
b.Cursor = Cursors.Hand;
pic.SizeMode = PictureBoxSizeMode.StretchImage;
pic.Location = new Point((konumX * bWBoyutu) + 10, konumY);
b.Location = new Point((konumX * bWBoyutu) + 10, pic.Location.Y + (bWBoyutu / 2) + (bWBoyutu / 4));
konumX++;
pic.MouseHover += pic_MouseHover;
pic.MouseLeave += pic_MouseLeave;
pic.MouseMove += pic_MouseMove;
b.Click += but_Click;
programAyarlari.fodalar.panel2.Controls.Add(pic);
programAyarlari.fodalar.panel2.Controls.Add(b);
programAyarlari.toplamOdaS++;
}
degiskenler.baglan.Close();
foreach (Control item in programAyarlari.fodalar.panel2.Controls) { if (item is Button) item.BackColor = Color.Green; } // Önce bütün butonları yeşil yaptık.
islemler.kosulsuzVeriGetir("SELECT * from ODA_MUSTERI");
while (degiskenler.oku.Read())
{
foreach (Control item in programAyarlari.fodalar.panel2.Controls) // panel2 deki elemanları kontrol ediyoruz.
{
if (item is PictureBox) // eğer eleman picturebox ise
{
PictureBox yeniP = item as PictureBox; // bu elemanı pictureboxa aktardık
if (item.Name.ToString() == "p" + degiskenler.oku["OM_O_NU"].ToString())
{ yeniP.ImageLocation = @"resimler/doluOda.png"; } // eğer elemanın namesi doluodanumarasına eşitse resmini değiştirdik.
}
else if (item is Button) // eğer eleman Button ise
if (item.Name.ToString() == "b" + degiskenler.oku["OM_O_NU"].ToString())
{
item.BackColor = Color.Red; // arkaplanını kırmızı yaptık.
item.Text = degiskenler.oku["OM_O_NU"].ToString() + " - Dolu";
if (Convert.ToBoolean(degiskenler.oku["CIKTI_MI"]) == true) item.Text = degiskenler.oku["OM_O_NU"].ToString() + " - Kirli";
}
}
programAyarlari.doluOdaS++; // doluyu bir arttırdık teker teker baktığımız için
}// Arraylistesine dolu odaları ekledik.
degiskenler.baglan.Close();
programAyarlari.bosOdaS = (programAyarlari.toplamOdaS - programAyarlari.doluOdaS); // Boş oda sayısına değer atadık
programAyarlari.fodalar.lBos.Text = "Boş oda : " + programAyarlari.bosOdaS.ToString(); // label doluya yazdık odalar Formundaki
programAyarlari.fodalar.lDolu.Text = "Dolu oda : " + programAyarlari.doluOdaS.ToString(); // label doluya yazdık
programAyarlari.miniOdaDegerGetir();
}
catch (Exception ex) { programAyarlari.hataVer("Beklenmedik bir hata", "Hata ayrıntılarını buradan görebilirsiniz.\n\n" + ex); }
}
void but_Click(object sender, EventArgs e)
{
programAyarlari.secilen = sender as Button;
programAyarlari.secilenOda = programAyarlari.secilen.Name.Substring(1, 3);
programAyarlari.fodalar.lSecilenOda.Text = "Son seçilen oda : " + programAyarlari.secilenOda;
programAyarlari.fodalar.bRezervasyon.Enabled = true;
if (programAyarlari.secilen.Text == programAyarlari.secilenOda + " - Kirli")
{
programAyarlari.fodalar.bTemizeGec.Enabled = true;
programAyarlari.fodalar.bMusteriCikisi.Enabled = programAyarlari.fodalar.bMusteriEkle.Enabled = false;
}
else if (programAyarlari.secilen.Text == programAyarlari.secilenOda + " - Dolu")
{
programAyarlari.fodalar.bTemizeGec.Enabled = programAyarlari.fodalar.bMusteriEkle.Enabled = false;
programAyarlari.fodalar.bMusteriCikisi.Enabled = true;
}
else
{
programAyarlari.fodalar.bMusteriEkle.Enabled = true;
programAyarlari.fodalar.bMusteriCikisi.Enabled = programAyarlari.fodalar.bTemizeGec.Enabled = false;
}
degiskenler.komut = new OleDbCommand("SELECT * FROM MUSTERI INNER JOIN (ODA INNER JOIN ODA_MUSTERI ON ODA.O_NU = ODA_MUSTERI.OM_O_NU) ON MUSTERI.M_TC = ODA_MUSTERI.OM_M_TC where ODA_MUSTERI.OM_O_NU = @odaNu", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@odaNu", programAyarlari.secilenOda);
islemler.kosulluVeriGetir(degiskenler.komut);
while (degiskenler.oku.Read())
{
programAyarlari.sMusteriTC = degiskenler.oku["OM_M_TC"].ToString();
if (Convert.ToBoolean(degiskenler.oku["CIKTI_MI"]) == true)
programAyarlari.fodaBilgisi.lToplamOdenecek.Text = programAyarlari.fodaBilgisi.ltoplamGun.Text = programAyarlari.fodaBilgisi.lCikisTarihi.Text = programAyarlari.fodaBilgisi.lGirisTarihi.Text = programAyarlari.fodaBilgisi.lAdiSoyadi.Text = programAyarlari.fodaBilgisi.lKisiTC.Text = "Oda şuan kirli";
else
{
TimeSpan fark = DateTime.Now.Subtract(Convert.ToDateTime(degiskenler.oku["OM_GIRIS_TARIHI"]));
programAyarlari.gun = Convert.ToInt32(fark.TotalDays) - 1;
if (programAyarlari.gun == 0) programAyarlari.gun = 1; // çıkış tarihinden bir gün geçtiyse
if (programAyarlari.gun < 0) programAyarlari.gun = 0; // çıkış tarihi şimdi ki güne eşitse
programAyarlari.sOdaTutari = (Convert.ToInt32(degiskenler.oku["O_FIYATI"]) * ((programAyarlari.gun == 0) ? programAyarlari.gun + 1 : programAyarlari.gun)).ToString();
programAyarlari.odaFiyati = Convert.ToInt32(degiskenler.oku["O_FIYATI"]);
}
}
degiskenler.baglan.Close();
}
PictureBox picHover;
void pic_MouseHover(object sender, EventArgs e)
{
try
{
picHover = sender as PictureBox;
programAyarlari.fodaBilgisi.checkBoxSuit.Checked = programAyarlari.fodaBilgisi.checkBoxKlima.Checked = programAyarlari.fodaBilgisi.checkBoxTelevizyon.Checked = programAyarlari.fodaBilgisi.checkBoxKapalı.Checked = false;
programAyarlari.fodaBilgisi.lToplamOdenecek.Text = programAyarlari.fodaBilgisi.ltoplamGun.Text = programAyarlari.fodaBilgisi.lCikisTarihi.Text = programAyarlari.fodaBilgisi.lGirisTarihi.Text = programAyarlari.fodaBilgisi.lAdiSoyadi.Text = programAyarlari.fodaBilgisi.lKisiTC.Text = "";
programAyarlari.fodaBilgisi.LodaNumarasi.Text = "Oda numarası " + picHover.Name.Substring(1, 3);
degiskenler.komut = new OleDbCommand("SELECT * FROM MUSTERI INNER JOIN (ODA INNER JOIN ODA_MUSTERI ON ODA.O_NU = ODA_MUSTERI.OM_O_NU) ON MUSTERI.M_TC = ODA_MUSTERI.OM_M_TC where ODA_MUSTERI.OM_O_NU = @odaNu", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@odaNu", picHover.Name.Substring(1, 3).ToString());
islemler.kosulluVeriGetir(degiskenler.komut);
while (degiskenler.oku.Read())
{
if (Convert.ToBoolean(degiskenler.oku["CIKTI_MI"]) == true)
programAyarlari.fodaBilgisi.lToplamOdenecek.Text = programAyarlari.fodaBilgisi.ltoplamGun.Text = programAyarlari.fodaBilgisi.lCikisTarihi.Text = programAyarlari.fodaBilgisi.lGirisTarihi.Text = programAyarlari.fodaBilgisi.lAdiSoyadi.Text = programAyarlari.fodaBilgisi.lKisiTC.Text = "Oda şuan kirli";
else
{
programAyarlari.fodaBilgisi.LodaNumarasi.Text = "Oda numarası " + degiskenler.oku["OM_O_NU"].ToString();
programAyarlari.fodaBilgisi.lKisiTC.Text = degiskenler.oku["M_TC"].ToString();
programAyarlari.fodaBilgisi.lAdiSoyadi.Text = degiskenler.oku["M_ADI_SOYADI"].ToString();
programAyarlari.fodaBilgisi.lGirisTarihi.Text = Convert.ToDateTime(degiskenler.oku["OM_GIRIS_TARIHI"]).ToShortDateString();
programAyarlari.fodaBilgisi.lCikisTarihi.Text = Convert.ToDateTime(degiskenler.oku["OM_CIKIS_TARIHI"]).ToShortDateString();
TimeSpan fark = DateTime.Now.Subtract(Convert.ToDateTime(degiskenler.oku["OM_GIRIS_TARIHI"]));
int gun = Convert.ToInt32(fark.TotalDays);
programAyarlari.fodaBilgisi.ltoplamGun.Text = gun.ToString();
if (gun == 0) gun = 1; // çıkış tarihinden bir gün geçtiyse
if (gun < 0) gun = 0; // çıkış tarihi şimdi ki güne eşitse
if (Convert.ToDateTime(degiskenler.oku["OM_CIKIS_TARIHI"]) < DateTime.Now) programAyarlari.fodaBilgisi.ltoplamGun.Text = ((gun == 0)?gun + 1:gun).ToString() + " Gün oldu çıkış yapılmadı.";
else programAyarlari.fodaBilgisi.ltoplamGun.Text = "Henüz " + ((gun == 0)?gun + 1:gun) + " gün oldu.";
programAyarlari.fodaBilgisi.lToplamOdenecek.Text = (Convert.ToInt32(degiskenler.oku["O_FIYATI"]) * ((gun == 0)?gun + 1:gun)).ToString() + " ₺ Oda ücreti";
}
}
degiskenler.baglan.Close();
}
catch (Exception ex) { programAyarlari.hataVer("Beklenmedik bir hata", "Hata ayrıntılarını buradan görebilirsiniz.\n\n" + ex); }
try // ODA BİLGİLERİ GETİRTTİK
{
degiskenler.komut = new OleDbCommand("SELECT * FROM ODA where O_NU = @odaNu", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@odaNu", picHover.Name.Substring(1, 3).ToString());
islemler.kosulluVeriGetir(degiskenler.komut);
while (degiskenler.oku.Read())
{
programAyarlari.fodaBilgisi.checkBoxSuit.Checked = (Convert.ToBoolean(degiskenler.oku["O_SUIT"]));
programAyarlari.fodaBilgisi.checkBoxKlima.Checked = (Convert.ToBoolean(degiskenler.oku["O_KLIMA"]));
programAyarlari.fodaBilgisi.checkBoxTelevizyon.Checked = (Convert.ToBoolean(degiskenler.oku["O_TELEVIZYON"]));
programAyarlari.fodaBilgisi.checkBoxKapalı.Checked = (Convert.ToBoolean(degiskenler.oku["O_KAPALI"]));
programAyarlari.fodaBilgisi.labelOdaYatakSayisi.Text = degiskenler.oku["O_YATAK_SAYISI"].ToString();
programAyarlari.fodaBilgisi.labelGenisYatakSayisi.Text = degiskenler.oku["O_GENIS_YATAK_SAYISI"].ToString();
programAyarlari.fodaBilgisi.labelKat.Text = degiskenler.oku["O_KAT_NU"].ToString();
programAyarlari.fodaBilgisi.labelGecelikFiyat.Text = degiskenler.oku["O_FIYATI"].ToString() + " ₺";
}
degiskenler.baglan.Close();
}
catch (Exception ex) { programAyarlari.hataVer("Beklenmedik bir hata", "Hata ayrıntılarını buradan görebilirsiniz.\n\n" + ex); }
programAyarlari.fodaBilgisi.Show();
}
void pic_MouseLeave(object sender, EventArgs e)
{
programAyarlari.fodaBilgisi.Hide();
}
void pic_MouseMove(object sender, EventArgs e)
{
PictureBox p = sender as PictureBox;
double s = (MousePosition.X + 20) - programAyarlari.fodaBilgisi.Width - 30;
if (programAyarlari.fodalar.panel2.Width > 1300)
{
/* if (MousePosition.X + 20 > baglanti.fodalar.panel2.Width - p.Width * 2) baglanti.fodaBilgisi.Location = new Point(Convert.ToInt32(s), MousePosition.Y);
else baglanti.fodaBilgisi.Location = new Point(MousePosition.X + 20, MousePosition.Y);*/
if (MousePosition.X + 20 > programAyarlari.fodalar.panel2.Width - p.Width * 3.5) programAyarlari.fodaBilgisi.Location = new Point(Convert.ToInt32(s), MousePosition.Y);
else programAyarlari.fodaBilgisi.Location = new Point(MousePosition.X + 20, MousePosition.Y);
}
else programAyarlari.fodaBilgisi.Location = new Point(MousePosition.X + 20, MousePosition.Y);
}
TextBox t;
private void tChanged(object sender, EventArgs e)
{
t = sender as TextBox;
t.ForeColor = Color.Black;
if (t.Name == "tSifre") if (tSifre.Text != "Şifre") tSifre.PasswordChar = '*'; // Şifre girilmeye başlandığında karakter * olarak görünsün.
}
private void tClick(object sender, EventArgs e)
{
t = sender as TextBox;
if (t.Text == "Kullanıcı adı" || t.Text == "Şifre") t.Text = "";
}
private void tKeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsPunctuation(e.KeyChar)) e.Handled = true; // Bazı özel karakterler girilmesini engelledik.
if (e.KeyChar == ' ' || e.KeyChar == '+' || e.KeyChar == '^' || e.KeyChar == '=' || e.KeyChar == '|') e.Handled = true; // Ve bu karakterleride biz engelledik.
}
private void giris_FormClosed(object sender, FormClosedEventArgs e)
{
this.Dispose();
Application.ExitThread();
}
void dGvSutunlariAdlandirma(DataGridView d)
{
if (d.Name == "dGvMusteri")
{
d.Columns[0].HeaderText = "TC Kimlik";
d.Columns[1].HeaderText = "Adı Soyadı";
d.Columns[2].HeaderText = "Telefon";
d.Columns[3].HeaderText = "Adres";
d.Columns[4].HeaderText = "Kayıt Tarihi";
d.Columns[5].HeaderText = "Beraberindekiler";
d.ClearSelection();
}
else if (d.Name == "dGvKullanici")
{
d.Columns[0].HeaderText = "<NAME>";
d.Columns[1].HeaderText = "Kullanıcı adı";
d.Columns[2].HeaderText = "Şifre";
d.Columns[3].HeaderText = "Adı Soyadı";
d.Columns[4].HeaderText = "Doğum Tarihi";
d.Columns[5].HeaderText = "Telefon Numarası";
d.Columns[6].HeaderText = "Adres";
d.Columns[7].HeaderText = "Kişisel Bilgiler";
d.Columns[8].HeaderText = "Program yetkisi";
d.Columns[9].Visible = true;
d.ClearSelection();
}
else if (d.Name == "dGvOdaAyarlari")
{
d.Columns[0].HeaderText = "Nu";
d.Columns[1].HeaderText = "Kat";
d.Columns[2].HeaderText = "Yatak Sayısı";
d.Columns[3].HeaderText = "Geniş Yatak";
d.Columns[4].HeaderText = "Suit";
d.Columns[5].HeaderText = "Klima";
d.Columns[6].HeaderText = "Televizyon";
d.Columns[7].HeaderText = "Temiz";
d.Columns[8].HeaderText = "Kapalı";
d.Columns[9].HeaderText = "Fiyat";
d.ClearSelection();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using veriT;
namespace OTEL254
{
public partial class musteriler : Form
{
public musteriler()
{
InitializeComponent();
}
private void tSifirla()
{
tTC.Text = tAdSoyad.Text = tTel.Text = tAdres.Text = tBeraberindekiler.Text = "";
bMusteriEkle.Enabled = tTC.Enabled = true;
bDuzenle.Enabled = bMusteriSil.Enabled = false;
checkBox1.Checked = false;
dGvMusteri.ClearSelection();
}
private void musteriler_FormClosing(object sender, FormClosingEventArgs e)
{
tSifirla();
tAra.Text = "Tc kimlik numarası veya isme göre ara";
e.Cancel = true;
this.Hide();
programAyarlari.fmain.Show();
}
private void bDuzenle_Click(object sender, EventArgs e)
{ // BDUZENLEDE HATA VAR ONU ÇÖZ İLİŞKİLİ KAYITLAR SORUNU
if (tTC.Text == "" || tAdSoyad.Text == "" || tTel.Text == "" || tAdres.Text == "") programAyarlari.hataVer("Eksik bilgi girişi yapıldı.", "Müşteri bilgileri eksik. Lütfen boş alanları doldurunuz. ");
else
{
try
{
islemler.varsaKosulluVeriGuncelle("MUSTERI", "M_TC ='" + tTC.Text + "',M_ADI_SOYADI = '" + tAdSoyad.Text + "',M_TEL ='" + tTel.Text + "',M_ADRES = '" + tAdres.Text + "',M_BERABERINDEKILER = '" + tBeraberindekiler.Text + "' where M_TC = '" + tTC.Text + "'", "");
DataGridViewRow dr = dGvMusteri.CurrentRow;
dr.Cells[0].Value = tTC.Text;
dr.Cells[1].Value = tAdSoyad.Text;
dr.Cells[2].Value = tTel.Text;
dr.Cells[3].Value = tAdres.Text;
dr.Cells[5].Value = tBeraberindekiler.Text;
MessageBox.Show("Müşteri başarıyla düzenlendi","Başarı");
}
catch (Exception) { programAyarlari.hataVer("Bir hata gerçekleşti.", "Müşteri şuan düzenlenemez.\nLütfen müşterinin oda işlemleri bittikten sonra düzenleyiniz."); }
dGvMusteri.DataSource = degiskenler.ds.Tables["MUSTERI"];
dGvMusteri.Refresh();
tSifirla();
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
bDuzenle.Enabled = bMusteriSil.Enabled = true;
bMusteriEkle.Enabled = false;
try
{
tTC.Enabled = false;
tTC.Text = dGvMusteri.SelectedRows[0].Cells[0].Value.ToString();
tAdSoyad.Text = dGvMusteri.SelectedRows[0].Cells[1].Value.ToString();
tTel.Text = dGvMusteri.SelectedRows[0].Cells[2].Value.ToString();
tAdres.Text = dGvMusteri.SelectedRows[0].Cells[3].Value.ToString();
tBeraberindekiler.Text = dGvMusteri.SelectedRows[0].Cells[5].Value.ToString(); // sÜTUNLARI TEXTBOXLARA AKTARDIK
}
catch (Exception) { }
if (tTC.Text == "")
{
bDuzenle.Enabled = bMusteriSil.Enabled = false;
bMusteriEkle.Enabled = tTC.Enabled = true;
}
}
private void bMusteriEkle_Click(object sender, EventArgs e)
{
if (tTC.Text == "" || tAdSoyad.Text == "" || tTel.Text == "" || tAdres.Text == "") programAyarlari.hataVer("Eksik bilgi girişi yapıldı.", "Müşteri bilgileri eksik. Lütfen boş alanları doldurunuz. ");
else
{
// Yeni kayıt veri tabanına ekleme kodu
islemler.veriEkle("MUSTERI", "M_TC,M_ADI_SOYADI,M_TEL,M_ADRES,M_KAYIT_TARIHI,M_BERABERINDEKILER", "'" + tTC.Text + "','" + tAdSoyad.Text + "','" + tTel.Text + "','" + tAdres.Text + "','" + DateTime.Now.ToShortDateString() + "','" + tBeraberindekiler.Text + "'");
DataRow dr = degiskenler.ds.Tables["MUSTERI"].NewRow();
dr["M_TC"] = tTC.Text;
dr["M_ADI_SOYADI"] = tAdSoyad.Text;
dr["M_TEL"] = tTel.Text;
dr["M_ADRES"] = tAdres.Text;
dr["M_KAYIT_TARIHI"] = DateTime.Now.ToShortDateString();
dr["M_BERABERINDEKILER"] = tBeraberindekiler.Text;
degiskenler.ds.Tables["MUSTERI"].Rows.Add(dr);
programAyarlari.musteriSayisi++;
tSifirla();
}
}
private void bMusteriSil_Click(object sender, EventArgs e)
{
try
{
bool MusterininOdasiVarMi = false; // müşterinin odası var mı diye sorgulaacağız.
OleDbCommand musterininOdasıVarMi = new OleDbCommand("Select * from ODA_MUSTERI where OM_M_TC = @m_tc and CIKTI_MI = false", degiskenler.baglan);
musterininOdasıVarMi.Parameters.Add("@m_tc", tTC.Text); // Eğer oda müşteri tablosunda bu tc li kişi varsa
islemler.kosulluVeriGetir(musterininOdasıVarMi);
if (degiskenler.oku.Read()) MusterininOdasiVarMi = true; // Musterinin odası var mı true oluyor.
else MusterininOdasiVarMi = false; // yoksa false değeri dönecek
degiskenler.baglan.Close(); // bağlantıyı kapattık.
// Eğer müşteri varsa hatamızı veriyoruz. Henüz çıkış yapmamış bir müşteriyi silemezsiniz.Lütfen önce çıkış işlemlerini yapınız.
if (MusterininOdasiVarMi == true) MessageBox.Show("Henüz çıkış yapmamış bir müşteriyi silemezsiniz.\nLütfen önce çıkış işlemlerini yapınız.", "Uyarı!", MessageBoxButtons.OK,MessageBoxIcon.Warning);
else // Eğer müşterinin odası yoksa false ise
{
DialogResult diaRes = MessageBox.Show("Müşteri silinecek onaylıyor musunuz ?.", "Uyarı!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); // Müşteriyi silmek istiyor musunuz diye soruyoruz.
if (diaRes == DialogResult.Yes) // Eğer cevap evet ise
{
bool MusteriCiktiMi = false; // müşterinin odası var mı diye sorgulayacağız.
degiskenler.komut = new OleDbCommand("Select * from ODA_MUSTERI where OM_M_TC = @m_tc and CIKTI_MI = true", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@m_tc", tTC.Text); // Eğer oda müşteri tablosunda bu tc li kişi varsa
islemler.kosulluVeriGetir(degiskenler.komut);
if (degiskenler.oku.Read()) MusteriCiktiMi = true; // Musterinin odası var mı true oluyor.
else MusteriCiktiMi = false; // yoksa false değeri dönecek
degiskenler.baglan.Close(); // bağlantıyı kapattık.
if (MusteriCiktiMi == true) // Eğer müşteri çıkış yaptıysa silinebilir.
{
degiskenler.komut = new OleDbCommand("DELETE * FROM ODA_MUSTERI WHERE OM_M_TC = @m_tc", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@m_tc", tTC.Text);
islemler.kosulluVeriSil(degiskenler.komut);
}
// Daha sonra müşteriyi sildik.
degiskenler.komut = new OleDbCommand("DELETE * FROM MUSTERI WHERE M_TC = @m_tc", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@m_tc", tTC.Text);
islemler.kosulluVeriSil(degiskenler.komut);
dGvMusteri.Rows.Remove(dGvMusteri.SelectedRows[0]);
programAyarlari.musteriSayisi--;
/* degiskenler.ds.Tables["MUSTERI"].Rows.RemoveAt(dGvMusteri.CurrentRow.Cells[0].Value);
degiskenler.ds.Tables["MUSTERI"].Rows.Remove(dGvMusteri.CurrentRow.Cells[0]);*/
}
}
}
catch (Exception ex) { programAyarlari.hataVer("Beklenmedik bir hata", "Hata ayrıntılarını buradan görebilirsiniz.\n\n" + ex); }
dGvMusteri.DataSource = degiskenler.ds.Tables["MUSTERI"];
tSifirla();
dGvMusteri.ClearSelection();
bDuzenle.Enabled = bMusteriSil.Enabled = false;
bMusteriEkle.Enabled = true;
}
private void tAra_Click(object sender, EventArgs e) { tAra.Text = ""; }
private void tAra_TextChanged(object sender, EventArgs e)
{
if (tAra.Text == "")
{
dGvMusteri.DataSource = degiskenler.ds.Tables["MUSTERI"];
dGvMusteri.Refresh();
tSifirla();
} // Boşsa tüm veriler gelecek
else // Doluysa arama yapılacak.
{
OleDbDataAdapter oDataA = new OleDbDataAdapter("Select * From MUSTERI where M_TC like '%" + tAra.Text + "%' or M_ADI_SOYADI like '%" + tAra.Text + "%'", degiskenler.baglan);
programAyarlari.kosulluMusteriGetir("MUSTERI", dGvMusteri, oDataA);
dGvMusteri.ClearSelection();
//programAyarlari.musteriGetir("MUSTERI", programAyarlari.fmusteriler.dGvMusteri, "M_TC like '%" + tAra.Text + "%' or M_ADI_SOYADI like '%" + tAra.Text + "%'");
tSifirla();
}
}
private void musteriler_Load(object sender, EventArgs e)
{
programAyarlari.formBasligi(this, tSAciklama);// Form başlığını yazdırdık.
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{ //Belli tarihler arası kayıtları ara
if (checkBox1.Checked == true) // seçiliyse
{
tAra.Enabled = false;
groupBox1.Visible = true;
}
else // eğer seçili değilse
{
tAra.Enabled = true;
groupBox1.Visible = false;
dGvMusteri.DataSource = degiskenler.ds.Tables["MUSTERI"];
dGvMusteri.Refresh();
}
}
private void dTp_ValueChanged(object sender, EventArgs e)
{// tarihlerin değerleri değiştiğinde
if (checkBox1.Checked == true)
{
try
{
OleDbDataAdapter oDataA = new OleDbDataAdapter("Select * From MUSTERI where M_KAYIT_TARIHI >= @tarih1 and M_KAYIT_TARIHI <= @tarih2", degiskenler.baglan);
oDataA.SelectCommand.Parameters.Add("@tarih1", dTpBaslangic.Value.ToShortDateString());
oDataA.SelectCommand.Parameters.Add("@tarih2", dTpBitis.Value.ToShortDateString());
programAyarlari.kosulluMusteriGetir("MUSTERI", dGvMusteri, oDataA);
dGvMusteri.ClearSelection();
}
catch (Exception ex) { programAyarlari.hataVer("Beklenmedik bir hata\n", ex.ToString()); }
}
}
private void dGvMusteri_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using veriT;
namespace OTEL254
{
public partial class odaAyarlari : Form
{
public odaAyarlari()
{
InitializeComponent();
}
private void odaAyarlari_Load(object sender, EventArgs e)
{
comboBox_katNumarasi.SelectedIndex = comboBox_yatakSayisi.SelectedIndex = comboBox_genisYatakSayisi.SelectedIndex = 0;
programAyarlari.formBasligi(this, tSAciklama);
}
private void odaAyarlari_FormClosing(object sender, FormClosingEventArgs e)
{
comboBox_katNumarasi.SelectedIndex = comboBox_yatakSayisi.SelectedIndex = comboBox_genisYatakSayisi.SelectedIndex = 0;
tOda.Text = tOdaFiyati.Text = "";
checkBox_suit.Checked = checkBox_klima.Checked = checkBox_televizyon.Checked = checkBox_temiz.Checked = checkBox_kapali.Checked = false;
e.Cancel = true;
this.Hide();
programAyarlari.fmain.Show();
}
private void dGvOdaAyarlari_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
tOda.Text = dGvOdaAyarlari.SelectedRows[0].Cells[0].Value.ToString();
comboBox_katNumarasi.Text = dGvOdaAyarlari.SelectedRows[0].Cells[1].Value.ToString();
comboBox_yatakSayisi.Text = dGvOdaAyarlari.SelectedRows[0].Cells[2].Value.ToString();
comboBox_genisYatakSayisi.Text = dGvOdaAyarlari.SelectedRows[0].Cells[3].Value.ToString();
checkBox_suit.Checked = Convert.ToBoolean(dGvOdaAyarlari.SelectedRows[0].Cells[4].Value);
checkBox_klima.Checked = Convert.ToBoolean(dGvOdaAyarlari.SelectedRows[0].Cells[5].Value);
checkBox_televizyon.Checked = Convert.ToBoolean(dGvOdaAyarlari.SelectedRows[0].Cells[6].Value);
checkBox_temiz.Checked = Convert.ToBoolean(dGvOdaAyarlari.SelectedRows[0].Cells[7].Value);
checkBox_kapali.Checked = Convert.ToBoolean(dGvOdaAyarlari.SelectedRows[0].Cells[8].Value);
tOdaFiyati.Text = dGvOdaAyarlari.SelectedRows[0].Cells[9].Value.ToString();
}
catch (Exception) { }
}
private void button1_Click(object sender, EventArgs e)
{
try
{
islemler.veriEkle("ODA", "O_NU,O_KAT_NU,O_YATAK_SAYISI,O_GENIS_YATAK_SAYISI,O_SUIT,O_KLIMA,O_TELEVIZYON,O_TEMIZ,O_KAPALI,O_FIYATI", tOda.Text + "," + comboBox_katNumarasi.Text + "," + comboBox_yatakSayisi.Text + "," + comboBox_genisYatakSayisi.Text + "," + checkBox_suit.Checked + "," + checkBox_klima.Checked + "," + checkBox_televizyon.Checked + "," + checkBox_temiz.Checked + "," + checkBox_kapali.Checked + "," + tOdaFiyati.Text);
programAyarlari.tabloDoldur("ODA", programAyarlari.fodaAyarlari.dGvOdaAyarlari);
}
catch (Exception)
{
MessageBox.Show("Aynı oda ismi adı mevcut veya bu oda şuan eklenememektedir.\nLütfen daha sonra tekrar deneyiniz.", "Bir hatayla karşılaşıldı.");
}
}
private void bDuzenle_Click(object sender, EventArgs e)
{
try
{
islemler.varsaKosulluVeriGuncelle("ODA", "O_NU = " + tOda.Text + ",O_KAT_NU = " + comboBox_katNumarasi.Text + ",O_YATAK_SAYISI = " + comboBox_yatakSayisi.Text + ",O_GENIS_YATAK_SAYISI = " + comboBox_genisYatakSayisi.Text + ",O_SUIT = " + checkBox_suit.Checked + ",O_KLIMA = " + checkBox_klima.Checked + ",O_TELEVIZYON = " + checkBox_televizyon.Checked + ",O_TEMIZ = " + checkBox_temiz.Checked + ",O_KAPALI = " + checkBox_kapali.Checked + ",O_FIYATI = " + tOdaFiyati.Text, "O_NU = " + tOda.Text);
programAyarlari.tabloDoldur("ODA", programAyarlari.fodaAyarlari.dGvOdaAyarlari);
}
catch (Exception)
{
MessageBox.Show("Aynı oda ismi adı mevcut veya bu oda şuan eklenememektedir.\nLütfen daha sonra tekrar deneyiniz.", "Bir hatayla karşılaşıldı.");
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using veriT;
namespace OTEL254
{
public partial class kullanicilar : Form
{
public kullanicilar()
{
InitializeComponent();
}
private void tSifirla()
{
tTC.Text = tKadi.Text = tSifre.Text = tAdSoyad.Text = dTpDogumTarihi.Text = tTel.Text = tAdres.Text = tKisisel.Text = cYetki.Text = "";
bKullaniciEkle.Enabled = tKadi.Enabled = true;
cYetki.SelectedIndex = 1;
bDuzenle.Enabled = bMusteriSil.Enabled = false;
dGvKullanici.ClearSelection();
pResim.ImageLocation = @"resimler/default.png";
}
private void tAra_TextChanged(object sender, EventArgs e)
{
if (tAra.Text == "")
{
dGvKullanici.DataSource = degiskenler.ds.Tables["KULLANICILAR"];
tSifirla();
} // Boşsa tüm veriler gelecek
else // Doluysa arama yapılacak.
{
OleDbDataAdapter oDataA = new OleDbDataAdapter("Select * From KULLANICILAR where K_TC like '%" + tAra.Text + "%' or K_ADI_SOYADI like '%" + tAra.Text + "%' or K_KADI like '%" + tAra.Text + "%'", degiskenler.baglan);
programAyarlari.kosulluMusteriGetir("KULLANICILAR", dGvKullanici, oDataA);
dGvKullanici.ClearSelection();
tSifirla();
}
}
private void tAra_Click(object sender, EventArgs e)
{
tAra.Text = "";
}
private void bMusteriSil_Click(object sender, EventArgs e)
{
try
{
DialogResult diaRes = MessageBox.Show("Müşteri silinecek onaylıyor musunuz ?.", "Uyarı!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); // Müşteriyi silmek istiyor musunuz diye soruyoruz.
if (diaRes == DialogResult.Yes) // Eğer cevap evet ise
{
degiskenler.komut = new OleDbCommand("DELETE * FROM KULLANICILAR WHERE K_TC = @k_tc", degiskenler.baglan);
degiskenler.komut.Parameters.Add("@k_tc", tTC.Text);
islemler.kosulluVeriSil(degiskenler.komut);
dGvKullanici.Rows.Remove(dGvKullanici.SelectedRows[0]);
}
}
catch (Exception ex) { programAyarlari.hataVer("Beklenmedik bir hata", "Hata ayrıntılarını buradan görebilirsiniz.\n\n" + ex); }
tSifirla();
//dGvKullanici.DataSource = degiskenler.ds.Tables["KULLANICILAR"];
bDuzenle.Enabled = bMusteriSil.Enabled = false;
bKullaniciEkle.Enabled = tKadi.Enabled = true;
}
private void bKullaniciEkle_Click(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(tTC.Text) || String.IsNullOrWhiteSpace(tKadi.Text) || String.IsNullOrWhiteSpace(tSifre.Text) || String.IsNullOrWhiteSpace(tAdSoyad.Text) || String.IsNullOrWhiteSpace(dTpDogumTarihi.Text) || String.IsNullOrWhiteSpace(tTel.Text) || String.IsNullOrWhiteSpace(tAdres.Text) || String.IsNullOrWhiteSpace(pResim.ImageLocation.ToString()))
{
programAyarlari.hataVer("Eksik bilgi girişi yapıldı.", "Müşteri bilgileri eksik. Lütfen boş alanları doldurunuz. ");
}
else
{
// Yeni kayıt eklenecek
islemler.veriEkle("KULLANICILAR", "K_TC,K_KADI,K_SIFRE,K_ADI_SOYADI,K_DOGUM_TARIHI,K_TEL,K_ADRES,K_KISISEL_BILGILER,K_Y_ADI,K_RESIM", "'" + tTC.Text + "','" + tKadi.Text + "','" + tSifre.Text + "','" + tAdSoyad.Text + "','" + dTpDogumTarihi.Text + "','" + tTel.Text + "','" + tAdres.Text + "','" + tKisisel.Text + "','" + cYetki.Text + "','" + pResim.ImageLocation.ToString() + "'");
DataRow dataR = degiskenler.ds.Tables["KULLANICILAR"].NewRow();
dataR["K_TC"] = tTC.Text;
dataR["K_KADI"] = tKadi.Text;
dataR["K_SIFRE"] = tSifre.Text;
dataR["K_ADI_SOYADI"] = tAdSoyad.Text;
dataR["K_DOGUM_TARIHI"] = dTpDogumTarihi.Text;
dataR["K_TEL"] = tTel.Text;
dataR["K_ADRES"] = tAdres.Text;
dataR["K_KISISEL_BILGILER"] = tKisisel.Text;
dataR["K_Y_ADI"] = cYetki.Text;
dataR["K_RESIM"] = pResim.ImageLocation.ToString();
degiskenler.ds.Tables["KULLANICILAR"].Rows.Add(dataR);
MessageBox.Show("Müşteri başarıyla eklendi.", "Başarı");
tSifirla();
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
bDuzenle.Enabled = bMusteriSil.Enabled = true;
bKullaniciEkle.Enabled = tKadi.Enabled = false;
try
{
tTC.Text = dGvKullanici.SelectedRows[0].Cells[0].Value.ToString();
tKadi.Text = dGvKullanici.SelectedRows[0].Cells[1].Value.ToString();
tSifre.Text = dGvKullanici.SelectedRows[0].Cells[2].Value.ToString();
tAdSoyad.Text = dGvKullanici.SelectedRows[0].Cells[3].Value.ToString();
dTpDogumTarihi.Text = dGvKullanici.SelectedRows[0].Cells[4].Value.ToString();
tTel.Text = dGvKullanici.SelectedRows[0].Cells[5].Value.ToString();
tAdres.Text = dGvKullanici.SelectedRows[0].Cells[6].Value.ToString();
tKisisel.Text = dGvKullanici.SelectedRows[0].Cells[7].Value.ToString();
cYetki.Text = dGvKullanici.SelectedRows[0].Cells[8].Value.ToString();
if (dGvKullanici.SelectedRows[0].Cells[9].Value.ToString() == "") pResim.ImageLocation = @"resimler/default.png";
else pResim.ImageLocation = dGvKullanici.SelectedRows[0].Cells[9].Value.ToString();
}
catch (Exception) { }
}
private void bDuzenle_Click(object sender, EventArgs e)
{
if (tTC.Text == "" || tAdSoyad.Text == "" || tTel.Text == "" || tAdres.Text == "") programAyarlari.hataVer("Eksik bilgi girişi yapıldı.", "Müşteri bilgileri eksik. Lütfen boş alanları doldurunuz. ");
else
{
islemler.varsaKosulluVeriGuncelle("KULLANICILAR", "K_TC ='" + tTC.Text + "',K_KADI = '" + tKadi.Text + "',K_SIFRE = '" + tSifre.Text + "',K_ADI_SOYADI = '" + tAdSoyad.Text + "',K_DOGUM_TARIHI = '" + dTpDogumTarihi.Text + "',K_TEL ='" + tTel.Text + "',K_ADRES = '" + tAdres.Text + "',K_KISISEL_BILGILER = '" + tKisisel.Text + "',K_Y_ADI = '" + cYetki.Text + "',K_RESIM = '" + pResim.ImageLocation.ToString() + "' where K_KADI = '" + tKadi.Text + "'", "");
DataGridViewRow dr = dGvKullanici.CurrentRow;
dr.Cells[0].Value = tTC.Text;
dr.Cells[1].Value = tKadi.Text;
dr.Cells[2].Value = tSifre.Text;
dr.Cells[3].Value = tAdSoyad.Text;
dr.Cells[4].Value = dTpDogumTarihi.Text;
dr.Cells[5].Value = tTel.Text;
dr.Cells[6].Value = tAdres.Text;
dr.Cells[7].Value = tKisisel.Text;
dr.Cells[8].Value = cYetki.Text;
dr.Cells[9].Value = pResim.ImageLocation.ToString();
MessageBox.Show("Müşteri başarıyla düzenlendi.", "Başarı");
tSifirla();
}
}
private void kullanicilar_FormClosing(object sender, FormClosingEventArgs e)
{
tSifirla();
tAra.Text = "Tc kimlik numarası,kullanıcı adı veya isme göre ara";
e.Cancel = true;
this.Hide();
programAyarlari.fmain.Show();
}
private void kullanicilar_Load(object sender, EventArgs e)
{
programAyarlari.formBasligi(this, tSAciklama);// Form başlığını yazdırdık.
islemler.kosulsuzVeriGetir("select Y_ADI from YETKI");
while (degiskenler.oku.Read()) // Eğer okunuyorsa başarılıysa giriş yap
{
/* Giriş yapan kişinin profil bilgisi */
cYetki.Items.Add(degiskenler.oku["Y_ADI"].ToString());
}
degiskenler.baglan.Close();
cYetki.SelectedIndex = 1;
}
string resimYolu = ""; // Resim yolu değişkenimizi tanımladık.
private void bResimSec_Click(object sender, EventArgs e)
{
// p.ImageLocation == @"resimler/default.png";
// p.ImageLocation = veritabani.dr["film_resmi"].ToString(); // Ve picturebox a veritabanında ki film_in resmini ekranda gösterttik.
openFileDialog1.Title = "Resim seçiniz!"; // Resim seç dediğimizde açılan resim seçme ekranı başlığı
openFileDialog1.Filter = "(*.jpg)|*.jpg|(*.png)|*.png"; // Resim seç dediğimizde açılan resim seçme ekranı hangi uzantıları seçeceğimizi belirttik.
if (openFileDialog1.ShowDialog() == DialogResult.OK) // Eğer resim seçildiyse
{
resimYolu = openFileDialog1.FileName; // resim yoluna seçtiğimiz resmin yolunu attık.
Bitmap bmp = new Bitmap(resimYolu); // resim yolunu bitmapa çevirdik
//resmimizi picturebox1 de gösterdik
pResim.Image = Image.FromFile(resimYolu);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OTEL254
{
public partial class kayitlar : Form
{
public kayitlar()
{
InitializeComponent();
}
private void kayitlar_Load(object sender, EventArgs e)
{
programAyarlari.formBasligi(this, tSAciklama);// Form başlığını yazdırdık.
}
private void kayitlar_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Hide();
programAyarlari.fmain.Show();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using veriT;
namespace OTEL254
{
class programAyarlari
{
/* Formlar */
public static giris fgiris = new giris();
public static main fmain = new main();
public static programHK fprogramHK = new programHK();
public static profil fprofil = new profil();
public static ayarlar fayarlar = new ayarlar();
public static odalar fodalar = new odalar();
public static odaBilgisi fodaBilgisi = new odaBilgisi();
public static musteriler fmusteriler = new musteriler();
public static kullanicilar fkullanicilar = new kullanicilar();
public static musteriEkle fmusteriEkle = new musteriEkle();
public static yetki fyetki = new yetki();
public static telefonlar ftelefonlar = new telefonlar();
public static rezervasyonlar frezervasyonlar = new rezervasyonlar();
public static odaAyarlari fodaAyarlari = new odaAyarlari();
public static kayitlar fkayitlar = new kayitlar();
/* Mini Formlar */
public static miniOda fminiOda = new miniOda();
public static miniRezervasyon fminiRezervasyon = new miniRezervasyon();
public static miniMusteri fminiMusteri = new miniMusteri();
public static miniKayitlar fminiKayitlar = new miniKayitlar();
public static miniTel fminiTel = new miniTel();
public static miniProgramHK fminiProgramHK = new miniProgramHK();
/* Public Değişkenler */
public static string pAdi, pSurumu, pYapimci, pYapimciTel, pWebSite, pYenilikler, pArkaPlan, secilenOda,sMusteriTC,sOdaTutari, rezervasyonBtarihi;
public static int toplamOdaS = 0, doluOdaS = 0, bosOdaS = 0, musteriSayisi = 0, gun = 0, odaFiyati = 0;
public static Button secilen;
/* Kullanıcı bilgileri ve rütbe bilgileri */
public static string kAdi, kSifre, kRutbe, kTC, kAdiSoyadi, kDogumTarihi, kTel, kAdres, kKisiselBilgiler, kResim;
/* Kullanıcı bilgisi ve yetkileri */
public static bool programDuzeni, kullaniciIslemleri, yetkiLer, odaIslemleri, musteriIslemleri, girisCikisIslemleri, hasilatRaporuIslemleri;
public static void hataVer(string hataBasligi, string hataDetayi) { MessageBox.Show(hataDetayi, hataBasligi, MessageBoxButtons.OK, MessageBoxIcon.Error); }
public static void formBasligi(Form f, ToolStripStatusLabel t) // Formların rengibaşlıkları vs ayarlar
{
f.Text = pAdi ;
t.Text = pWebSite ;
}
public static void musteriGetir(string tabloadi, DataGridView d, string varSaKosul)
{
islemler.bagKontrol(); // Bağlantı kontrolü
degiskenler.adaptor = new OleDbDataAdapter("Select * From " + tabloadi + ((varSaKosul == "") ? varSaKosul : " where " + varSaKosul), degiskenler.baglan);// Sorguda ki tablo verilerini koşul varsa getir yoksa koşul boşsa tüm veriler.
degiskenler.adaptor.Fill(degiskenler.ds, tabloadi); // dataseti tabloadına göre doldur
d.DataSource = degiskenler.ds.Tables[tabloadi];
degiskenler.baglan.Close();
}
public static DataSet ds2 = new DataSet();
public static DataSet ds3 = new DataSet();
public static void kosulluMusteriGetir(string tabloadi, DataGridView d, OleDbDataAdapter oDa)
{
try
{
islemler.bagKontrol(); // Bağlantı kontrolü
ds2.Clear(); // dataset temizle
degiskenler.adaptor = oDa;// Sorguda ki tablo verilerini koşul varsa getir yoksa koşul boşsa tüm veriler.
degiskenler.adaptor.Fill(ds2, tabloadi); // dataseti tabloadına göre doldur
d.DataSource = ds2.Tables[tabloadi];
degiskenler.baglan.Close();
}
catch (Exception ex) { hataVer("Bir şeyler ters gitti.", "Beklenmedik bir hata gerçekleşti.\nHata ayrıntılarına aşağıdan ulaşabilirsiniz.\n" + ex.ToString()); } // Hata mesajı
}
public static void miniOdaDegerGetir()
{
programAyarlari.bosOdaS = (programAyarlari.toplamOdaS - programAyarlari.doluOdaS);
// Progressbar kodları
try { programAyarlari.fminiOda.chart1.Series["seriler"].Points.Clear(); }
catch (Exception) { }
programAyarlari.fminiOda.progressBar1.Value = (100 * programAyarlari.doluOdaS) / programAyarlari.toplamOdaS;
programAyarlari.fminiOda.lDoluluk.Text = "%" + ((100 * programAyarlari.doluOdaS) / programAyarlari.toplamOdaS).ToString(); // label doluya yazdık
if (programAyarlari.fminiOda.progressBar1.Value < 25) programAyarlari.fminiOda.progressBar1.BackColor = Color.Green;
else if (programAyarlari.fminiOda.progressBar1.Value > 25 && programAyarlari.fminiOda.progressBar1.Value < 50) programAyarlari.fminiOda.progressBar1.BackColor = Color.Yellow;
else if (programAyarlari.fminiOda.progressBar1.Value > 50 && programAyarlari.fminiOda.progressBar1.Value < 75) programAyarlari.fminiOda.progressBar1.BackColor = Color.LightSalmon;
else if (programAyarlari.fminiOda.progressBar1.Value > 75 && programAyarlari.fminiOda.progressBar1.Value < 100) programAyarlari.fminiOda.progressBar1.BackColor = Color.Red;
// chart kontrolü
programAyarlari.fminiOda.chart1.Series["seriler"].Points.Add(programAyarlari.bosOdaS).LegendText = programAyarlari.bosOdaS.ToString() + " Boş";
programAyarlari.fminiOda.chart1.Series["seriler"].Points[0].Color = Color.Green;
programAyarlari.fminiOda.chart1.Series["seriler"].Points.Add(programAyarlari.doluOdaS).LegendText = programAyarlari.doluOdaS + " Dolu";
programAyarlari.fminiOda.chart1.Series["seriler"].Points[1].Color = Color.Red;
// labellara yazma işlemi
programAyarlari.fminiOda.lToplam.Text = programAyarlari.toplamOdaS.ToString();
programAyarlari.fminiOda.lBos.Text = programAyarlari.bosOdaS.ToString(); // label doluya yazdık
programAyarlari.fminiOda.lDolu.Text = programAyarlari.doluOdaS.ToString(); // label doluya yazdık
}
public static DataSet tabloDS;
public static void tabloDoldur(string tabloAdi,DataGridView d)
{
tabloDS = new DataSet();
islemler.bagKontrol(); // Bağlantı kontrolü
tabloDS.Clear(); // dataset temizle
degiskenler.adaptor = new OleDbDataAdapter("Select * from " + tabloAdi, degiskenler.baglan);
degiskenler.adaptor.Fill(tabloDS, tabloAdi); // dataseti tabloadına göre doldur
d.DataSource = tabloDS.Tables[tabloAdi];
degiskenler.baglan.Close();
d.ClearSelection();
}
}
}
| 1716bc2c1a4074b4f7036bcf88f7ec28e13377d0 | [
"C#"
]
| 14 | C# | gunesnrllh/Otel-yonetim-sistemi | 29ae4f8ce9d6092cddf7d5abfbf9d7d2d76828a4 | 59bf92aab619ca00d95559ba0557e51e21de81d8 |
refs/heads/master | <file_sep><?php
namespace Containers;
use DataExtractor;
class GroupsContainer extends BaseContainer{
public static function get($selected, DataExtractor $extractor, $params = array()) {
$mode = $extractor->getMode();
return array_map(function($group) use ($extractor, $mode) {
if (empty($group['name'])) {
$column = ColumnsContainer::get($group, $extractor)['sql'];
$group['name'] = $column;
} else {
$group['name'] = is_numeric($group['name'])? ColumnsContainer::getById($group['name'], $extractor)['name'] : $group['name'];
}
return $group['name'];
}, $selected);
}
public static function construct($groups, DataExtractor $extractor, $params = array()) {
return implode(',' . $extractor->getSeparator() . ' ', $groups) . $extractor->getSeparator();
}
}<file_sep><?php
namespace Containers;
use DataExtractor;
class HavingsContainer extends BaseContainer {
static protected $conjunctions;
static protected $mode = DataExtractor::MYSQL_MODE;
public static function init($mode) {}
public static function get($selected, DataExtractor $extractor, $params = array()) {
static::init($extractor->getMode());
return FiltersContainer::get($selected, $extractor, $params, true);
}
public static function construct($havings, DataExtractor $extractor, $params = array()) {
return FiltersContainer::construct($havings, $extractor, $params);
}
}<file_sep><?php
global $CFG;
require_once($CFG->dirroot . '/local/intelliboard/locallib.php');
class DataExtractor
{
const MYSQL_MODE = 'mysqli';
const POSTGRES_MODE = 'pgsql';
private $requests = array();
private $scenarios;
private $arguments;
private $params;
private $rawValues;
private $separator = "\n";
private $mode = self::MYSQL_MODE;
public function __construct($scenarios, $arguments, $params, $settings, $mode = null)
{
$this->scenarios = $scenarios;
$this->rawValues = $arguments;
$this->params = $params;
$this->arguments = array();
if ($mode) {
$this->setMode($mode);
}
}
public function extract()
{
$result = array('response' => array());
foreach($this->scenarios as $key => $value) {
$result['response'][$key] = $this->getData($value);
}
if (!empty($this->params['debug'])) {
$result['debug'] = $this->requests;
}
return $result;
}
public function getData($scenario) {
global $DB;
$this->arguments = array();
$sql = $this->construct($scenario);
$values = $this->prepareArguments($sql, $this->arguments);
$data = $DB->get_records_sql($sql, $values);
$result['hasPrev'] = !empty($scenario['offset']);
if (!empty($this->params['pagination_numbers'])) {
$countSql = $this->count($sql);
$result['count'] = $DB->count_records_sql($countSql, $values);
$result['hasNext'] = !empty($scenario['offset']);
} else {
if (empty($scenario['limit']) || count($data) <= $scenario['limit']) {
$result['hasNext'] = false;
} else {
$result['hasNext'] = true;
array_pop($data);
}
$result['count'] = 0;
}
$result['data'] = $data;
$this->requests[] = array('sql' => $sql, 'arguments' => $values);
return $result;
}
public function construct($scenario) {
$data = $this->findElements($scenario);
$sql = $this->separator . 'SELECT '. $data['columns'];
if (!empty($scenario['tables'])) {
$sql .= ' FROM ' . $data['tables'];
}
if (!empty($scenario['filters'])) {
$sql .= ' WHERE ' . $data['filters'];
}
if (!empty($scenario['groups'])) {
$sql .= ' GROUP BY ' . $data['groups'];
}
if (!empty($scenario['orders'])) {
$sql .= ' ORDER BY ' . $data['orders'];
}
if (!empty($scenario['havings'])) {
$sql .= ' HAVING ' . $data['havings'];
}
if (!empty($scenario['limit'])) {
$sql .= ' LIMIT ' . (empty($this->params->pagination_numbers) && (empty($scenario['type']) || $scenario['type'] === 'table')? $scenario['limit'] + 1 : $scenario['limit']);
}
if (!empty($scenario['offset'])) {
$sql .= ' OFFSET ' . $scenario['offset'];
}
return $sql;
}
private function findElements($scenario) {
$result = array();
foreach ($scenario as $key => $value) {
$classname = 'Containers' . '\\' . ucfirst($key) . 'Container';
if (class_exists($classname)) {
$result[$key] = $classname::get($value, $this);
$result[$key] = $classname::construct($result[$key], $this);
}
}
return $result;
}
public function count($sql) {
$limitIndex = strripos($sql, 'limit');
if ($limitIndex !== false) {
$sql = substr($sql, 0, $limitIndex);
}
return 'SELECT COUNT(*) FROM (' . $sql . ') as result';
}
public function prepareArguments(&$sql, $arguments, $prefix = null) {
$result = array();
foreach($arguments as $key => $argument) {
if ($argument === null && $this->mode === static::POSTGRES_MODE) {
$sql = preg_replace('~\:' . $key .'\b~', 'NULL', $sql);
} else {
$result[$key] = $argument;
}
}
return $result;
}
public function getMode() {
return $this->mode;
}
public function setMode($mode) {
if (in_array($mode, array(self::MYSQL_MODE, self::POSTGRES_MODE))) {
$this->mode = $mode;
}
}
public function getArguments($key = null) {
if ($key) {
$key = str_replace(':', '', $key);
return $this->arguments[$key];
}
return $this->arguments;
}
public function getRawValue($key) {
return $this->rawValues[$key];
}
public function setArguments($key, $value) {
$key = str_replace(':', '', $key);
$this->arguments[$key] = $value;
}
public function getSeparator() {
return $this->separator;
}
}<file_sep><?php
/**
* Function for class auto loading
*
* @param string $class Class name for required class
* @return bool A status indicating that class has been loaded or not
*/
spl_autoload_register(function($class) {
$baseDir = __DIR__;
$path = $baseDir . '/' . str_replace('\\', '/', $class) . '.php';
if (file_exists($path)) {
require_once($path);
return true;
}
return false;
});
function d($arg, $stop = true, $backtrace = false) {
print "<pre>";
print "Debug info:";
var_dump($arg);
print "</pre>";
if ($backtrace) {
debug_print_backtrace();
}
if ($stop) {
die();
}
}
<file_sep><?php
namespace Containers;
use Helpers\FunctionHelper;
use Helpers\ArrayHelper;
use DataExtractor;
class FiltersContainer extends BaseContainer {
private static $conjunctions;
private static $operators;
private static $mode;
private static $filtersCount = 0;
public static function init($mode) {
if (static::$operators && static::$conjunctions && static::$mode === $mode) {
return;
}
static::$mode = $mode;
$operators = array(
1 => "=",
2 => ">",
3 => "<",
4 => "<>",
5 => function($param) {
return "BETWEEN " . $param . "from AND " . $param . "to";
},
6 => "IS NOT",
7 => function($param) {
if (is_array($param)) {
return "IN(" . implode(',',$param) . ")";
}
return "IN(" . $param . ")";
},
8 => "NOT IN",
9 => "IS",
10 => "NOT",
11 => "LIKE",
12 => ">=",
13 => "<=",
);
static::$conjunctions = array(
1 => 'AND',
2 => 'OR'
);
static::$operators = array_map(function($operator) use ($mode) {
if (is_array($operator)) {
$operator = $operator[$mode];
}
return $operator;
}, $operators);
}
public static function get($request, DataExtractor $extractor, $params = array(), $isHaving = false) {
static::init($extractor->getMode());
$selected = ($flag = ArrayHelper::is_indexed_array($request))? $request : array($request);
$result = array_map(function($filter) use ($extractor, &$filtersCount, $isHaving) {
$conjunction = isset($filter['conjunction'])? static::$conjunctions[$filter['conjunction']] : static::$conjunctions[1];
$filter = isset($filter['prop'])? $filter : array('prop' => $filter);
if (ArrayHelper::is_indexed_array($filter['prop'])) {
return array('prop' => static::get($filter['prop'], $extractor), 'conjunction' => $conjunction);
}
$prop = $isHaving && $extractor->getMode() === DataExtractor::MYSQL_MODE? ColumnsContainer::get($filter['prop'], $extractor)['name'] : ColumnsContainer::get($filter['prop'], $extractor)['sql'];
$placeholder = false;
if (isset($filter['value']['id'])) {
$placeholder = ColumnsContainer::get($filter['value'], $extractor)['sql'];
} else {
$id = ':filter' . static::$filtersCount;
static::$filtersCount++;
if (!isset($filter['value'])) {
$value = $extractor->getRawValue($filter['argument']);
} else {
$value = $filter['value'];
}
$extractor->setArguments($id, $value);
}
if (!isset($filter['operator'])) {
$filter['operator'] = !empty($value) && ArrayHelper::is_indexed_array($value)? array(7) : array(1);
}
if (!$placeholder) {
$checker = $extractor->getArguments($id);
if (in_array(5, $filter['operator'])) {
$extractor->setArguments($id . 'from', $checker['from']);
$extractor->setArguments($id . 'to', $checker['to']);
$placeholder = $id;
} elseif (in_array(7, $filter['operator'])) {
$value = array();
if (!is_array($checker)) {
$checker = array($checker);
}
foreach($checker as $key => $current) {
$deeper = $id . '_' . $key;
$extractor->setArguments($deeper, $current);
$value[] = $deeper;
}
$placeholder = $value;
static::ignoreCase($prop, $placeholder, $checker, $extractor);
} else if(in_array(11, $filter['operator'])) {
$extractor->setArguments($id, "%$checker%");
$placeholder = $id;
static::ignoreCase($prop, $placeholder, $checker, $extractor);
} else {
$placeholder = $id;
}
}
$operator = array_map(function($operator) {
return static::$operators[$operator];
}, $filter['operator']);
return compact('prop', 'operator', 'conjunction', 'placeholder');
}, $selected);
return $flag? $result : $result[0];
}
public static function construct($filters, DataExtractor $extractor, $params = array()) {
$filters = ArrayHelper::is_indexed_array($filters)? $filters : array($filters);
$processed = array_reduce($filters, function($carry, $filter) use ($extractor) {
if (ArrayHelper::is_indexed_array($filter['prop'])) {
return $carry . '(' . static::construct($filter['prop'], $extractor) . ')' . ' ' . $filter['conjunction'];
}
return $carry . ' ' . $filter['prop'] . ' ' . static::applyOperators($filter['operator'], $filter['placeholder']) . $extractor->getSeparator() .' ' . $filter['conjunction'];
}, '');
return trim($processed, 'ANDOR');
}
protected static function applyOperators($operators, $placeholder) {
$buffer = '';
foreach ($operators as $operator) {
if (FunctionHelper::is_anonym_function($operator)) {
$placeholder = $operator($placeholder);
} else {
$buffer .= $operator . ' ';
}
}
return $buffer . $placeholder;
}
protected static function ignoreCase(&$prop, &$value, $checker, DataExtractor $extractor) {
if (is_array($checker)) {
$flag = false;
foreach ($checker as $index => $item) {
if (is_string($item) && !is_numeric($item)) {
$flag = true;
$value[$index] = ColumnsContainer::applyModifier(10, $value[$index], $extractor);
}
}
if ($flag) {
$prop = ColumnsContainer::applyModifier(10, $prop, $extractor);
}
} else {
if (is_string($checker) && !is_numeric($checker)) {
$value = ColumnsContainer::applyModifier(10, $value, $extractor);
$prop = ColumnsContainer::applyModifier(10, $prop, $extractor);
}
}
}
public static function getOperator($id, DataExtractor $extractor) {
static::init($extractor->getMode());
return static::$operators[$id];
}
}<file_sep><?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This plugin provides access to Moodle data in form of analytics and reports in real time.
*
*
* @package local_intelliboard
* @copyright 2017 IntelliBoard, Inc
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @website http://intelliboard.net/
*/
$string['pluginname'] = 'Plug-in IntelliBoard.net';
$string['tracking_title'] = 'Monitoreo de tiempo';
$string['tracking'] = 'Monitoreo de sesión';
$string['dashboard'] = 'Dashboard';
$string['settings'] = 'Ajustes';
$string['adv_settings'] = 'Ajustes avanzados';
$string['intelliboardroot'] = 'IntelliBoard';
$string['report'] = 'Reporte';
$string['reports'] = 'Reportes';
$string['learners'] = 'Aprendices';
$string['courses'] = 'Cursos';
$string['load'] = 'Cargar';
$string['inactivity'] = 'Inactividad';
$string['inactivity_desc'] = 'Tiempo de inactividad del usuario (en segundos)';
$string['ajax'] = 'Frecuencia';
$string['ajax_desc'] = 'Frecuencia de almacenamiento de la sesión vía AJAX.O - AJAX desactivada (en segundos)';
$string['enabled'] = 'Monitoreo activado';
$string['enabled_desc'] = 'Activar monitoreo';
$string['trackadmin'] = 'Admins monitoreo';
$string['logs'] = 'Herramienta de migración';
$string['trackadmin_desc'] = 'Activar monitoreo para usuarios admin (no recomendado)';
$string['intelliboard:instructors'] = 'IntelliBoard [Instructor]';
$string['intelliboard:students'] = 'IntelliBoard [Estudiante]';
$string['intelliboard:view'] = 'IntelliBoard [Ver]';
$string['intelliboard:manage'] = 'IntelliBoard [Administrar]';
$string['intelliboard:competency'] = 'IntelliBoard [Competencia]';
$string['tls12'] = 'TLS v1.2';
$string['tls12_desc'] = 'Ajustes avanzados:TLS v1.2';
$string['sso'] = 'SSO link';
$string['sso_desc'] = 'SSO Link to IntelliBoard.net';
$string['ssomenu'] = 'SSO menu item';
$string['ssomenu_desc'] = 'SSO Link in navigation menu (for admins only)';
$string['server'] = 'Servidor IntelliBoard';
$string['server_usa'] = 'IntelliBoard USA';
$string['server_au'] = 'IntelliBoard Australia';
$string['server_eu'] = 'IntelliBoard Europa';
$string['filters'] = 'Filtros de Dashboard';
$string['filter1'] = 'Usuarios eliminados';
$string['filter2'] = 'Usuarios suspendidos';
$string['filter3'] = 'Usuario invitado';
$string['filter4'] = 'Filtro curso';
$string['filter5'] = 'Filtro método inscripción';
$string['filter6'] = 'Filtro inscripción usuario';
$string['filter7'] = 'Filtro actividades/recursos';
$string['filter8'] = 'Filtro usuarios inscritos';
$string['filter1_desc'] = 'Mostrar usuarios eliminados';
$string['filter2_desc'] = 'Mostrar usuarios suspendidos';
$string['filter3_desc'] = 'Mostrar [invitar] usuario en reportes';
$string['filter4_desc'] = 'Mostrar cursos no visibles';
$string['filter5_desc'] = 'Mostrar métodos de inscripción no activos';
$string['filter6_desc'] = 'Mostrar usuarios con estado de inscripción no activos';
$string['filter7_desc'] = 'Mostrar actividades/recursos no visibles';
$string['filter8_desc'] = 'Mostrar sólo usuarios inscritos (no recomendado)';
$string['intelliboardaccess'] = 'Ud. no tiene permiso para visualizar esta página.Por favor contacte a su Administrador de Sistema.';
$string['tex1'] = 'Dashboard del Aprendiz IntelliBoard no habilitado.';
$string['account'] = 'Información de suscripción';
$string['te12'] = 'Nombre';
$string['te13'] = 'Apellido';
$string['te1'] = 'Correo';
$string['te1_desc'] = 'Ingrese su correo utilizado con suscripción IntelliBoard.net.Si no tiene una suscripción activa, por favor regístrese en <a target="_blank" href="https://intelliboard.net">IntelliBoard.net</a>.Learner and Instructor Dashboard están disponibles con una suscripción de Nivel 4 y superior.';
$string['n1'] = 'Información [Progreso del Aprendiz]';
$string['n2'] = 'Información [Progreso de Notas]';
$string['n3'] = 'Información [Progreso de Actividad]';
$string['n4'] = 'Información [Totales]';
$string['n5'] = 'Progreso actual';
$string['n6'] = 'Widget:Correlaciones';
$string['n7'] = 'Widget:Utilización de Evento';
$string['n8'] = 'Página de Curso';
$string['n9'] = 'Página de Reportes';
$string['n10'] = 'Dashboard Instructor';
$string['n11'] = 'Texto alternativo para menú de navegación';
$string['ts1'] = 'Dashboard del Aprendiz';
$string['ts2'] = 'Dashboard Página del Aprendiz';
$string['ts3'] = 'Dashboard Cursos del Aprendiz';
$string['ts4'] = 'Dashboard Notas del Aprendiz';
$string['ts5'] = 'Dashboard Reportes del Aprendiz';
$string['learner_tf_last_week'] = 'Time filter: Last Week';
$string['t01'] = 'Filtro tiempo:Último mes';
$string['t02'] = 'Filtro tiempo:Último trimestre';
$string['t03'] = 'Filtro tiempo:Último semestre';
$string['t04'] = 'Habilitar cursos completados [título]';
$string['t05'] = 'Habilitar cursos en progreso [título]';
$string['t06'] = 'Habilitar nota promedio de cursos [título]';
$string['t07'] = 'Habilitar Mensajes [título]';
$string['t08'] = 'Habilitar nota suma de cursos [título]';
$string['t09'] = 'El instructor puede ver a sus propios alumnos';
$string['t1'] = 'Habilitar Dashboard del Aprendiz';
$string['t2'] = 'Habilitar Dashboard';
$string['t3'] = 'Habilitar cursos';
$string['t4'] = 'Habilitar notas';
$string['t48'] = 'Habilitar reportes';
$string['t5'] = 'Habilitar gráfico [Progreso de actividad]';
$string['t6'] = 'Habilitar gráfico [Progreso del curso]';
$string['t7'] = 'Habilitar [Mi promedio en el curso]';
$string['t8'] = 'Habilitar [Promedio general del curso]';
$string['t9'] = 'Habilitar widget [Tareas]';
$string['t10'] = 'Habilitar widget [Quizzes]';
$string['t11'] = 'Habilitar widget [Progreso del curso]';
$string['t12'] = 'Habilitar widget [Participación en actividad]';
$string['t13'] = 'Habilitar widget [Aprendizaje]';
$string['t14'] = 'Habilitar widget [Éxito del curso]';
$string['t15'] = 'Habilitar widget [Correlaciones]';
$string['t16'] = 'Habilitar profesor del curso';
$string['t17'] = 'Habilitar categoría del curso';
$string['t18'] = 'Habilitar conclusión del curso';
$string['t19'] = 'Habilitar nota del curso';
$string['t20'] = 'Habilitar promedio de la clase en el curso';
$string['t21'] = 'Habilitar tiempo invertido en el curso';
$string['t22'] = 'Habilitar fecha de inicio del curso';
$string['t23'] = 'Habilitar columna [Fecha de inicio del curso]';
$string['t24'] = 'Habilitar columna [Fecha inscrito]';
$string['t25'] = 'Habilitar columna [Progreso]';
$string['t26'] = 'Habilitar columna [Carta]';
$string['t27'] = 'Habilitar columna [Actividades completadas]';
$string['t28'] = 'Habilitar columna [Puntuación]';
$string['t29'] = 'Habilitar columna estatus [Conclusión del Curso]';
$string['t30'] = 'Habilitar columna [Notas de actividad]';
$string['t31'] = 'Habilitar columna widget [Tareas][Nota]';
$string['t32'] = 'Habilitar columna widget [Tareas][Fecha límite]';
$string['t33'] = 'Habilitar columna widget [Quizzes][Nota]';
$string['t34'] = 'Habilitar columna widget [Quizzes][Notas]';
$string['t35'] = 'Habilitar columna widget [Progreso del Curso][Progreso]';
$string['t36'] = 'Habilitar columna widget [Progreso del Curso][Nota]';
$string['t37'] = 'Habilitar columna widget [Progreso del Curso][Inscrito]';
$string['t38'] = 'Habilitar columna widget [Progreso del Curso][Completado]';
$string['t52'] = 'Habilitar fila widget [Progreso del Curso][Categoría]';
$string['t39'] = 'Habilitar opción [Progreso][Nota Objetivos]';
$string['t40'] = 'Habilitar opción [Progreso][Promedio Clase]';
$string['t41'] = 'Habilitar columna Completado el [Título Notas de actividad]';
$string['t42'] = 'Habilitar columna Último acceso al curso [Título Notas de actividad]';
$string['t43'] = 'Habilitar columna Tipo [Notas de actividad]';
$string['t44'] = 'Habilitar columna Puntuación [Notas de actividad]';
$string['t45'] = 'Habilitar columna Notas [Notas de actividad]';
$string['t46'] = 'Habilitar columna Completado [Notas de actividad]';
$string['t47'] = 'Color de fondo de cursos [grid]';
$string['t49'] = 'Columnas de filtrado de reportes';
$string['t50'] = 'Roles de profesor';
$string['t51'] = 'Roles de estudiante';
$string['current_grade'] = 'Nota actual';
$string['average_grade'] = 'Nota promedio';
$string['type_here'] = 'Escriba aquí...';
$string['enrolled_date'] = 'Fecha inscripción';
$string['teacher'] = 'Profesor';
$string['category'] = 'Categoría';
$string['current_grade'] = 'Nota actual';
$string['completion'] = 'Logro';
$string['class_average'] = 'Promedio de la clase';
$string['time_spent'] = 'Tiempo invertido';
$string['completed_on'] = 'Completado el {$a}';
$string['last_access_on_course'] = 'Último acceso al curso: {$a}';
$string['you_have_certificates'] = 'Ud. tiene certificados{$a}';
$string['close'] = 'Cerrar';
$string['view_course_details'] = 'Ver detalles del curso';
$string['incomplete'] = 'Incompleto';
$string['return_to_grades'] = 'Volver a Calificaciones';
$string['grade'] = 'Calificación';
$string['last_week'] = 'Última semana';
$string['last_month'] = 'Último mes';
$string['last_quarter'] = 'Último trimestre';
$string['last_semester'] = 'Último semestre';
$string['activity_progress'] = 'Progreso de la actividad';
$string['course_progress'] = 'Progreso del curso';
$string['my_course_average_all'] = 'Mi promedio del curso (todos los cursos)';
$string['overall_course_average'] = 'Promedio global del curso (todos los aprendices; todos los cursos))';
$string['assignments'] = 'Tareas';
$string['quizzes'] = 'Quizzes';
$string['assignment_name'] = 'Nombre tarea';
$string['due_date'] = 'Fecha límite';
$string['no_data'] = 'Sin datos';
$string['quiz_name'] = 'Nombre del quiz';
$string['all_courses'] = 'Todos los cursos';
$string['time_period_due'] = 'Período (Fecha límite)';
$string['all_data'] = 'Todos los datos';
$string['progress'] = 'Progreso';
$string['enrolled'] = 'Inscrito';
$string['completed'] = 'Completado el';
$string['activity_participation'] = 'Participación en actividad';
$string['learning'] = 'Aprendizaje';
$string['course_success'] = 'Éxito del curso';
$string['correlations'] = 'Correlaciones';
$string['course_start_date'] = 'Fecha de inicio del curso';
$string['letter'] = 'Carta';
$string['completed_activities'] = 'Actividades completadas';
$string['score'] = 'Puntuación';
$string['course_completion_status'] = 'Estatus de conclusión del curso';
$string['activity_grades'] = 'Notas de actividad';
$string['completion_is_not_enabled'] = 'Conclusión no habilitada para este curso';
$string['activities'] = 'Actividades';
$string['activity_name'] = 'Nombre actividad';
$string['type'] = 'Tipo';
$string['graded'] = 'Calificado';
$string['completed_courses'] = 'Cursos completados';
$string['courses_in_progress'] = 'Cursos en progreso';
$string['courses_avg_grade'] = 'Nota promedio de cursos';
$string['courses_sum_grade'] = 'Curso Suma Grado por Valor de Escala de Grado';
$string['grades'] = 'Notas';
$string['messages'] = 'Mensajes';
$string['x_completions'] = '{$a} Logros';
$string['completion_status'] = 'Estatus de conclusión';
$string['users_activity'] = 'Actividad del usuario';
$string['daily'] = 'Diaria';
$string['weekly'] = 'Semanal';
$string['monthly'] = 'Mensual';
$string['number_of_sessions'] = 'Número de sesiones';
$string['number_today'] = '{$a} hoy';
$string['number_this_week'] = '{$a} esta semana';
$string['course_completions'] = 'Cursos concluidos';
$string['user_enrolments'] = 'Inscripciones del usuario';
$string['users'] = 'Usuarios';
$string['modules'] = 'Módulos';
$string['categories'] = 'Categorías';
$string['total'] = 'Total';
$string['users_overview'] = 'Información de usuarios';
$string['enable_time_and_visits_users_overview'] = 'Habilitar tiempo invertido y visitas en Información de usuarios';
$string['disable_time_and_visits_users_overview'] = 'Inhabilitar tiempo invertido y visitas en Información de usuarios';
$string['loading'] = 'Cargando...';
$string['enrollments'] = 'Inscripciones';
$string['registrations'] = 'Registros';
$string['participation'] = 'Participación';
$string['time'] = 'Tiempo';
$string['enrolment_method'] = 'Método de inscripción';
$string['intelliBoard_migration_tool'] = 'Herramienta de Migración IntelliBoard';
$string['importing_totals'] = 'Totales de importaciones';
$string['total_numbers'] = 'Fecha: {$a->timepoint}, Sesiones: {$a->sessions}, Visitas: {$a->visits}, Tiempo invertidos: {$a->timespend}';
$string['total_numbers2'] = 'USUARIO:: {$a->userid}, Página: {$a->page}, Param:{$a->param}, Visitas: {$a->visits}, Tiempo invertido: {$a->timespend}';
$string['total_numbers3'] = '----Fecha: {$a->timecreated}, Monitorear ID: {$a->trackid}, Visitas: {$a->visits}, iempo invertido: {$a->timespend}';
$string['logs_to_process'] = 'Registros por procesar {$a}';
$string['please_wait_or_cancel'] = 'Por favor espere para continuar o <a href="{$a}">Cancelar</a>';
$string['done'] = 'Listo!';
$string['return_to_home'] = 'Volver a Inicio';
$string['importing_logs'] = 'Importar registros';
$string['intelliBoard_migration_tool_info'] = 'La herramienta de migración IntelliBoard se utiliza para migrar los datos históricos de la tabla de registros de Moodle hacia el nuevo formato.Por favor tenga en cuenta que el procedimiento de almacenamiento de los registros de Moodle no cambiará.Una vez completada la migración de los datos históricos hacia el nuevo formato, valores históricos como \'Tiempo invertido\' y \'Visitas\' estarán disponibles para visualización en IntelliBoard.net.';
$string['moodle_logs'] = 'Registros Moodle';
$string['intelliboard_tracking'] = 'Monitoreo IntelliBoard';
$string['intelliboard_logs'] = 'Registros IntelliBoard';
$string['intelliboard_totals'] = 'Totales IntelliBoard';
$string['intelliboard_start_tracking'] = 'Monitoreo de inicio IntelliBoard';
$string['total_values_include'] = 'Los valores totales incluyen sesiones únicas, cursos, visitas, tiempo invertido.';
$string['items_per_query'] = 'Elementos por consulta';
$string['import'] = 'Importar';
$string['log_values_include'] = 'Los valores de registro incluyen registros para cada usuario por día.';
$string['powered_by'] = 'Powered by <a href="https://intelliboard.net/">IntelliBoard.net</a>';
$string['intelliboardnet'] = 'IntelliBoard.net';
$string['visits'] = 'Visitas';
$string['registered'] = 'Registrado';
$string['disabled'] = 'Inhabilitado';
$string['enrolled_completed'] = 'Inscritos: {$a->courses}, Completado: {$a->completed_courses}';
$string['enrolled_users_completed'] = 'Usarios inscritos: {$a->users}, Completado: {$a->completed}';
$string['user_grade_avg'] = '{$a->user} Nota: {$a->grade}, Nota promedio: {$a->avg_grade_site})';
$string['user_visit_avg'] = '{$a->user} Visitas: {$a->visits}, Visitas promedio: {$a->avg_visits_site}';
$string['user_time_avg'] = '{$a->user} Tiempo: {$a->timespend}, Tiempo promedio: {$a->avg_timespend_site}';
$string['more_users'] = 'Más usuarios';
$string['more_courses'] = 'Más cursos';
$string['showing_1_to_10'] = 'Mostrar 1 ta 10';
$string['course_grade'] = 'Nota del curso';
$string['completed_activities_resourses'] = 'Actividades/recursos completados';
$string['save'] = 'Guardar';
$string['help'] = '¿Necesita ayuda?';
$string['in1'] = 'Información general';
$string['in2'] = 'Progreso actual';
$string['in3'] = 'Total Cursos';
$string['in4'] = 'Total Aprendices';
$string['in5'] = 'Notas totales del curso';
$string['in6'] = 'Aprendices completos';
$string['in7'] = 'Aprendices incompletos';
$string['in8'] = 'Nota promedio del aprendiz';
$string['in9'] = 'Correlaciones';
$string['in10'] = 'Utilización de evento';
$string['in11'] = 'Progreso del aprendiz';
$string['in12'] = 'Progreso de calificación';
$string['in13'] = 'Tiempo invertido (%)';
$string['in14'] = '% Progreso';
$string['in15'] = 'Logros Aprendiz';
$string['in16'] = 'Último acceso';
$string['in17'] = 'Tiempo total invertido';
$string['in18'] = 'Visitas totales';
$string['in19'] = 'Nota promedio';
$string['in20'] = 'Volver a Aprendices';
$string['in201'] = 'Volver a Actividades';
$string['in21'] = 'Nota promedio del curso';
$string['in22'] = 'Habilitado';
$string['in23'] = 'No hay aprendices para mostrar.';
$string['in24'] = 'Módulos';
$string['in25'] = 'Nota aprobatoria';
$string['status'] = 'Estado';
$string['course_category'] = 'Categoría del curso';
$string['course_started'] = 'Curso iniciado';
$string['total_time_spent_enrolled_learners'] = 'Tiempo total invertido por aprendices inscritos en curso';
$string['total_visits_enrolled_learners'] = 'Visitas totales por aprendices inscritos en curso';
$string['learners_enrolled'] = 'Aprendiz inscrito';
$string['learning_progress'] = 'Progreso del aprendizaje';
$string['sections'] = 'Secciones';
$string['section'] = 'Sección';
$string['total_activities_resources'] = 'Recursos/actividades totales';
$string['completions'] = 'Logros';
$string['return_to_courses'] = 'Volver a Cursos';
$string['click_link_below_support_pages'] = 'Haga clic en el siguiente link para acceder a las páginas de soporte de IntelliBoard:';
$string['support'] = 'Soporte';
$string['course_name'] = 'Nombre del curso';
$string['enrolled_completed_learners'] = 'Aprendices inscritos/completados';
$string['activities_resources'] = 'Actividades/recursos';
$string['actions'] = 'Acciones';
$string['learner_name'] = 'Nombre Aprendiz';
$string['completed_activities_resources'] = 'Actividades/recursos completados';
$string['a31'] = 'Marcos';
$string['a32'] = 'Planes de aprendizaje';
$string['a33'] = 'Calificado, proficiente';
$string['a34'] = 'Calificado, no proficiente';
$string['a35'] = 'No calificado';
$string['a36'] = 'Descripción de competencia';
$string['a37'] = 'No ha creado una competencia.Por favor contacte a su Administrador de Sistema';
$string['a38'] = 'Cursos vinculados a competencias';
$string['a39'] = 'Competencias totales';
$string['a40'] = 'Cursos vinculados';
$string['no_competency'] = 'Parece que usted no tiene las competencias habilitadas para su sitio.';
$string['a0'] = 'Dashboard Competencias';
$string['a1'] = 'Competencias';
$string['a2'] = 'Proficiencia';
$string['a3'] = 'Actividades asignadas';
$string['a4'] = 'Progreso de Proficiencia';
$string['a5'] = 'Competencias evaluadas';
$string['a6'] = '# de Evidencias';
$string['a7'] = 'Estudiantes calificados';
$string['a8'] = 'Progreso';
$string['a9'] = 'Estudiantes competentes';
$string['a10'] = 'Aprendiz inscrito';
$string['a11'] = 'Lista de competencias asignadas al curso';
$string['a12'] = 'Aprendices inscritos';
$string['a13'] = 'Nombre de la Competencia';
$string['a14'] = 'Creado en';
$string['a15'] = 'Asignado en';
$string['a16'] = 'Proficiente Indiceted';
$string['a17'] = 'Clasificación';
$string['a18'] = 'Competencias Proficiente';
$string['a19'] = 'Fecha Competencias Clasificación';
$string['a20'] = 'Apreciador de Competencias';
$string['a21'] = 'Actividades asignadas';
$string['a22'] = 'Competencia adquirida';
$string['a23'] = 'Competencias calificadas';
$string['a24'] = '# de Evidencias';
$string['a25'] = 'Aprendices completos';
$string['a27'] = ' de ';
$string['a28'] = 'Detalles';
$string['a29'] = 'Habilitar Dashboard Competencias';
$string['a30'] = 'Habilitar reportes de competencias';
$string['a26'] = 'Esta tabla muestra el número de competencias asignadas a un curso, los alumnos que han sido calificados (competentes o no) y los alumnos que han sido designados competentes en la competencia.';
$string["n12"] = "Resumen [Resumen del curso]";
$string["n13"] = "Total de estudiantes";
$string["n14"] = "Widget: Participación de los estudiantes";
$string["n15"] = "Widget: Utilización de la actividad";
$string["n16"] = "Widget: Utilización del tema";
$string["passed"] = "Aprobado";
$string["failed"] = "Fallado";
$string["in26"] = "Participación de los estudiantes";
$string["in27"] = "Total de estudiantes";
$string["in28"] = "Tiempo promedio gastado";
$string["in29"] = "Estudiantes Activos";
$string["in30"] = "Estudiantes inactivos";
$string["in31"] = "Utilización de la actividad";
$string["in32"] = "Tiempo promedio en el período seleccionado";
$string["in33"] = "Utilización del tema";
$string["learners_enrolled_period"] = "Estudiantes matriculados dentro del período seleccionado";
$string["filter_dates"] = "Filtrar fechas:";
$string["select_date"] = "Seleccionar fechas";
$string["course_overview"] = "Resumen del curso";
$string["topics"] = "Temas";
$string["scalesettings"] = "Ajustes de escala";
$string["scales"] = "Habilitar escala personalizada";
$string["scale_raw"] = "Desactivar escala";
$string['scale_real'] = 'Mostrar porcentaje real en lugar de porcentaje';
$string["scale_total"] = "Grado total";
$string["scale_value"] = "Valor";
$string["scale_percentage"] = "Porcentaje";
$string["s25"] = "Tiempo dedicado a la actividad";
$string["s45"] = "Actividad";
$string["s46"] = "Porcentaje de estudiantes que intentaron";
$string["s47"] = "Tema";
$string["s48"] = "Tiempo dedicado al tema";
$string['passed_on'] = 'Completado (aprobado) {$a}';
$string['failed_on'] = 'Completado (fallado) en {$a}';
$string['completions'] = 'Estado de finalización de la actividad';
$string['completions_completed'] = 'Estado de finalización (completado)';
$string['completions_pass'] = 'Estado de finalización (pasar)';
$string['completions_fail'] = 'Estado de finalización (falla)';
$string['completions_desc'] = '1) El usuario ha completado esta actividad. No se especifica si han pasado o fallado. <br>
2) El usuario ha completado esta actividad con un grado por encima de la calificación de aprobado. <br>
3) El usuario ha completado esta actividad, pero su calificación es menor que la calificación de aprobado.';
$string['reportselect'] = 'Please select at least one report from App.IntelliBoard.net. Click on a Report, then Report Settings, and select it in "Visible in Moodle".';
$string['monitorselect'] = 'Please select at least one monitor from App.IntelliBoard.net. Click on a Monitors, then Monitors Settings, and select it in "Visible in Moodle".';
$string['privacy:metadata:local_intelliboard_assign:rel'] = 'Rel type of record';
$string['privacy:metadata:local_intelliboard_assign:type'] = 'Moodle Instance Type';
$string['privacy:metadata:local_intelliboard_assign:instance'] = 'Connected Moodle Instance ID';
$string['privacy:metadata:local_intelliboard_assign:timecreated'] = 'Records Timestamp';
$string['privacy:metadata:local_intelliboard_details:logid'] = 'Table ID [local_intelliboard_logs]';
$string['privacy:metadata:local_intelliboard_details:visits'] = 'The number of visits, mouse clicks, per day';
$string['privacy:metadata:local_intelliboard_details:timespend'] = 'The amount of time spent per hour';
$string['privacy:metadata:local_intelliboard_details:timepoint'] = 'The hour';
$string['privacy:metadata:local_intelliboard_logs:trackid'] = 'The ID of the table [local_intelliboard_tracking]';
$string['privacy:metadata:local_intelliboard_logs:visits'] = 'Visits, mouse clicks, per day';
$string['privacy:metadata:local_intelliboard_logs:timespend'] = 'Timespent, per day';
$string['privacy:metadata:local_intelliboard_logs:timepoint'] = 'Timestamp of day in year';
$string['privacy:metadata:local_intelliboard_totals:sessions'] = 'Total Number of User Sessions in Moodle';
$string['privacy:metadata:local_intelliboard_totals:courses'] = 'Total Courses in Moodle';
$string['privacy:metadata:local_intelliboard_totals:visits'] = 'Total Visits by all Ssers in Moodle';
$string['privacy:metadata:local_intelliboard_totals:timespend'] = 'Total Users Timespent in Moodle';
$string['privacy:metadata:local_intelliboard_totals:timepoint'] = 'Timestamp of day in year';
$string['privacy:metadata:local_intelliboard_tracking:userid'] = 'User ID who visits Moodle Page.';
$string['privacy:metadata:local_intelliboard_tracking:courseid'] = 'Course ID that User Visits';
$string['privacy:metadata:local_intelliboard_tracking:page'] = 'Page Type [course,module,profile,site]';
$string['privacy:metadata:local_intelliboard_tracking:param'] = 'Page ID Type';
$string['privacy:metadata:local_intelliboard_tracking:visits'] = 'Users Visits on a Page';
$string['privacy:metadata:local_intelliboard_tracking:timespend'] = 'Users Timespent on a Page';
$string['privacy:metadata:local_intelliboard_tracking:firstaccess'] = 'Users First Access';
$string['privacy:metadata:local_intelliboard_tracking:lastaccess'] = 'Users Last Access';
$string['privacy:metadata:local_intelliboard_tracking:useragent'] = 'Users Browser Type';
$string['privacy:metadata:local_intelliboard_tracking:useros'] = 'Users Operating System';
$string['privacy:metadata:local_intelliboard_tracking:userlang'] = 'Users Browser Language';
$string['privacy:metadata:local_intelliboard_tracking:userip'] = 'Users Last IP address';
$string['privacy:metadata:local_intelliboard_ntf:id'] = 'Notification ID';
$string['privacy:metadata:local_intelliboard_ntf:type'] = 'Notification type';
$string['privacy:metadata:local_intelliboard_ntf:externalid'] = 'Notification ExternalNID';
$string['privacy:metadata:local_intelliboard_ntf:userid'] = 'Notification ExternalAppID';
$string['privacy:metadata:local_intelliboard_ntf:email'] = 'Notification email';
$string['privacy:metadata:local_intelliboard_ntf:cc'] = 'Notification cc';
$string['privacy:metadata:local_intelliboard_ntf:subject'] = 'Notification subject';
$string['privacy:metadata:local_intelliboard_ntf:message'] = 'Notification message';
$string['privacy:metadata:local_intelliboard_ntf:state'] = 'Notification status';
$string['privacy:metadata:local_intelliboard_ntf:attachment'] = 'Notification attachment';
$string['privacy:metadata:local_intelliboard_ntf:tags'] = 'Notification tags';
$string['privacy:metadata:local_intelliboard_ntf_hst:id'] = 'Notification history ID';
$string['privacy:metadata:local_intelliboard_ntf_hst:notificationid'] = 'Notification ID';
$string['privacy:metadata:local_intelliboard_ntf_hst:userid'] = 'Notification ExternalAppID';
$string['privacy:metadata:local_intelliboard_ntf_hst:notificationname'] = 'Notification name';
$string['privacy:metadata:local_intelliboard_ntf_hst:email'] = 'Notification history email';
$string['privacy:metadata:local_intelliboard_ntf_hst:timesent'] = 'Notification history timestamp';
$string['select_manager_role'] = 'Seleccionar rol de administrador';
$string['group_aggregation'] = 'Agrupación de grupos';
$string['ssodomain'] = 'Subdomain SSO';
$string['ssodomain_desc'] = 'Single Sign On with separated Server/Account';
$string['instructor_redirect'] = 'Redireccionamiento del instructor';
$string['student_redirect'] = 'Redirección del estudiante';
$string['scale_percentage_round'] = 'Pourcentage ronda';
$string['api'] = 'Alternative API';
$string['api_desc'] = 'Use alternative API server (to avoid firewall blocking)';
$string['n18'] = 'Widget: Student Grade Progression';
$string['n101'] = 'Enable Instructor Dashboard';
$string['loading2'] = 'Please wait, loading...';
$string['in34'] = 'Student Grade Progression';
$string['select'] = 'Select';
$string['selectall'] = 'Select All';
$string['ok'] = 'OK';
$string['moodle'] = 'Moodle';
$string['totara'] = 'Totara';
$string['monitors'] = 'Monitors';
$string['cohorts'] = 'Cohorts';
$string['widget_name27'] = 'Cumulative Signups';
$string['widget_name28'] = 'Engagement';
$string['widget_name29'] = 'Unique Logins';
$string['widget_name30'] = 'Enrollments by Course';
$string['widget_name31'] = 'Registrars & Supervisor up take';
$string['role1'] = 'First Role';
$string['role2'] = 'Second Role';
$string['select_course'] = 'Select course';
$string['select_quiz'] = 'Select quiz';
$string['not_quiz'] = 'Oops, it looks like you do not have any quizzes created for selected course.';
$string['enter_course_and_quiz'] = 'Please select your course and quiz.';
$string['enter_quiz'] = 'Please select your quiz.';
$string['analityc_3_name'] = 'Quiz Overview & Question Detail';
$string['course_name_a'] = 'Course: {$a}';
$string['quiz_name_a'] = 'Quiz: {$a}';
$string['cor_incor_answers'] = 'Correct/Incorrect Answers';
$string['quiz_finished'] = 'Quiz finished';
$string['quiz_grades'] = 'Quiz grades';
$string['correct_number'] = 'Correct {$a}';
$string['incorrect_number'] = 'Incorrect {$a}';
$string['correct'] = 'Correct';
$string['incorrect'] = 'Incorrect';
$string['weekday_0'] = 'Monday';
$string['weekday_1'] = 'Tuesday';
$string['weekday_2'] = 'Wednesday';
$string['weekday_3'] = 'Thursday';
$string['weekday_4'] = 'Friday';
$string['weekday_5'] = 'Saturday';
$string['weekday_6'] = 'Sunday';
$string['time_1'] = 'Morning';
$string['time_2'] = 'Afternoon';
$string['time_3'] = 'Evening';
$string['time_4'] = 'Off Hours';
$string['passing_score_for'] = 'Passing grade for {$a}';
$string['name'] = 'Name';
$string['answers'] = 'Answers';
$string['ques_breakdown'] = 'Question Breakdown';
$string['n17'] = 'Analytics Page';
$string['analytics'] = 'Analytics';
$string['pdf'] = 'PDF';
$string['csv'] = 'CSV';
$string['excel'] = 'Excel';
$string['grades_alt_text'] = 'Alternative text for navigation menu';
$string['course_chart'] = 'Enable course chart';
$string['course_activities'] = 'Enable course activities';
$string['filter_this_year'] = 'Time filter: This Year';
$string['filter_last_year'] = 'Time filter: Last Year';
$string['this_year'] = 'This Year';
$string['last_year'] = 'Last Year';
$string['select_user'] = 'Select user';
$string['course_max_grade'] = 'Course max grade';
$string['no_data_notification'] = 'There is no new data for [date]';
$string['last_hour'] = 'hour';
$string['last_day'] = 'day';
$string['privacy:metadata:local_intelliboard_assign'] = 'Intelliboard assigns-subaccounts table';
$string['privacy:metadata:local_intelliboard_details'] = 'Intelliboard alt/logs/by-hour table';
$string['privacy:metadata:local_intelliboard_logs'] = 'Intelliboard alt/logs/by-day table';
$string['privacy:metadata:local_intelliboard_totals'] = 'Intelliboard alt/logs/total table';
$string['privacy:metadata:local_intelliboard_tracking'] = 'Intelliboard alt/logs/all-time table';
$string['privacy:metadata:local_intelliboard_reports'] = 'Intelliboard custom sql reports table';
$string['privacy:metadata:local_intelliboard_ntf'] = 'Intelliboard notifications main table';
$string['privacy:metadata:local_intelliboard_ntf_hst'] = 'Intelliboard notifications history table';
$string['privacy:metadata:local_intelliboard_ntf_pms'] = 'Intelliboard notifications dynamic params table';
$string['privacy:metadata:local_intelliboard_assign:userid'] = 'USER ID of record';
$string['privacy:metadata:local_intelliboard_reports:status'] = 'Status of report - activated/not activated';
$string['privacy:metadata:local_intelliboard_reports:name'] = 'Name of custom report';
$string['privacy:metadata:local_intelliboard_reports:sqlcode'] = 'BASE64 encoded SQL code';
$string['privacy:metadata:local_intelliboard_reports:timecreated'] = 'Creation time';
$string['sqlreport'] = 'SQL report';
$string['sqlreportcreate'] = 'Create report';
$string['sqlreports'] = 'SQL reports';
$string['sqlreportname'] = 'Report name';
$string['sqlreportcode'] = 'SQL';
$string['sqlreportdate'] = 'Created On';
$string['sqlreportactive'] = 'Activated';
$string['sqlreportinactive'] = 'Deactivated';
$string['remove_message'] = 'SQL report has been deleted';
$string['delete_message'] = 'Delete SQL report?';
$string['success_message'] = 'SQL report has been saved';
$string['bbbapiendpoint'] = 'BBB API endpoint';
$string['bbbserversecret'] = 'BBB server secret';
$string['check_active_meetings'] = 'Check active meetings';
$string['bbbmeetings'] = 'BigBlueButton meetings';
$string['enablebbbmeetings'] = 'Enable monitoring of BigBlueButton meetings';
$string['enablebbbdebug'] = 'BigBlueButton debug mode';
$string['privacy:metadata:local_intelliboard_bbb_meet'] = 'Log about BigBlueButton meetings';
$string['privacy:metadata:local_intelliboard_bbb_meet:id'] = 'ID of meeting log';
$string['privacy:metadata:local_intelliboard_bbb_meet:meetingname'] = 'Meeting name';
$string['privacy:metadata:local_intelliboard_bbb_meet:meetingid'] = 'Meeting ID';
$string['privacy:metadata:local_intelliboard_bbb_meet:internalmeetingid'] = 'Internal (in BBB server) Meeting ID';
$string['privacy:metadata:local_intelliboard_bbb_meet:createtime'] = 'Create time (timestamp)';
$string['privacy:metadata:local_intelliboard_bbb_meet:createdate'] = 'Create date (string)';
$string['privacy:metadata:local_intelliboard_bbb_meet:voicebridge'] = 'The extension number for the voice bridge (use if connected to phone system)';
$string['privacy:metadata:local_intelliboard_bbb_meet:dialnumber'] = 'The dial access number that participants can call in using regular phone.';
$string['privacy:metadata:local_intelliboard_bbb_meet:attendeepw'] = 'The password that will be required for attendees to join the meeting';
$string['privacy:metadata:local_intelliboard_bbb_meet:moderatorpw'] = 'The password that will be required for moderators to join the meeting or for certain administrative actions';
$string['privacy:metadata:local_intelliboard_bbb_meet:running'] = 'Status of meeting (active|stopped)';
$string['privacy:metadata:local_intelliboard_bbb_meet:duration'] = 'Meeting duration';
$string['privacy:metadata:local_intelliboard_bbb_meet:hasuserjoined'] = 'Flag. Users joined to meeting';
$string['privacy:metadata:local_intelliboard_bbb_meet:recording'] = 'Flag. Meeting will be recorded';
$string['privacy:metadata:local_intelliboard_bbb_meet:hasbeenforciblyended'] = 'Flag. Meeting has been forcibly ended';
$string['privacy:metadata:local_intelliboard_bbb_meet:starttime'] = 'Start time of meeting';
$string['privacy:metadata:local_intelliboard_bbb_meet:endtime'] = 'End time of meeting';
$string['privacy:metadata:local_intelliboard_bbb_meet:participantcount'] = 'Number of attendees';
$string['privacy:metadata:local_intelliboard_bbb_meet:listenercount'] = 'Number of listeners';
$string['privacy:metadata:local_intelliboard_bbb_meet:voiceparticipantcount'] = 'Number of participants with connected microphone';
$string['privacy:metadata:local_intelliboard_bbb_meet:videocount'] = 'Number of participants with connected video camera';
$string['privacy:metadata:local_intelliboard_bbb_meet:maxusers'] = 'Max number of participants';
$string['privacy:metadata:local_intelliboard_bbb_meet:moderatorcount'] = 'Number of moderators';
$string['privacy:metadata:local_intelliboard_bbb_meet:courseid'] = 'Course ID';
$string['privacy:metadata:local_intelliboard_bbb_meet:cmid'] = 'Course module ID';
$string['privacy:metadata:local_intelliboard_bbb_meet:bigbluebuttonbnid'] = 'Row ID in table bigbluebuttonbn';
$string['privacy:metadata:local_intelliboard_bbb_meet:ownerid'] = 'Owner ID (user which created the meeting)';
$string['privacy:metadata:local_intelliboard_bbb_atten'] = 'Log about attendees of BigBlueButton meetings';
$string['privacy:metadata:local_intelliboard_bbb_atten:id'] = 'Attendee ID';
$string['privacy:metadata:local_intelliboard_bbb_atten:userid'] = 'User ID (row in table "user")';
$string['privacy:metadata:local_intelliboard_bbb_atten:fullname'] = 'Full name of meeting attendee';
$string['privacy:metadata:local_intelliboard_bbb_atten:role'] = 'Role of meeting attendee';
$string['privacy:metadata:local_intelliboard_bbb_atten:ispresenter'] = 'Flag. Attendee is presenter';
$string['privacy:metadata:local_intelliboard_bbb_atten:islisteningonly'] = 'Flag. Attendee has no connected microphone or webcam';
$string['privacy:metadata:local_intelliboard_bbb_atten:hasjoinedvoice'] = 'Flag. Attendee has connected microphone';
$string['privacy:metadata:local_intelliboard_bbb_atten:hasvideo'] = 'Flag. Attendee has connected webcam';
$string['privacy:metadata:local_intelliboard_bbb_atten:meetingid'] = 'Meeting ID (ID in BigBlueButton server)';
$string['privacy:metadata:local_intelliboard_bbb_atten:localmeetingid'] = 'Meeting ID (ID in table local_intelliboard_bbb_meet)';
$string['privacy:metadata:local_intelliboard_bbb_atten:arrivaltime'] = 'Time when user connected to meeting';
$string['privacy:metadata:local_intelliboard_bbb_atten:departuretime'] = 'Time when user disconnected from meeting';
$string['myorders'] = 'Orders';
$string['myseats'] = 'Seats';
$string['mywaitlist'] = 'Waitlist';
$string['mysubscriptions'] = 'Subscriptions';
$string['seatscode'] = 'Seats code';
$string['numberofseats'] = 'Number of seats';
$string['downloadinvoice'] = 'Download Invoice';
$string['product'] = 'Product';
$string['key'] = 'Key';
$string['created'] = 'Created';
$string['seatnumber'] = 'Seats Number';
$string['seatsused'] = 'Seat Used';
$string['details'] = 'Details';
$string['username'] = 'User Name';
$string['used'] = 'Used';
$string['subscriptiondate'] = 'Subscription date';
$string['price'] = 'Price';
$string['recurringperiod'] = 'Recurring period';
$string['billingcycles'] = 'Billing cycles';
$string['active'] = 'Active';
$string['suspended'] = 'Suspended';
$string['canceled'] = 'Canceled';
$string['expired'] = 'Expired';
$string['process'] = 'Process';
$string['cancel_subscription'] = 'Cancel subscription';
$string['messageprovider:intelliboard_notification'] = "Intelliboard notification";
$string['verifypeer'] = "CURLOPT SSL VERIFYPEER";
$string['verifypeer_desc'] = "This option determines whether curl verifies the authenticity of the peer's certificate.";
$string['verifyhost'] = "CURLOPT SSL VERIFYHOST";
$string['verifyhost_desc'] = "This option determines whether libcurl verifies that the server cert is for the server it is known as.";
$string['cipherlist'] = "CURLOPT SSL CIPHER LIST";
$string['cipherlist_desc'] = "Specify ciphers to use for TLS";
$string['sslversion'] = "CURLOPT SSLVERSION";
$string['sslversion_desc'] = "Pass a long as parameter to control which version range of SSL/TLS versions to use";
$string['debug'] = "Debug CURL requests";
$string['debug_desc'] = "";
/* IntelliCart */
$string['intellicart'] = "IntelliCart integration";
$string['intellicart_desc'] = "Allow students to see IntelliCart reports.";
$string['coursessessionspage'] = "Courses Sessions Page";
$string['coursessessions'] = "Courses Sessions";
$string['session_name'] = "Session Name";
$string['session_time'] = "Session Time";
$string['return_to_sessions'] = "Return to Sessions";
/* IntelliCart END*/
$string['allmod'] = "All activities";
$string['customod'] = "Custom activities";
$string['timespent'] = "------ Time Spent ----";
$string['inprogress'] = "In progress";
$string['notstarted'] = "Not started";
$string['modulename'] = "Module name";
$string['viewed'] = "Viewed";
$string['course'] = "Course";
$string['courseaverage'] = "Course Average";
$string['mygrade'] = "My Grade";
$string['myprogress'] = "My grade progress";
$string['instructor_course_shortname'] = "Show course short name instead course full name";
$string['trackmedia'] = "Track HTML5 media";
$string['trackmedia_desc'] = "Track HTML5 video and audio";
$string['t53'] = 'Enable on [Activity progress] chart average line';
$string['ianalytics'] = 'IntelliBoard Analytics';
$string['instructor_course_visibility'] = 'Show hidden/suspended courses for [instructor]';
$string['instructor_mode'] = 'Show all courses available for [instructor]';
$string['instructor_mode_access'] = 'Show all courses available for [instructor] with [update] permissions';
$string['student_course_visibility'] = 'Show hidden/suspended courses for [student]';
$string['support_text1'] = "All your Moodle data: easy, shareable, understandable, and attractive. IntelliBoard is a Moodle plugin that puts <strong>120+</strong> reports and monitors into your hands.";
$string['support_text2'] = "All your Moodle data: easy, shareable, understandable, and attractive. IntelliBoard is your Moodle reporting and analytics solution, giving you 120+ reports and analytics to help inform your educational business decisions.";
$string['support_info1'] = "You can join our <a target='_blank' href='https://intelliboard.net/events'>Webinars</a> as we take you on a tour through IntelliBoard 5.0 reporting and analytics!";
$string['support_info2'] = "Join our <a target='_blank' href='https://intelliboard.net/events'>Webinars</a>, or schedule a personal tour of your own data. With our world class support and service, you'll see your LMS in an entirely new light.";
$string['support_terms'] = "All rights reserved.";
$string['support_page'] = "Support Page";
$string['support_demo'] = "Schedule a Demo";
$string['support_trial'] = "Start Trial";
$string['support_close'] = "Close";
$string['instructor_custom_groups'] = "Instructor custom groups";
// settings of tables
$string['show_dashboard_tab'] = 'Show dashboard tab';
$string['table_set_icg'] = 'Instructor`s table "Course grades"';
$string['table_set_icg_c1'] = 'Course Name';
$string['table_set_icg_c2'] = 'Short Name';
$string['table_set_icg_c3'] = 'Category';
$string['table_set_icg_c4'] = 'Enrolled/Completed Learners';
$string['table_set_icg_c5'] = 'Course Avg. grade';
$string['table_set_icg_c6'] = 'Sections';
$string['table_set_icg_c7'] = 'Activities/Resources';
$string['table_set_icg_c8'] = 'Visits';
$string['table_set_icg_c9'] = 'Time Spent';
$string['table_set_icg_c10'] = 'Actions';
$string['table_set_ilg'] = 'Instructor`s table "Learners grades"';
$string['table_set_ilg_c1'] = 'Learner Name';
$string['table_set_ilg_c2'] = 'Email address';
$string['table_set_ilg_c3'] = 'Enrolled';
$string['table_set_ilg_c4'] = 'Last Access';
$string['table_set_ilg_c5'] = 'Status';
$string['table_set_ilg_c6'] = 'Grade';
$string['table_set_ilg_c7'] = 'Completed Activities/Resources';
$string['table_set_ilg_c8'] = 'Visits';
$string['table_set_ilg_c9'] = 'Time Spent';
$string['table_set_ilg_c10'] = 'Actions';
$string['table_set_ilg1'] = 'Instructor`s table "Learner grades"';
$string['table_set_ilg1_c1'] = 'Activity name';
$string['table_set_ilg1_c2'] = 'Type';
$string['table_set_ilg1_c3'] = 'Grade';
$string['table_set_ilg1_c4'] = 'Graded';
$string['table_set_ilg1_c5'] = 'Status';
$string['table_set_ilg1_c6'] = 'Visits';
$string['table_set_ilg1_c7'] = 'Time Spent';
$string['table_set_iag'] = 'Instructor`s table "Activities grades"';
$string['table_set_iag_c1'] = 'Activity name';
$string['table_set_iag_c2'] = 'Type';
$string['table_set_iag_c3'] = 'Learners Completed';
$string['table_set_iag_c4'] = 'Average grade';
$string['table_set_iag_c5'] = 'Visits';
$string['table_set_iag_c6'] = 'Time Spent';
$string['table_set_iag_c7'] = 'Actions';
$string['table_set_iag1'] = 'Instructor`s table "Activity grades"';
$string['table_set_iag1_c1'] = 'Learner Name';
$string['table_set_iag1_c2'] = 'Email address';
$string['table_set_iag1_c3'] = 'Status';
$string['table_set_iag1_c4'] = 'Grade';
$string['table_set_iag1_c5'] = 'Graded';
$string['table_set_iag1_c6'] = 'Visits';
$string['table_set_iag1_c7'] = 'Time Spent';
<file_sep><?php
namespace Containers;
use DataExtractor;
class OrdersContainer extends BaseContainer {
public static function get($selected, DataExtractor $extractor, $params = array()) {
$directions = array(
1 => array(
DataExtractor::MYSQL_MODE => 'ASC',
DataExtractor::POSTGRES_MODE => 'ASC NULLS FIRST'
),
2 => array(
DataExtractor::MYSQL_MODE => 'DESC',
DataExtractor::POSTGRES_MODE => 'DESC NULLS LAST'
)
);
$mode = $extractor->getMode();
$directions = array_map(function($direction) use ($mode) {
if (is_array($direction)) {
$direction = $direction[$mode];
}
return $direction;
}, $directions);
return array_map(function($order) use ($directions, $extractor) {
if (empty($order['name'])) {
$column = ColumnsContainer::get($order, $extractor)['sql'];
$order['name'] = $column;
}
$order['direction'] = isset($order['direction'])? $directions[$order['direction']] : $directions[1];
return $order;
}, $selected);
}
public static function construct($orders, DataExtractor $extractor, $params = array()) {
return implode(',' . $extractor->getSeparator() . ' ' . $extractor->getSeparator(), array_map(function($order) {
return $order['name'] . ' ' . $order['direction'];
}, $orders));
}
} | 52028462dc7d623e9fdef7bd38f18bf10150c9f4 | [
"PHP"
]
| 7 | PHP | jm-montanez/intelliboard | 50cb39e798986954200287ff661563bc15a2a143 | cd187de0a6727828153b019275bcbeca835a73d5 |
refs/heads/master | <file_sep>package com.Exercise2;
class Node{
int data;
Node next;
}
public class StackLinkedList {
//top is equivalent to head
Node top;
StackLinkedList(){
Node top = new Node();
}
boolean isEmpty(){
if(top == null){
return true;
}
else{
return false;
}
}
int peek(){
if(top == null){
return -1;
}
else{
return top.data;
}
}
void display(){
if(top == null){
System.out.println("Stack underflow");
}
else {
Node temp = top;
while(temp.next != null){
System.out.println(temp.data);
temp = temp.next;
}
}
}
void push(int data){
/*if(top == null){
System.out.println("Stack overflow");
return;
}*/
//else{
Node temp = new Node();
temp.data = data;
temp.next = top;
top = temp;
//}
}
int pop(){
if(top == null){
System.out.println("Stack underflow");
return -1;
}
else{
int res = top.data;
top = top.next;
return res;
}
}
public static void main(String[] args) {
System.out.println("*********************************");
System.out.println("Stack implemented using LinkedList");
StackLinkedList sll = new StackLinkedList();
System.out.println("Is stack empty:"+sll.isEmpty());
System.out.println("Top:"+sll.peek());
System.out.println("Pushing elements to the stack");
sll.push(2);
sll.push(4);
sll.push(6);
sll.push(8);
sll.push(10);
System.out.println("Top:"+sll.peek());
System.out.println("After pushing the elements:");
sll.display();
System.out.println("Popping:"+sll.pop());
System.out.println("Popping:"+sll.pop());
System.out.println("After popping the elements:");
sll.display();
}
}
| 36553056da0d4ac7d954806925156f8d1d5a94fc | [
"Java"
]
| 1 | Java | Keerthi-V5/PreCourse_1 | 9870319b688066eaa7e5a1a5014d153865a6000e | 866a7c3bd93b0f2605baddaca446e313d401bfba |
refs/heads/master | <file_sep>// Your server code here...
import express from 'express';
// app is instance of server
// we call .listen --> server starts, runs, waits for request
const app = express();
import bodyParser from 'body-parser';
// body parser can parse many different forms, we want JSON, easiest
// use .use adds middleware to express
app.use(bodyParser.json());
// callback function defined by express - request/response
// request respresents the http request sent to server ;
// response represents the http response sent back to client
// use app.something plus path plus function --> tell server what to do in any given circumstance
// we want to send back data in form JSON
app.get('/', (request, response) => {
// return response.send('you tried to get the route path');
return response.json({message: 'Hello World'});
});
/*
app.get('/', (request, response) => {
return response.json({hello: 'world'});
});
app.post('/', (request, response) => {
return response.json({whatisthis: 'you posted'});
});
*/
/*
app.post('/contacts', (request, response) => {
return response.json({whatisthis: 'you posted'});
});
*/
app.post('/contacts', (request, response) => {
return response.json({whatisthis: request.body});
});
app.get('/contacts', (request, response) => {
return response.json([
{
_id: 1,
name: '<NAME>',
occupation: 'FBI Agent',
avatar: 'https://upload.wikimedia.org/wikipedia/en/5/50/Agentdalecooper.jpg'
},
{
_id: 2,
name: '<NAME>',
occupation: 'Bounty Hunter',
avatar: 'http://vignette4.wikia.nocookie.net/deadliestfiction/images/d/de/Spike_Spiegel_by_aleztron.jpg/revision/latest?cb=20130920231337'
},
{
_id: 3,
name: 'Wirt',
occupation: 'adventurer',
avatar: 'http://66.media.tumblr.com/5ea59634756e3d7c162da2ef80655a39/tumblr_nvasf1WvQ61ufbniio1_400.jpg'
},
{
_id: 4,
name: '<NAME>',
occupation: 'Loving little brother',
avatar: 'http://vignette2.wikia.nocookie.net/villains/images/e/e3/MMH.jpg/revision/latest?cb=20150810215746'
},
{
_id: 5,
name: '<NAME>',
occupation: 'FBI Agent',
avatar: 'https://pbs.twimg.com/profile_images/718881904834056192/WnMTb__R.jpg'
}
]);
});
app.get('/contacts/:id', (request, response) => {
// request object has everything from request
// .id is variable name, defined above, called below
return response.json({theId: request.params.id});
});
// shows we train for anything, it will return
app.get('/themostsecretpasswordeverthoughtof', (request, response) => {
return response.json({secret: 'super secret information'});
});
app.listen(3002, (err) => {
if (err) {
return console.log('Error', err);
}
});
<file_sep># My First Web Server
A starter repo for the ACA Advanced `My First Web Server` project.
| 58e0f3b5027666b0b029b323139db84a17276a06 | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | jkilleen15/advanced-first-web-server | 1fd152c58e3192aa35d0b2c8db56d1fd351d3099 | 83c7e0a839f1cb24058df533fa1f0d9a7ca75ff0 |
refs/heads/master | <repo_name>cadenzajon/monasca-agent<file_sep>/monasca_agent/collector/checks_d/cadvisor_host.py
# (C) Copyright 2017 Hewlett Packard Enterprise Development LP
import requests
from monasca_agent.collector.checks import AgentCheck
from monasca_agent.collector.checks import utils
DEFAULT_TIMEOUT = "3"
# format for METRICS: (cadvisor metric name, [metric types], [metric units])
METRICS = {
"cpu_metrics": {
"system": ("system_time", ["gauge", "rate"],
["core_seconds", "core_seconds_per_second"]),
"total": ("total_time", ["gauge", "rate"],
["core_seconds", "core_seconds_per_second"]),
"user": ("user_time", ["gauge", "rate"],
["core_seconds", "core_seconds_per_second"])
},
"memory_metrics": {
"swap": ("swap_bytes", ["gauge"], ["bytes"]),
"cache": ("cache_bytes", ["gauge"], ["bytes"]),
"usage": ("used_bytes", ["gauge"], ["bytes"]),
},
"filesystem_metrics": {
"capacity": ("total_bytes", ["gauge"], ["bytes"]),
"usage": ("usage_bytes", ["gauge"], ["bytes"])
},
'network_metrics': {
"rx_bytes": ("in_bytes", ["gauge", "rate"],
["bytes", "bytes_per_second"]),
"tx_bytes": ("out_bytes", ["gauge", "rate"],
["bytes", "bytes_per_second"]),
"rx_packets": ("in_packets", ["gauge", "rate"],
["packets", "packets_per_second"]),
"tx_packets": ("out_packets", ["gauge", "rate"],
["packets", "packets_per_second"]),
"rx_dropped": ("in_dropped_packets", ["gauge", "rate"],
["packets", "packets_per_second"]),
"tx_dropped": ("out_dropped_packets", ["gauge", "rate"],
["packets", "packets_per_second"]),
"rx_errors": ("in_errors", ["gauge", "rate"],
["errors", "errors_per_second"]),
"tx_errors": ("out_errors", ["gauge", "rate"],
["errors", "errors_per_second"])
}
}
class CadvisorHost(AgentCheck):
"""Queries given cAdvisor API for node metrics
"""
def __init__(self, name, init_config, agent_config, instances=None):
AgentCheck.__init__(self, name, init_config, agent_config, instances)
if instances is not None and len(instances) > 1:
raise Exception('cAdvisor host check only supports one configured instance.')
self.connection_timeout = int(init_config.get('connection_timeout', DEFAULT_TIMEOUT))
self.cadvisor_url = None
def check(self, instance):
if not self.cadvisor_url:
cadvisor_url = instance.get("cadvisor_url", None)
detect_cadvisor_url = instance.get("kubernetes_detect_cadvisor", False)
if not cadvisor_url:
if detect_cadvisor_url:
kubernetes_connector = utils.KubernetesConnector(self.connection_timeout)
host = kubernetes_connector.get_agent_pod_host()
cadvisor_url = "http://{}:4194".format(host)
else:
exception_message = "Either cAdvisor url or kubernetes detect cAdvisor must be set when " \
"monitoring a Kubernetes Node."
self.log.error(exception_message)
raise Exception(exception_message)
self.cadvisor_url = "{}/{}".format(cadvisor_url, "api/v2.0/stats?count=1")
dimensions = self._set_dimensions(None, instance)
try:
host_metrics = requests.get(self.cadvisor_url, self.connection_timeout).json()
except Exception as e:
self.log.error("Error communicating with cAdvisor to collect data - {}".format(e))
else:
self._parse_send_metrics(host_metrics, dimensions)
def _send_metrics(self, metric_name, value, dimensions, metric_types,
metric_units):
for metric_type in metric_types:
if metric_type == 'rate':
dimensions.update({'unit': metric_units[metric_types.index('rate')]})
self.rate(metric_name + "_sec", value, dimensions)
elif metric_type == 'gauge':
dimensions.update({'unit': metric_units[metric_types.index('gauge')]})
self.gauge(metric_name, value, dimensions)
def _parse_memory(self, memory_data, dimensions):
memory_metrics = METRICS['memory_metrics']
for cadvisor_key, (metric_name, metric_types, metric_units) in memory_metrics.items():
if cadvisor_key in memory_data:
self._send_metrics("mem." + metric_name, memory_data[cadvisor_key], dimensions,
metric_types, metric_units)
def _parse_filesystem(self, filesystem_data, dimensions):
filesystem_metrics = METRICS['filesystem_metrics']
for filesystem in filesystem_data:
file_dimensions = dimensions.copy()
file_dimensions['device'] = filesystem['device']
for cadvisor_key, (metric_name, metric_types, metric_units) in filesystem_metrics.items():
if cadvisor_key in filesystem:
self._send_metrics("fs." + metric_name, filesystem[cadvisor_key], file_dimensions,
metric_types, metric_units)
def _parse_network(self, network_data, dimensions):
network_interfaces = network_data['interfaces']
network_metrics = METRICS['network_metrics']
for interface in network_interfaces:
network_dimensions = dimensions.copy()
network_dimensions['interface'] = interface['name']
for cadvisor_key, (metric_name, metric_types, metric_units) in network_metrics.items():
if cadvisor_key in interface:
self._send_metrics("net." + metric_name, interface[cadvisor_key], network_dimensions,
metric_types, metric_units)
def _parse_cpu(self, cpu_data, dimensions):
cpu_metrics = METRICS['cpu_metrics']
cpu_usage = cpu_data['usage']
for cadvisor_key, (metric_name, metric_types, metric_units) in cpu_metrics.items():
if cadvisor_key in cpu_usage:
# Convert nanoseconds to seconds
cpu_usage_sec = cpu_usage[cadvisor_key] / 1000000000.0
self._send_metrics("cpu." + metric_name, cpu_usage_sec, dimensions, metric_types, metric_units)
def _parse_send_metrics(self, metrics, dimensions):
for host, cadvisor_metrics in metrics.items():
host_dimensions = dimensions.copy()
# Grab first set of metrics from return data
cadvisor_metrics = cadvisor_metrics[0]
if cadvisor_metrics['has_memory'] and cadvisor_metrics['memory']:
self._parse_memory(cadvisor_metrics['memory'], host_dimensions)
if cadvisor_metrics['has_filesystem'] and cadvisor_metrics['filesystem']:
self._parse_filesystem(cadvisor_metrics['filesystem'], host_dimensions)
if cadvisor_metrics['has_network'] and cadvisor_metrics['network']:
self._parse_network(cadvisor_metrics['network'], host_dimensions)
if cadvisor_metrics['has_cpu'] and cadvisor_metrics['cpu']:
self._parse_cpu(cadvisor_metrics['cpu'], host_dimensions)
| 87af2ee87c27a8fcab6aff97802ba6a116449dfc | [
"Python"
]
| 1 | Python | cadenzajon/monasca-agent | 75ba59793a0412090c76bf0f7416c3a39dfdbdb4 | 8fe93ffa0dbcb966c8d4bd86a2e530f0928b1aaf |
refs/heads/master | <repo_name>samaya-credencesoft/java-customer-onboarding<file_sep>/src/main/java/co/nz/csoft/losMaster/SupplierRepository.java
package co.nz.csoft.losMaster;
import org.springframework.data.jpa.repository.JpaRepository;
import javax.transaction.Transactional;
@Transactional
//@RepositoryRestResource
public interface SupplierRepository extends JpaRepository<SupplierMaster, Long> {
}<file_sep>/src/main/java/co/nz/csoft/notification/Test.java
package co.nz.csoft.notification;
import co.nz.csoft.notification.EmailServiceImpl;
import co.nz.csoft.notification.MailObject;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
public class Test {
@Autowired
public EmailServiceImpl emailService;
public static void main(String args[]){
String uuid = UUID.randomUUID().toString();
System.out.println(uuid);
}
}
<file_sep>/src/main/java/co/nz/csoft/losMaster/ManufactureRepository.java
package co.nz.csoft.losMaster;
import org.springframework.data.jpa.repository.JpaRepository;
import javax.transaction.Transactional;
@Transactional
//@RepositoryRestResource
public interface ManufactureRepository extends JpaRepository<ManufactureMaster, Long> {
}<file_sep>/src/main/java/co/nz/csoft/address/AddressFinder.java
package co.nz.csoft.address;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.stereotype.Service;
@Service
public class AddressFinder {
private static Map<String,String> addressFinder= new LinkedHashMap<String, String>();
DataInputStream dis = null;
/**
* returns a string which is comma separate column values for matching row otherwise null.
* @param searchColumnIndex
* @param searchString
* @return
* @throws IOException
*
*/
public String searchCsvLine(int searchColumnIndex, String searchString) throws IOException {
String resultRow = null;
String line;
String keyName;
File f = new File("C:\\dev\\credencesoft\\postCodeFinder\\PostCode.csv");
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis,1024);
dis = new DataInputStream(bis);
if(addressFinder == null)
{
System.out.println("Address Finder is null ");
addressFinder = new HashMap<String, String>();
}
if(!addressFinder.isEmpty())
{
if(addressFinder.containsKey(searchString)){
System.out.println("get the details from the map ");
return addressFinder.get(searchString).toString();
}
}
while ( (line = dis.readLine()) != null ) {
String[] values = line.split(",");
addressFinder.put(values[searchColumnIndex], line);
System.out.println("frewrewr "+line);
if(values[searchColumnIndex].equals(searchString)) {
resultRow = line;
try {
addressFinder.put(searchString, resultRow);
System.out.println("get the details from the file5 ");
}
catch(Exception ex){
ex.getMessage();
}
break;
}
}
// br.close();
return resultRow;
}
}
<file_sep>/src/main/java/co/nz/csoft/losMaster/BranchRepository.java
package co.nz.csoft.losMaster;
import co.nz.csoft.users.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import javax.transaction.Transactional;
import java.util.List;
//@Transactional
@RepositoryRestResource
public interface BranchRepository extends JpaRepository<BranchMaster, Long> {
List<BranchMaster> findAll();
BranchMaster findByBranchName(String branchName);
}<file_sep>/src/main/java/co/nz/csoft/users/UserRepository.java
package co.nz.csoft.users;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.web.bind.annotation.CrossOrigin;
import java.util.List;
import javax.persistence.Entity;
import javax.transaction.Transactional;
@Transactional
//@RepositoryRestResource
@CrossOrigin(origins = "https://loan-origination-system.appspot.com")
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
User findOneById(Long id);
User findOneByEmailAndPassword(String email, String password);
User findOneByUuid(String uuid);
List<User> findAll();
// User saveUser(Long id);
}
<file_sep>/src/main/java/co/nz/csoft/losMaster/MasterController.java
package co.nz.csoft.losMaster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("api")
@CrossOrigin(origins = "http://localhost:4200")
public class MasterController {
@Autowired
private final MasterService service;
@Autowired
private BranchRepository branchRepository;
@Autowired
public MasterController(MasterService service) {
this.service = service;
}
@RequestMapping(value = "/createOrUpdateBranch",method = RequestMethod.POST)
// @RequestMapping(value = "/branchMasterDetails",method = RequestMethod.POST)
public ResponseEntity<BranchMaster> createBranch(@RequestBody BranchMaster branch) {
if (branch!= null) {
//check if branch exist
//getBranchByBranchName();
//if there is a branch get the id of the branch save with the id
//else create a new branch
this.service.createBranch(branch);
}
return new ResponseEntity<BranchMaster>(branch, HttpStatus.OK);
}
@RequestMapping(value = "/departmentMasterDetails",method = RequestMethod.POST)
public ResponseEntity<DepartmentMaster> createDepartment(@RequestBody DepartmentMaster department) {
if (department!= null) {
this.service.createDepartment(department);
}
return new ResponseEntity<DepartmentMaster>(department, HttpStatus.OK);
}
@RequestMapping(value = "/allBranches",method = RequestMethod.GET)
public ResponseEntity<?> getAllBranchDetails() {
return new ResponseEntity<>(branchRepository.findAll(), HttpStatus.OK);
}
@RequestMapping(value = "/manufactureMasterDetails",method = RequestMethod.POST)
public ResponseEntity<ManufactureMaster> createManufacture(@RequestBody ManufactureMaster manufacture) {
if (manufacture!= null) {
this.service.createManufacture(manufacture);
}
return new ResponseEntity<ManufactureMaster>(manufacture, HttpStatus.OK);
}
@RequestMapping(value = "/supplierMasterDetails",method = RequestMethod.POST)
public ResponseEntity<SupplierMaster> createSupplier(@RequestBody SupplierMaster supplier) {
if (supplier!= null) {
this.service.createSupplier(supplier);
}
return new ResponseEntity<SupplierMaster>(supplier, HttpStatus.OK);
}
@RequestMapping(value = "/sourcingMasterDetails",method = RequestMethod.POST)
public ResponseEntity<SourcingMaster> createSourcing(@RequestBody SourcingMaster sourcing) {
if (sourcing!= null) {
this.service.createSourcing(sourcing);
}
return new ResponseEntity<SourcingMaster>(sourcing, HttpStatus.OK);
}
@RequestMapping(value = "/modelMasterDetails",method = RequestMethod.POST)
public ResponseEntity<ModelMaster> createModel(@RequestBody ModelMaster model) {
if (model!= null) {
this.service.createModel(model);
}
return new ResponseEntity<ModelMaster>(model, HttpStatus.OK);
}
@RequestMapping(value = "/productMasterDetails",method = RequestMethod.POST)
public ResponseEntity<ProductMaster> createProduct(@RequestBody ProductMaster product) {
if (product!= null) {
this.service.createProduct(product);
}
return new ResponseEntity<ProductMaster>(product, HttpStatus.OK);
}
@RequestMapping(value = "/salesmanagerMasterDetails",method = RequestMethod.POST)
public ResponseEntity<SalesmanagerMaster> createSalesmanager(@RequestBody SalesmanagerMaster salesmanager) {
if (salesmanager!= null) {
this.service.createSalesmanager(salesmanager);
}
return new ResponseEntity<SalesmanagerMaster>(salesmanager, HttpStatus.OK);
}
@RequestMapping(value = "/bounceReasonMasterDetails",method = RequestMethod.POST)
public ResponseEntity<BounceReasonMaster> createBounceReason(@RequestBody BounceReasonMaster bouncereason) {
if (bouncereason!= null) {
this.service.createBounceReason(bouncereason);
}
return new ResponseEntity<BounceReasonMaster>(bouncereason, HttpStatus.OK);
}
@RequestMapping(value = "/schemeMasterDetails",method = RequestMethod.POST)
public ResponseEntity<SchemeMaster> createScheme(@RequestBody SchemeMaster scheme) {
if (scheme!= null) {
this.service.createScheme(scheme);
}
return new ResponseEntity<SchemeMaster>(scheme, HttpStatus.OK);
}
}
<file_sep>/README.md
# java-customer-onboarding
API for Loan Origination System
<file_sep>/src/main/java/co/nz/csoft/losMaster/SalesmanagerMaster.java
package co.nz.csoft.losMaster;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
@Table(name = "salesmanagermaster")
public class SalesmanagerMaster {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
private String name;
private String designation;
private String employeeCode;
public SalesmanagerMaster(String name,String designation, String employeeCode) {
this.name = name;
this.designation = designation;
this.employeeCode = employeeCode;
}
public SalesmanagerMaster()
{
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getEmployeeCode() {
return employeeCode;
}
public void setEmployeeCode(String employeeCode) {
this.employeeCode = employeeCode;
}
}
<file_sep>/src/main/java/co/nz/csoft/ApplicationRunner.java
package co.nz.csoft;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SpringBootApplication(scanBasePackages={"co.nz.csoft"})
/*@EntityScan(basePackages = {"EntityPackage"} )
@EnableJpaRepositories(basePackages = {"RepositoryPackage"})*/
@RestController
public class ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(ApplicationRunner.class, args);
}
/* @GetMapping("/")
public String hello() {
return "hello world!";
}*/
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").allowedOrigins
("https://sourcing-application.appspot.com",
"https://loan-origination-system.appspot.com",
"https://dashboard-los.appspot.com",
"http://localhost:4200");
}
};
}
}
<file_sep>/src/main/java/co/nz/csoft/notification/EmailConfig.java
package co.nz.csoft.notification;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
@Configuration
@ComponentScan("co.nz.csoft.notification")
public class EmailConfig {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Bean
public SimpleMailMessage templateSimpleMessage() {
SimpleMailMessage message = new SimpleMailMessage();
message.setText("This is the test email template for your email:\n%s\n");
return message;
}
}
<file_sep>/src/main/java/co/nz/csoft/losMaster/MasterServiceImpl.java
package co.nz.csoft.losMaster;
//import org.apache.commons.collections4.IteratorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import co.nz.csoft.users.User;
@Service
public class MasterServiceImpl implements MasterService {
@Autowired
private BranchRepository branchRepository;
private DepartmentRepository departmentRepository;
private ManufactureRepository manufactureRepository;
private SupplierRepository supplierRepository;
private SourcingRepository sourcingRepository;
private ModelRepository modelRepository;
private ProductRepository productRepository;
private SalesmanagerRepository salesmanagerRepository;
private BounceReasonRepository bounceReasonRepository;
private SchemeRepository schemeRepository;
@Autowired
public MasterServiceImpl(BranchRepository branchRepository, DepartmentRepository departmentRepository, ManufactureRepository manufactureRepository, SupplierRepository supplierRepository, SourcingRepository sourcingRepository, ModelRepository modelRepository, ProductRepository productRepository, SalesmanagerRepository salesmanagerRepository, BounceReasonRepository bounceReasonRepository, SchemeRepository schemeRepository) {
this.branchRepository = branchRepository;
this.departmentRepository = departmentRepository;
this.manufactureRepository = manufactureRepository;
this.supplierRepository = supplierRepository;
this.sourcingRepository = sourcingRepository;
this.modelRepository = modelRepository;
this.productRepository = productRepository;
this.salesmanagerRepository = salesmanagerRepository;
this.bounceReasonRepository = bounceReasonRepository;
this.schemeRepository = schemeRepository;
}
@Override
public BranchMaster createBranch(BranchMaster branch) {
return branchRepository.save(branch);
}
@Override
public BranchMaster updateBranch(BranchMaster branch) {
return null;
}
@Override
public DepartmentMaster createDepartment(DepartmentMaster department) {
return departmentRepository.save(department);
}
@Override
public DepartmentMaster updateDepartment(DepartmentMaster department) {
return null;
}
@Override
public ManufactureMaster createManufacture(ManufactureMaster manufacture) {
return manufactureRepository.save(manufacture);
}
@Override
public ManufactureMaster updateManufacture(ManufactureMaster manufacture) {
return null;
}
@Override
public SupplierMaster createSupplier(SupplierMaster supplier) {
return supplierRepository.save(supplier);
}
@Override
public SupplierMaster updateSupplier(SupplierMaster supplier) {
return null;
}
@Override
public SourcingMaster createSourcing(SourcingMaster sourcing) {
return sourcingRepository.save(sourcing);
}
@Override
public SourcingMaster updateSourcing(SourcingMaster sourcing) {
return null;
}
@Override
public ModelMaster createModel(ModelMaster model) {
return modelRepository.save(model);
}
@Override
public ModelMaster updateModel(ModelMaster model) {
return null;
}
@Override
public ProductMaster createProduct(ProductMaster product) {
return productRepository.save(product);
}
@Override
public ProductMaster updateProduct(ProductMaster product) {
return null;
}
@Override
public SalesmanagerMaster createSalesmanager(SalesmanagerMaster salesmanager) {
return salesmanagerRepository.save(salesmanager);
}
@Override
public SalesmanagerMaster updateSalesmanager(SalesmanagerMaster salesmanager) {
return null;
}
@Override
public BounceReasonMaster createBounceReason(BounceReasonMaster bouncereason) {
return bounceReasonRepository.save(bouncereason);
}
@Override
public BounceReasonMaster updateBounceReason(BounceReasonMaster bouncereason) {
return null;
}
@Override
public SchemeMaster createScheme(SchemeMaster scheme) {
return schemeRepository.save(scheme);
}
@Override
public SchemeMaster updateScheme(SchemeMaster scheme) {
return null;
}
}<file_sep>/src/main/java/co/nz/csoft/losMaster/SchemeMaster.java
package co.nz.csoft.losMaster;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
@Table(name = "schememaster")
public class SchemeMaster {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
private String schemeName;
private String schemeCode;
private String minimumLoanAmount;
private String maximumLoanAmount;
private String minimumTenure ;
private String maximumTenure;
private String minimumEffectiveInterestRate;
private String maximumEffectiveInterestRate;
private String minimumFlatRate;
private String maximumFlatRate ;
private String rateMethod;
private String rateType;
private String reschedulement ;
public SchemeMaster(@NotNull String schemeName, String schemeCode, String maximumLoanAmount, String minimumTenure, String minimumLoanAmount, String maximumTenure, String minimumEffectiveInterestRate, String maximumEffectiveInterestRate, String minimumFlatRate, String maximumFlatRate, String rateMethod, String rateType, String reschedulement) {
this.schemeName = schemeName;
this.schemeCode = schemeCode;
this.minimumLoanAmount = minimumLoanAmount;
this.maximumLoanAmount = maximumLoanAmount;
this.minimumTenure = minimumTenure;
this.maximumTenure = maximumTenure;
this.minimumEffectiveInterestRate = minimumEffectiveInterestRate;
this.maximumEffectiveInterestRate = maximumEffectiveInterestRate;
this.minimumFlatRate = minimumFlatRate;
this.maximumFlatRate = maximumFlatRate;
this.rateMethod = rateMethod;
this.rateType = rateType;
this.reschedulement = reschedulement;
}
public SchemeMaster()
{
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSchemeName() {
return schemeName;
}
public void setSchemeName(String schemeName) {
this.schemeName = schemeName;
}
public String getSchemeCode() {
return schemeCode;
}
public void setSchemeCode(String schemeCode) {
this.schemeCode = schemeCode;
}
public String getMinimumLoanAmount() {
return minimumLoanAmount;
}
public void setMinimumLoanAmount(String minimumLoanAmount) {
this.minimumLoanAmount = minimumLoanAmount;
}
public String getMaximumLoanAmount() {
return maximumLoanAmount;
}
public void setMaximumLoanAmount(String maximumLoanAmount) {
this.maximumLoanAmount = maximumLoanAmount;
}
public String getMinimumTenure() {
return minimumTenure;
}
public void setMinimumTenure(String minimumTenure) {
this.minimumTenure = minimumTenure;
}
public String getMaximumTenure() {
return maximumTenure;
}
public void setMaximumTenure(String maximumTenure) {
this.maximumTenure = maximumTenure;
}
public String getMinimumEffectiveInterestRate() {
return minimumEffectiveInterestRate;
}
public void setMinimumEffectiveInterestRate(String minimumEffectiveInterestRate) {
this.minimumEffectiveInterestRate = minimumEffectiveInterestRate;
}
public String getMaximumEffectiveInterestRate() {
return maximumEffectiveInterestRate;
}
public void setMaximumEffectiveInterestRate(String maximumEffectiveInterestRate) {
this.maximumEffectiveInterestRate = maximumEffectiveInterestRate;
}
public String getMinimumFlatRate() {
return minimumFlatRate;
}
public void setMinimumFlatRate(String minimumFlatRate) {
this.minimumFlatRate = minimumFlatRate;
}
public String getMaximumFlatRate() {
return maximumFlatRate;
}
public void setMaximumFlatRate(String maximumFlatRate) {
this.maximumFlatRate = maximumFlatRate;
}
public String getRateMethod() {
return rateMethod;
}
public void setRateMethod(String rateMethod) {
this.rateMethod = rateMethod;
}
public String getRateType() {
return rateType;
}
public void setRateType(String rateType) {
this.rateType = rateType;
}
public String getReschedulement() {
return reschedulement;
}
public void setReschedulement(String reschedulement) {
this.reschedulement = reschedulement;
}
}
<file_sep>/src/main/java/co/nz/csoft/losMaster/DepartmentMaster.java
package co.nz.csoft.losMaster;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
@Table(name = "departmentmaster")
public class DepartmentMaster {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
private String departmentName;
private Integer serialNumber;
public DepartmentMaster(String departmentName, Integer serialNumber) {
this.departmentName = departmentName;
this.serialNumber = serialNumber;
}
public DepartmentMaster()
{
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public Integer getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(Integer serialNumber) {
this.serialNumber = serialNumber;
}
}
<file_sep>/src/main/java/co/nz/csoft/otp/OTPController.java
package co.nz.csoft.otp;
import co.nz.csoft.loans.LoanApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
//@CrossOrigin(origins = "http://localhost:4200")
public class OTPController {
@GetMapping(path = {"/sendOTP/{mobileNumber}"})
public String sendOTP(@PathVariable("mobileNumber") String mobileNumber) {
System.out.println("Mobile Number" + mobileNumber);
return mobileNumber;
}
} | 76898249ab30b5c95fe143f1cc740495c7bfd290 | [
"Markdown",
"Java"
]
| 15 | Java | samaya-credencesoft/java-customer-onboarding | 91f2f65f6b622b5c9600f38efe727b831ca9a05e | 941f8825215ce96c667034d6304312fd70159330 |
refs/heads/master | <repo_name>vtthombre/Generic-Batch-Processor-using-Akka.NET<file_sep>/Concurrent_Application/TaskExecuter/ExternalSystems/ClientTaskExecuter.cs
using System.Threading.Tasks;
using TaskExecuter.Messages;
namespace TaskExecuter.ExternalSystems
{
public class ClientTaskExecuter : ITaskExecuter
{
public async Task<AcknowledgementMessage> ExecuteTask(JobStartedMessage taskMessage)
{
return await Task.Delay(100)
.ContinueWith<AcknowledgementMessage>(task =>
{
AcknowledgementReceipt receipt = AcknowledgementReceipt.SUCCESS;
long taskTime = 0;
Task externalTask = Task.Factory.StartNew(() =>
{
// call or execute an external application here
});
// wait for task to complete
externalTask.Wait();
switch (externalTask.Status)
{
case TaskStatus.Faulted:
receipt = AcknowledgementReceipt.FAILED;
break;
case TaskStatus.Canceled:
receipt = AcknowledgementReceipt.CANCELED;
break;
case TaskStatus.RanToCompletion:
receipt = AcknowledgementReceipt.SUCCESS;
break;
}
// send the acknowledgement
return new AcknowledgementMessage(taskMessage.ID, taskMessage.Description, taskTime, receipt);
});
}
}
}
<file_sep>/README.md
# Generic Batch Processor using Akka.NET
” Building a concurrent, remote and distributed System for batch processing which is fault tolerant and can scale up or scale out using [Akka.NET](http://getakka.net/ "Akka.NET - .NET distributed actor framework") (based on actor model)”.
A generic batch processor is used for dividing parallel work to multiple actors on the same machine, remote machine as well as on distributed network.
### Batch Processor workflow

## Job Manager
Job Manger is managing all the tasks and their status. This can be UI or console based appliaction.
### Job Pool Controller Actor
Job Pool Controller actor has following responsibilities
1. Assign the task to commander actor
2. Get the response from commander actor
3. update the job status
4. print the job statastics
### Job Scheduler
Job Scheduler is responsible for scheduling the job after each interval (10 sec ). It is also responsible for checking the job status after every 3 minutes.
## Executer
Executer is the backbone the batchprocessor acgtor system. It is responsible for taking the job from job manager (Job pool controller actor) and perfor that job and after completion, update job manager.
### Commander Actor
Commander actor has following responsibilities-
1. Create the broadcast router for creating coordinator instances.
2. Get the task from Job pool controller and assign it to any available coordinator.
3. Get the response from coordinator and update to job pool controller about the task.
### Coordinator Actor
Coordinator actor plays mediator role between commander and worker actor.Coordinator actor has following responsibilities-
1. Create the worker actor for performing task.
2. Supervise worker actor. If worker actor failed to perform any task then it will take necessary action.
3. Update the commander once the task is completed by worker.
### Worker Actor
Worker actor is the last actor in the hierarchy which actully perform the task. It has following responsibilities-
1. Get the task from coordinator and perform the task.
2. Update the task status to coordinator
## Current Samples
**[Concurrent application for Batch Processing](/Concurrent_Application/)** - how to execute multiple tasks concurrently as well as paralley in Akka.NET.
## Contributing
Please feel free to contribute.
### Questions about Samples?
Please [create a Github issue](https://github.com/vtthombre/Generic-Batch-Processor-using-Akka.NET/issues) for any questions you might have.
### Code License
## About Author
<file_sep>/Concurrent_Application/README.md
## Concurrent application for batch processing which is fault tolerant using [Akka.NET](http://getakka.net/ "Akka.NET - .NET distributed actor framework").
Demonstrates via a console application how `concurrent as well as parallely perform multple tasks`.

## Contributing
Please feel free to contribute.
### Questions about Samples?
If you have any questions about this sample, please [create a Github issue for us](https://github.com/vtthombre/Generic-Batch-Processor-using-Akka.NET/issues)!
### Code License
## About Author
| 331cb1c190db2ce46658c141be7d4345f33a69e7 | [
"Markdown",
"C#"
]
| 3 | C# | vtthombre/Generic-Batch-Processor-using-Akka.NET | d45c824bb842ac8ddb5bae339f5656f99fe2c443 | 3974450dd0285f990b01e17fff658d6fe59343d0 |
refs/heads/master | <file_sep><?php
const server = "127.0.0.1";
const dbuser = "root";
const dbpw = "";
const db = "jacksonn_hiit";
?><file_sep>import { Component } from '@angular/core';
import { fail } from 'assert';
import { HiitService } from '../hiit.service';
import { LoadingService } from '../loading.service';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
public inputBMIData = {
"height": "",
"weight": "",
"gender": "",
"dreamWeight": "",
"age": "",
"exercise": ""
};
public resultBMIData = {
"weightState": "",
"bmi": "",
"bmr": "",
"maintainWeight": "",
"achieveWeight": "",
"reduce": false,
"daysWeight": ""
};
public inputHIITData = {
"exerciseTime": "",
"repotition": "",
"work": "",
"rest": "",
"exercise": ""
};
public resultHIITData = {
"listData": [],
"totalExerciseTime": 0,
"totalRestTime": 0,
"totalHiitTime": 0
};
public switchBMIHIIT = true;
public bmiResultState = false;
public hiitResultState = false;
constructor(
public hitService: HiitService,
public loading: LoadingService,
) {
}
bmiSubmit(bmiData) {
console.log("asdfhlasjdfhlaj");
console.log(bmiData);
console.log(bmiData.valid);
if (bmiData.valid) {
this.calculateBMI();
}
}
calculateBMI() {
this.resultBMIData.bmi = (parseFloat(this.inputBMIData.weight)
/ (parseFloat(this.inputBMIData.height) * parseFloat(this.inputBMIData.height))).toString();
let floatBMI = parseFloat(this.resultBMIData.bmi);
if (floatBMI < 18.5) {
this.resultBMIData.weightState = "Underweight";
} else if (floatBMI > 18.5 && floatBMI < 24.99) {
this.resultBMIData.weightState = "Normal Weight";
} else if (floatBMI > 25 && floatBMI < 29.99) {
this.resultBMIData.weightState = "Overweight";
} else if (floatBMI > 30 && floatBMI < 34.99) {
this.resultBMIData.weightState = "Obese (class 1)";
} else if (floatBMI > 35 && floatBMI < 39.99) {
this.resultBMIData.weightState = "Obese (class 2)";
} else if (floatBMI > 40) {
this.resultBMIData.weightState = "Morbidly Obese";
}
switch (this.inputBMIData.gender) {
case "Female":
this.resultBMIData.bmr = (655 + 9.6 * parseFloat(this.inputBMIData.weight) +
180 * parseFloat(this.inputBMIData.height) - (4.7 * parseFloat(this.inputBMIData.age))).toString();
break;
case "Male":
this.resultBMIData.bmr = (66 + 13.7 * parseFloat(this.inputBMIData.weight) +
500 * parseFloat(this.inputBMIData.height) - (6.8 * parseFloat(this.inputBMIData.age))).toString();
break;
default:
break
}
switch (this.inputBMIData.exercise) {
case "Hardly Exercise":
this.resultBMIData.maintainWeight = (parseFloat(this.resultBMIData.bmr) * 1.2).toString();
break;
case "Exercise 1 to 2 times a week":
this.resultBMIData.maintainWeight = (parseFloat(this.resultBMIData.bmr) * 1.375).toString();
break;
case "Exercise 3 to 5 times a week":
this.resultBMIData.maintainWeight = (parseFloat(this.resultBMIData.bmr) * 1.55).toString();
break;
case "Exercise 6 to 7 times a week":
this.resultBMIData.maintainWeight = (parseFloat(this.resultBMIData.bmr) * 1.725).toString();
break;
case "Intensive Exercise more than 7 times a week":
this.resultBMIData.maintainWeight = (parseFloat(this.resultBMIData.bmr) * 1.9).toString();
break;
default:
break
}
this.resultBMIData.achieveWeight =
(parseFloat(this.inputBMIData.dreamWeight) - parseFloat(this.inputBMIData.weight)).toString();
if (parseFloat(this.resultBMIData.achieveWeight) < 0) {
this.resultBMIData.reduce = true;
this.resultBMIData.achieveWeight = (Math.abs(parseFloat(this.resultBMIData.achieveWeight))).toString();
} else {
this.resultBMIData.reduce = false;
}
this.resultBMIData.daysWeight = (parseFloat(this.resultBMIData.achieveWeight) / 0.0064).toString();
this.resultBMIData.daysWeight = (Math.abs(parseFloat(this.resultBMIData.daysWeight))).toString();
this.bmiResultState = true;
}
closeModal() {
this.bmiResultState = false;
}
openBMI() {
this.switchBMIHIIT = true;
}
openHIIT() {
this.switchBMIHIIT = false;
}
hiitSubmit(hiitData) {
console.log(hiitData);
console.log(hiitData.valid);
if (hiitData.valid) {
this.loading.present();
this.hitService.saveHiitData(this.inputHIITData).subscribe(result => {
console.log(result);
this.loading.dismiss();
this.inputHIITData.exercise = "";
this.inputHIITData.exerciseTime = "";
this.inputHIITData.work = "";
this.inputHIITData.rest = "";
this.inputHIITData.repotition = "";
this.loadData();
}, error => {
console.log(error);
this.loading.dismiss();
})
// this.loadData();
}
}
loadData() {
this.loading.present();
this.resultHIITData.listData = new Array();
this.resultHIITData.totalExerciseTime = 0;
this.resultHIITData.totalHiitTime = 0;
this.resultHIITData.totalRestTime = 0;
this.hitService.loadHiitData().subscribe(result => {
console.log(result);
this.hiitResultState = true;
for (let list of Object(result)) {
let param = { "TPR": 0, "WRR": 0, "workout": 0, "rest": 0 };
param.TPR = Math.round(list.time / list.rep);
param.WRR = Math.round((param.TPR * 60) / (list.work + list.rest));
param.workout = param.WRR * list.work;
param.rest = param.WRR * list.rest;
this.resultHIITData.listData.push(param);
this.resultHIITData.totalExerciseTime = this.resultHIITData.totalExerciseTime + param.workout;
this.resultHIITData.totalRestTime = this.resultHIITData.totalRestTime + param.rest;
this.resultHIITData.totalHiitTime = this.resultHIITData.totalHiitTime + param.rest + param.workout;
}
this.resultHIITData.totalExerciseTime = this.resultHIITData.totalExerciseTime / 60;
this.resultHIITData.totalRestTime = this.resultHIITData.totalRestTime / 60;
this.resultHIITData.totalHiitTime = this.resultHIITData.totalHiitTime / 60;
console.log(this.resultHIITData);
this.loading.dismiss();
}, error => {
console.log(error);
this.loading.dismiss();
})
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class HiitService {
public apiURL = "http://192.168.10.159/health-app-api/";
constructor(public http: HttpClient) { }
loadHiitData() {
return this.http.get(this.apiURL + "load.php");
}
saveHiitData(hiitData) {
let param = "?time=" + hiitData.exerciseTime + "&rep=" + hiitData.repotition +
"&work=" + hiitData.work + "&rest=" + hiitData.rest + "&exercise=" + hiitData.exercise;
console.log(param);
return this.http.get(this.apiURL + "save.php" + param);
}
}
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.8.3
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Jan 03, 2019 at 07:11 PM
-- Server version: 5.6.41
-- PHP Version: 7.2.7
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: `jacksonn_hiit`
--
-- --------------------------------------------------------
--
-- Table structure for table `hiit`
--
CREATE TABLE `hiit` (
`time` float NOT NULL,
`rep` int(11) NOT NULL,
`work` int(11) NOT NULL,
`rest` int(11) NOT NULL,
`exercise` varchar(50) NOT NULL,
`serial` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
--
-- Dumping data for table `hiit`
--
INSERT INTO `hiit` (`time`, `rep`, `work`, `rest`, `exercise`, `serial`) VALUES
(60, 10, 2, 1, 'Standing Mountain Climbers', 1);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `hiit`
--
ALTER TABLE `hiit`
ADD PRIMARY KEY (`serial`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `hiit`
--
ALTER TABLE `hiit`
MODIFY `serial` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
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><?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-Type: application/json; charset=UTF-8");
include("global.php");
$conn = new mysqli(server, dbuser, dbpw, db);
$query = "select time, rep, work, rest,exercise from hiit";
$result = $conn->query($query);
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"time":'. $rs["time"].',';
$outp .= '"rep":'.$rs["rep"].',';
$outp .= '"work":'.$rs["work"].',';
$outp .= '"rest":'.$rs["rest"].',';
$outp .= '"exercise":"'. $rs["exercise"].'"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>
<file_sep><?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-Type: application/json; charset=UTF-8");
error_reporting(E_ERROR);
//https://<your url>/codetest/save.php?time=60&rep=10&work=3&rest=1&exercise=Standing%20Mountain%20Climbers
include("global.php");
try{
$conn = new mysqli(server, dbuser, dbpw, db);
$time = $_GET["time"];
$rep = $_GET["rep"];
$work = $_GET["work"];
$rest = $_GET["rest"];
$exercise = $_GET['exercise'];
// $query = "update hiit set time = $time, rep = $rep, work = $work, rest = $rest, exercise = '$exercise'";
$query = "INSERT INTO `hiit` (`time`, `rep`, `work`, `rest`, `exercise`) VALUES ('$time', '$rep', '$work', '$rest', '$exercise')";
//echo $query;
$result = $conn->query($query);
if (!$result){
$json_out = "[" . json_encode(array("result"=>0)) . "]";
}
else {
$json_out = "[" . json_encode(array("result"=>1)) . "]";
}
echo $json_out;
$conn->close();
}
catch(Exception $e) {
$json_out = "[".json_encode(array("result"=>0))."]";
echo $json_out;
}
?>
<file_sep>import { TestBed } from '@angular/core/testing';
import { HiitService } from './hiit.service';
describe('HiitService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: HiitService = TestBed.get(HiitService);
expect(service).toBeTruthy();
});
});
| f7daff5d598cb3f06424e05743e5a9147003a757 | [
"SQL",
"TypeScript",
"PHP"
]
| 7 | PHP | julian32331/ionic-php-healthapp | 82c7b7bb9da400dd4289d5196763bc532b95ad68 | 116f8945bfa7e6a82cf01d1b4b1e99b5551c6e82 |
refs/heads/master | <file_sep>var colors = ["white","black", "red", "blue", "green", "yellow", "orange", "violet"];
var currentColor;
function setup() {
createCanvas(innerWidth,innerHeight);
background("white");
header();
}
function draw()
{
if (mouseIsPressed)
{
if (mouseX < 51) {
colorChange();
}
drawing();
}
var y = 50;
for (i = 0; i < colors.length; i++){
var currentColor = new ColorBox(0, y, 50, 50, colors[i] );
currentColor.appear();
y = y + 50;
}
}
//The function that changes the color of the line being drawn
function colorChange() {
if (mouseY > 50 && mouseY < 100)
{
currentColor = "white";
}
else if (mouseY > 100 && mouseY < 150)
{
currentColor = "black";
}
else if (mouseY > 150 && mouseY < 200)
{
currentColor = "red";
}
else if (mouseY > 200 && mouseY < 250)
{
currentColor = "blue";
}
else if (mouseY > 250 && mouseY < 300)
{
currentColor = "green";
}
else if (mouseY > 300 && mouseY < 350)
{
currentColor = "yellow";
}
else if (mouseY > 350 && mouseY < 400)
{
currentColor = "orange";
}
else if (mouseY > 400 && mouseY < 450)
{
currentColor = "violet";
}
}
function drawing() {
if (mouseX > 100 && mouseY > 100)
{
stroke(currentColor);
strokeWeight(3);
line(pmouseX, pmouseY, mouseX, mouseY);
}
}
function header() {
fill("#404040");
rect(0, 0, width, 50);
textAlign(CENTER);
fill("white");
textSize(18);
text("PAINT", width / 2, 33);
}
| ad909a63ee2a9b8fbde2959660eda4af2240b61e | [
"JavaScript"
]
| 1 | JavaScript | anandRaveen/G7-U1-C15-SA-Solution | 87f2ed3b1122b4994cbde2a36063a0cc630b2591 | 3bd5c0a83b6289a20c088ac53965ff3a403c01dc |
refs/heads/master | <file_sep>FROM debian:stretch-slim
ENV DNS64_PREFIX= \
DNS64_IP6_LISTEN= \
DNS64_LISTEN=
COPY entrypoint.sh /entrypoint.sh
RUN set -ex \
&& apt-get update \
&& apt-get install -y \
bind9 \
&& rm -rf /var/lists/apt/lists/* \
&& chmod +x /entrypoint.sh
EXPOSE 53/udp 53/tcp
ENTRYPOINT ["/entrypoint.sh"]
CMD ["named"]
<file_sep>#!/bin/sh
cat > /etc/bind/named.conf.options <<EOF
options {
directory "/var/cache/bind";
auth-nxdomain no;
listen-on { ${DNS64_IP6_LISTEN}; };
listen-on-v6 { ${DNS64_IP6_LISTEN}; };
allow-query { any; };
dns64 ${DNS64_STATIC_PREFIX} {
clients { any; };
};
};
EOF
cat /etc/bind/named.conf.options
if [ "$1" = 'named' ]; then
echo "Starting named..."
exec $(which named) -g
else
exec "$@"
fi
| 5799bc208999cfa4b5678efe4b6ece08e8f754ca | [
"Dockerfile",
"Shell"
]
| 2 | Dockerfile | FreifunkMD/dns64-docker-alpine | cf9b969ef551bf2994814e4e6be6788bfe27c7a2 | 863bdab2a6813ea1367dbb09dbb9655facbe6087 |
refs/heads/master | <file_sep>var HodlersDilemma = artifacts.require("HodlersDilemma");
module.exports = function(deployer) {
deployer.deploy(HodlersDilemma, 200000000000000000, {value: 200000000000000000});
}<file_sep>import React from 'react';
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
gameWagerDataKey: null,
getIncompleteGamesDataKey: null,
stackId: null,
gameWager: null,
choice: 'split',
nonce: '',
incompleteGames: null,
games: null
};
const { drizzle, drizzleState } = this.props;
const contract = drizzle.contracts.HodlersDilemma;
contract.methods.gameWager().call().then((data) => {
this.setState({ gameWager: data });
});
contract.methods.getIncompleteGames().call().then((data) => {
this.setState({ incompleteGames: data });
});
}
componentDidMount() {
const { drizzle, drizzleState } = this.props;
const contract = drizzle.contracts.HodlersDilemma;
const gameWagerDataKey = contract.methods['gameWager'].cacheCall();
const getIncompleteGamesDataKey = contract.methods['getIncompleteGames'].cacheCall();
this.setState({ gameWagerDataKey, getIncompleteGamesDataKey });
}
startGame = (choice, nonce) => {
const { drizzle, drizzleState } = this.props;
const contract = drizzle.contracts.HodlersDilemma;
const { HodlersDilemma } = drizzleState.contracts;
const gameWager = HodlersDilemma.gameWager[this.state.gameWagerDataKey];
const choiceNonceHex = drizzle.web3.utils.toHex(choice) + drizzle.web3.utils.toHex(nonce);
const commitment = drizzle.web3.utils.keccak256(choiceNonceHex);
const stackId = contract.methods['startGame'].cacheSend(commitment, {
from: drizzleState.accounts[0],
gas: 1000000,
value: gameWager.value
});
this.setState({ stackId });
}
getTxStatus = () => {
// get the transaction states from the drizzle state
const { transactions, transactionStack } = this.props.drizzleState;
// get the transaction hash using our saved `stackId`
const txHash = transactionStack[this.state.stackId];
// if transaction hash does not exist, don't display anything
if (!txHash) return null;
// otherwise, return the transaction status
return `Transaction status: ${transactions[txHash].status}`;
}
displayGameWager = () => {
const web3 = this.props.drizzle.web3;
return <div>Game Wager: {this.state.gameWager && web3.utils.fromWei(this.state.gameWager, 'ether')} ETH</div>;
}
displayStartGameForm = () => {
return (
<form onSubmit={this.handleSubmit}>
<label>
Choice:
<select name="choice" value={this.state.choice} onChange={this.handleChange}>
<option value="split">Split</option>
<option value="steal">Steal</option>
</select>
</label>
<br />
<label>
Nonce:
<input
name="nonce"
type="text"
value={this.state.nonce}
onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
getGames = () => {
const { HodlersDilemma } = this.props.drizzleState.contracts;
const incompleteGamesRes = HodlersDilemma.getIncompleteGames[this.state.getIncompleteGamesDataKey];
let games = [];
if (incompleteGamesRes) {
const contract = this.props.drizzle.contracts.HodlersDilemma;
const incompleteGameIds = incompleteGamesRes.value;
if (this.state.incompleteGames !== incompleteGameIds) {
for (let i = 0; i < incompleteGameIds.length; i++) {
let gameId = incompleteGameIds[i];
contract.methods.getGame(gameId).call().then((data) => {
games.push(data);
});
}
this.setState({ games: games, incompleteGames: incompleteGameIds });
}
}
}
displayGames = () => {
this.getGames();
const web3 = this.props.drizzle.web3;
let games = this.state.games;
if (games && games.length > 0) {
let gamesList = [];
for (let i = 0; i < games.length; i++) {
let game = games[i];
gamesList.push(
<div key={i}>
<span>Player 1: {game[0]} </span>
<span>Wager: {web3.utils.fromWei(game[2], 'ether')} ETH</span>
</div>
);
}
return gamesList;
} else {
return 'No games found.';
}
}
handleChange = event => {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleSubmit = event => {
event.preventDefault();
this.startGame(this.state.choice, this.state.nonce);
}
render() {
return (
<div>
{this.displayGameWager()}
{this.displayStartGameForm()}
<div>{this.getTxStatus()}</div>
<div>Games: {this.displayGames()}</div>
</div>
);
};
}
export default Game; | bfa9aafb1bcb816891027ba893eda05e4f63fce4 | [
"JavaScript"
]
| 2 | JavaScript | stevenpslade/hodlers-dilemma | c2060c99f833e3e2bd7f9d8c10de27f8144bed3d | 53aeb3dea2ac1dbac56dbc1deea8384bd0882a43 |
refs/heads/master | <file_sep>Here i'll put all problems that i'm working on.
If i get one exercise solved, I'll write in a read me file inside of
the problem's folder what was my thoughts and how I solved the problem.
<file_sep>#include <bits/stdc++.h>
using namespace std;
// Verifica se os vidros cabem em con conteiners de capacidade cap;
bool verificar(vector<int> vec, int cap, int con);
int main()
{
// n numero de vidros;
// m numero de conteiners;
int n,m;
while(scanf("%d %d", &n, &m) != EOF)
{
vector<int> vec;
for(int i = 0; i < n; i++)
{
int valor;
scanf("%d", &valor);
vec.push_back(valor);
}
int menor = 1, maior = 1000000000, cap = 0;
while(menor <= maior)
{
int meio = (menor+maior)/2;
if(verificar(vec,meio,m))
{
cap = meio;
maior = meio - 1;
}
else
{
menor = meio + 1;
}
}
printf("%d\n", cap);
}
return 0;
}
bool verificar(vector<int> vec, int cap, int con)
{
// conteiners usados e peso que resta no conteiner;
int conteiner = 1;
int peso = cap;
for(int i = 0; i < vec.size(); i++)
{
// Se o vidro não cabe em um conteiner
if(vec[i] > cap)
return false;
if(vec[i] > peso)
{
if(conteiner == con)
return false;
conteiner++;
peso = cap;
}
peso -= vec[i];
}
return true;
}
| 339bd9a11fbf1af2ceeb4c1277ef3d3cdff87cc2 | [
"Markdown",
"C++"
]
| 2 | Markdown | 4rchitect/Competitive-Programming | 074a39422efc200515c537db1720f5b498788ed0 | f72e7d0567dc3a535be9cd7b499317afafb00fc7 |
refs/heads/master | <repo_name>patrick-du/Serenity<file_sep>/src/components/Journal/JournalProgressBar.js
import React from 'react';
import { Row, Col, ProgressBar } from 'react-bootstrap';
export default function JournalProgressBar(props) {
return (
<div className="mt-3">
<Row noGutters={true}>
<Col><p className="JED-ProgressBar-Title">{props.title}</p></Col>
<Col className="text-right mt-1">{props.rating}%</Col>
</Row>
<ProgressBar variant="test" className="JED-ProgressBar" now={props.rating}/>
</div>
)
}<file_sep>/src/components/Authentication/Register.js
import React, { Component } from 'react';
import axios from "axios";
import { Row, Col, Form, Button } from 'react-bootstrap';
export default class Register extends Component {
constructor(props) {
super(props);
this.state = {};
}
handleRegister = (e) => {
e.preventDefault();
let registerData = {
name: e.target.name.value,
email: e.target.email.value,
password: e.target.<PASSWORD>.value,
password2: e.target.password2.value
}
axios.post('http://localhost:3000/register', registerData)
.then((res) => {
if (res.status == 200) {
alert("Success!")
this.props.postRegister()
}
})
.catch((error) => alert(error))
};
render() {
return (
<React.Fragment>
<Row noGutters={true}>
<Col>
<p className="standardBox-title">Create new account</p>
<p className="standardBox-subTitle">Enter your credentials below</p>
</Col>
</Row>
<Form onSubmit={this.handleRegister}>
<div className="my-3">
<Form.Group controlId="name" className="my-2">
<Form.Control required name="name" type="name" placeholder="Name" />
</Form.Group>
<Form.Group controlId="email" className="my-2">
<Form.Control required name="email" type="email" placeholder="Email" />
</Form.Group>
<Form.Group controlId="password" className="my-2">
<Form.Control required name="password" type="<PASSWORD>" placeholder="<PASSWORD>" />
</Form.Group>
<Form.Group controlId="password2" className="my-2">
<Form.Control required name="password2" type="<PASSWORD>" placeholder="<PASSWORD>" />
</Form.Group>
</div>
<Button className="button-create mt-2" type="submit">Register</Button>
<Button className="button-cancel mt-2" onClick={() => window.location.reload()}>Go Back</Button>
</Form>
</React.Fragment>
);
}
}
<file_sep>/src/components/Assessments/GAD7HistoryDisplay.js
import React, { Component } from 'react'
import { Row, Col, Button, Table, Modal } from 'react-bootstrap';
import axios from 'axios';
import $ from 'jquery';
export default class GAD7HistoryDisplay extends Component {
constructor(props) {
super(props);
this.state = {
entryId: "",
GAD7Entries: [],
modalShow: false,
};
}
componentDidMount() {
this.getGAD7Entry();
}
handleClose = () => {
this.setState({ modalShow: false });
}
handleShowAndSetEntryId = (entryId) => {
this.setState({
modalShow: true,
entryId: entryId
});
}
async getGAD7Entry() {
await axios.get(`http://localhost:3000/users/5db1abf4e12aa5442862e8a6/assessments/GAD7`)
.then((res) => {
this.setState({ GAD7Entries: res.data });
})
.catch((e) => {
alert(e)
})
}
async deleteGAD7Entry() {
console.log(this.state);
await axios.delete(`http://localhost:3000/users/5db1abf4e12aa5442862e8a6/assessments/GAD7`, { data: { entryId: this.state.entryId } })
.then((res) => window.location.reload())
.catch((error) => { alert(error) })
}
render() {
return (
<React.Fragment>
<p className="my-3 ml-2">Currently, there are {this.state.GAD7Entries.length} GAD-7 entries.</p>
<hr/>
<Table responsive borderless>
<thead>
<tr>
<th width={"20%"}>Date</th>
<th width={"15%"}>Score</th>
<th width={"50%"}>Severity of Depression</th>
<th width={"10%"}></th>
</tr>
</thead>
<tbody>
{this.state.GAD7Entries.map((entry) => {
return (
<React.Fragment>
<tr>
<td>{entry.date}</td>
<td>{entry.score}</td>
<td>{entry.level}</td>
<td>
<Button className="button-delete" onClick={() => this.handleShowAndSetEntryId(entry._id)}>
Delete
</Button>
</td>
</tr>
</React.Fragment>
)
})}
</tbody>
</Table>
<Modal show={this.state.modalShow} onHide={this.handleClose} centered>
<Modal.Body className="m-3">
<Row noGutters={true}>
<p className="standardBox-title">Confirmation</p>
<span className="ml-auto"><i class="fas fa-times" onClick={this.handleClose}></i></span>
</Row>
<Row noGutters={true} className="mt-3 mb-4">
<p style={{ fontFamily: "SFProDisplay-Regular" }}>
Are you sure you want to delete this journal? This action cannot be undone and you will be unable to recover any data.
</p>
</Row>
<Row noGutters={true}>
<Button className="button-delete" onClick={() => this.deleteGAD7Entry()}>Yes, delete it!</Button>
</Row>
</Modal.Body>
</Modal>
</React.Fragment>
)
}
}<file_sep>/src/components/Navbar/TopNavbar.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import { Navbar, Nav, NavDropdown, Form, FormControl, Button } from 'react-bootstrap';
export default class TopNavbar extends Component {
render() {
return (
<Navbar expand="md" className="p-0">
<Navbar.Brand>Serenity.</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="ml-auto">
<Link to="/journal" className="linkdec navLink">
<Nav.Link href="#journal">Journal</Nav.Link>
</Link>
<Link to="/assessments" className="linkdec navLink">
<Nav.Link href="#assessments">Assessments</Nav.Link>
</Link>
<Link to="/statistics" className="linkdec navLink">
<Nav.Link href="#statistics">Statistics</Nav.Link>
</Link>
<Link to="/account" className="linkdec navLink">
<Nav.Link href="#account">Account</Nav.Link>
</Link>
</Nav>
</Navbar.Collapse>
</Navbar>
)
}
}
<file_sep>/src/components/Authentication/Welcome.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import { Row, Col, Button, ButtonGroup } from 'react-bootstrap';
import axios from 'axios';
import Loader from '../Reusable/Loader';
import Register from './Register';
import Login from './Login';
import './Welcome.css';
import $ from 'jquery';
export default class Welcome extends Component {
constructor() {
super();
this.setLoginViewFromRegister = this.setLoginViewFromRegister.bind(this);
this.state = {}
}
getJWTToken = () => {
axios.defaults.headers.common['Authorization'] = localStorage.getItem('jwtToken');
}
authorizationCheck = () => {
axios.get('http://localhost:3000/authCheck')
.then(res => {
console.log("Authorized.")
this.props.history.push("/home");
})
.catch((error) => {
console.log(error);
if (error.response.status === 401) {
this.props.history.push("/");
}
});
}
setRegisterView = () => {
$("#box").fadeOut(200);
$("#welcomeView").fadeOut(200);
$("#box").fadeIn(400);
$("#registerView").fadeIn(400);
}
setLoginView = () => {
$("#box").fadeOut(200);
$("#welcomeView").fadeOut(200);
$("#box").fadeIn(400);
$("#loginView").fadeIn(400);
}
setLoginViewFromRegister = () => {
$("#box").fadeOut(200);
$("#registerView").fadeOut(200);
$("#box").fadeIn(400);
$("#loginView").fadeIn(400);
}
componentDidMount = () => {
this.getJWTToken();
this.authorizationCheck();
}
render() {
return (
<React.Fragment>
<div className="standardBox" id="box">
<div id="welcomeView">
<Row noGutters={true}>
<Col>
<p className="welcome-title">serenity</p>
<p className="mt-1">/səˈrenədē/</p>
<ButtonGroup className="mt-3 mb-5">
<Button variant="outline-secondary" style={{ paddingTop: 0, paddingBottom: 0 }} disabled> noun </Button>
<Button variant="outline-secondary" style={{ paddingTop: 0, paddingBottom: 0 }} disabled> plural</Button>
</ButtonGroup>
<div>
<p className="welcome-definitionTitle">DEFINITIONS</p>
<p className="welcome-definitionText">1. The state or quality of being serene, calm, or tranquil;</p>
<p className="welcome-definitionText">2. <span className="welcome-definitionText2"><a href="https://patrickdu.com/work/fgfbrands" className="linkdec" target="_blank" >A social wellness app aimed to improve one's physical and mental wellbeing</a></span></p>
</div>
<div>
<p className="welcome-definitionTitle mt-4">ORIGIN OF SERENITY</p>
<p className="welcome-definitionText">1. 1400-50; late Middle English;</p>
<p className="welcome-definitionText">2. 2019; <span className="welcome-definitionText2"><a href="https://patrickdu.com" className="linkdec" target="_blank" ><NAME></a></span>;</p>
</div>
<hr className="my-5" />
<div>
<p className="standardBox-subTitle text-center">Welcome to Serenity</p>
<Button className="button-create mx-auto mt-3" style={{ width: "100%" }} onClick={this.setRegisterView}>New User</Button>
<Button className="button-login mx-auto mt-3" style={{ width: "100%" }} onClick={this.setLoginView}>Existing User</Button>
</div>
</Col>
</Row>
</div>
<div id="registerView">
<Register postRegister={this.setLoginViewFromRegister}/>
</div>
<div id="loginView">
<Login history={this.props.history}/>
</div>
</div>
{/* <div className="standardBox">
<Row noGutters={true}>
<Col>
<p className="text-center">
<a href="https://github.com/patrick-du" target="_blank" className="mr-5"><i class="fab fa-github icon0" /></a>
<a href="https://www.linkedin.com/in/patrick-du3/" target="_blank" className="mr-5" ><i class="fab fa-linkedin-in icon0 " /></a>
<a href="mailto:<EMAIL>"><i class="fas fa-paper-plane icon0" /></a>
</p>
</Col>
</Row>
</div> */}
</React.Fragment>
)
}
}<file_sep>/src/components/Assessments/GAD-7.js
import React, { Component } from 'react';
import { Row, Col, Button, Form } from 'react-bootstrap';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import axios from 'axios';
import $ from 'jquery';
import FadeIn from 'react-fade-in';
export default class GAD7 extends Component {
constructor(props) {
super(props);
this.state = {
postSubmitScore: 0,
postSubmitReturnMessage: ""
};
}
componentDidMount() {
$("#GAD7_postSubmit").css("display", "none");
}
async handleGAD7Submit(e) {
e.preventDefault();
let GAD7Entry = {
submissionArr: [
e.target.q1.value,
e.target.q2.value,
e.target.q3.value,
e.target.q4.value,
e.target.q5.value,
e.target.q6.value,
e.target.q7.value,
]
}
await axios.post('http://localhost:3000/users/5db1abf4e12aa5442862e8a6/assessments/GAD7', GAD7Entry)
.then((res) => {
if (res.status == 200) {
$("#box").fadeOut(300);
$("#GAD7_preSubmit").fadeOut(300);
$("#box").fadeIn(400);
$("#GAD7_postSubmit").fadeIn(400);
$("#postSubmitScore").text(res.data.returnMessage.score)
$("#postSubmitReturnMessage").text(res.data.returnMessage.message)
}
})
.catch((error) => alert(error))
}
render() {
return (
<FadeIn delay={150} transitionDuration={300}>
<div className="standardBox" id="box">
<div id="GAD7_preSubmit">
<Row>
<Col>
<p className="standardBox-title">General Anxiety Disorder-7</p>
</Col>
</Row>
<Row className="my-3">
<Col>
<p className="standardBox-text-subtitle">What is it?</p>
GAD-7 is a questionnaire used for rapid screeening for the presence of a clinically significant anxiety disorder in primary care and mental health settings. The symptom severity measures for the four most common anxiety disorders (Generalized Anxiety Disorder, Panic Disorder, Social Phobia, and Post Traumatic Stress Disorder). Higher GAD-7 scores correlate with disability and functional impairment in measures such as work productivity and healthcare utilization.
</Col>
</Row>
<Row className="my-3">
<Col>
<p className="standardBox-text-subtitle">Rating System</p>
Patients answer questions using numbers. A value of 0 means not at all. A value of 1 means for several days. A value of 2 means for more than half the days of the week. A value of 3 means nearly every day.
</Col>
</Row>
<div className="mt-4">
<Form onSubmit={this.handleGAD7Submit}>
<Form.Group controlId="q1" className="my-2">
<Row>
<Col>
<Form.Label><b className="mr-4">Q1.</b>Feeling nervous, anxious, or on edge?</Form.Label>
</Col>
<Col xs={2} sm={2} lg={2} xl={2} className="text-right">
<Form.Control required name="q1" type="number" min="0" max="3" />
</Col>
</Row>
</Form.Group>
<Form.Group controlId="q2" className="my-2">
<Row>
<Col>
<Form.Label><b className="mr-4">Q2.</b>Not being able to stop or control worrying?</Form.Label>
</Col>
<Col xs={2} sm={2} lg={2} xl={2} className="text-right">
<Form.Control required name="q2" type="number" min="0" max="3" />
</Col>
</Row>
</Form.Group>
<Form.Group controlId="q3" className="my-2">
<Row>
<Col>
<Form.Label><b className="mr-4">Q3.</b>Worrying too much about different things?</Form.Label>
</Col>
<Col xs={2} sm={2} lg={2} xl={2} className="text-right">
<Form.Control required name="q3" type="number" min="0" max="3" />
</Col>
</Row>
</Form.Group>
<Form.Group controlId="q4" className="my-2">
<Row>
<Col>
<Form.Label><b className="mr-4">Q4.</b>Trouble relaxing?</Form.Label>
</Col>
<Col xs={2} sm={2} lg={2} xl={2} className="text-right">
<Form.Control required name="q4" type="number" min="0" max="3" />
</Col>
</Row>
</Form.Group>
<Form.Group controlId="q5" className="my-2">
<Row>
<Col>
<Form.Label><b className="mr-4">Q5.</b>Being so restless that it's hard to sit still?</Form.Label>
</Col>
<Col xs={2} sm={2} lg={2} xl={2} className="text-right">
<Form.Control required name="q5" type="number" min="0" max="3" />
</Col>
</Row>
</Form.Group>
<Form.Group controlId="q6" className="my-2">
<Row>
<Col>
<Form.Label><b className="mr-4">Q6.</b>Becoming easily annoyed or irritable?</Form.Label>
</Col>
<Col xs={2} sm={2} lg={2} xl={2} className="text-right">
<Form.Control required name="q6" type="number" min="0" max="3" />
</Col>
</Row>
</Form.Group>
<Form.Group controlId="q7" className="my-2">
<Row>
<Col>
<Form.Label><b className="mr-4">Q7.</b>Feeling afraid as if something awful might happen?</Form.Label>
</Col>
<Col xs={2} sm={2} lg={2} xl={2} className="text-right">
<Form.Control required name="q7" type="number" min="0" max="3" />
</Col>
</Row>
</Form.Group>
<Button className="button-create mt-2" type="submit">Calculate Score</Button>
</Form>
</div>
</div>
<div id="GAD7_postSubmit">
<Row className="mb-3">
<Col>
<p className="standardBox-title text-center">Your Score: <span id="postSubmitScore"></span></p>
</Col>
</Row>
<Row className="my-3">
<Col>
<p className="standardBox-text-subtitle">Interpretation of Results</p>
<p id="postSubmitReturnMessage"></p>
</Col>
</Row>
<Row className="mt-4">
<Col>
<Button className="button-cancel" onClick={() => window.location.reload()}>Back</Button>
</Col>
<Col>
<Link to="/assessments" className="linkdec">
<Button className="button-cancel">Assessments</Button>
</Link>
</Col>
</Row>
</div>
</div>
</FadeIn>
)
}
}<file_sep>/src/components/Assessments/AssessmentHistory.js
import React, { Component } from 'react';
import { Row, Col, Tabs, Tab } from 'react-bootstrap';
import { Router, Switch, Route, Link } from 'react-router-dom';
import PHQ9HistoryDisplay from './PHQ9HistoryDisplay';
import GAD7HistoryDisplay from './GAD7HistoryDisplay';
export default class AssessmentHistory extends Component {
constructor(props) {
super(props);
this.state = {
}
}
render() {
return (
<React.Fragment>
<div className="standardBox">
<Row className="mb-4">
<Col>
<p className="standardBox-title">Assessment Submission History</p>
</Col>
</Row>
<Tabs defaultActiveKey="PHQ9" id="uncontrolled-tab-example">
<Tab eventKey="PHQ9" title="PHQ-9">
<PHQ9HistoryDisplay />
</Tab>
<Tab eventKey="GAD7" title="GAD-7">
<GAD7HistoryDisplay />
</Tab>
</Tabs>
</div>
</React.Fragment>
)
}
}<file_sep>/src/components/Authentication/Login.js
import React, { Component } from 'react';
import axios from 'axios';
import { Row, Col, Form, Button } from 'react-bootstrap';
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
};
}
handleLogin = (e) => {
e.preventDefault();
let loginData = {
email: e.target.email.value,
password: e.target.password.value
}
axios.post('http://localhost:3000/login', loginData)
.then((res) => {
localStorage.setItem('jwtToken', res.data.token);
this.setState({ message: '' });
this.props.history.push('/journal')
})
.catch((error) => {
alert(error)
if (error.response.status === 400) {
alert(error.response.data);
} else if (error.response.status === 401) {
alert(error.response.data.msg)
this.setState({ message: 'Login Failed. Username or password does not match.' });
}
});
};
render() {
const { email, password, message } = this.state;
return (
<React.Fragment>
<Row noGutters={true}>
<Col>
<p className="standardBox-title">Welcome back</p>
<p className="standardBox-subTitle">Please sign in to continue</p>
</Col>
</Row>
<Form onSubmit={this.handleLogin}>
<div className="my-3">
<Form.Group controlId="email" className="my-2">
<Form.Control required name="email" type="email" placeholder="Email" />
</Form.Group>
<Form.Group controlId="password" className="my-2">
<Form.Control required name="password" type="<PASSWORD>" placeholder="<PASSWORD>" />
</Form.Group>
</div>
<Button className="button-login mt-2" type="submit">Login</Button>
<Button className="button-cancel mt-2" onClick={() => window.location.reload()}>Go Back</Button>
</Form>
</React.Fragment>
);
}
}<file_sep>/src/components/Statistics/Statistics.js
import React, { Component } from 'react';
import { Row, Col, Tabs, Tab } from 'react-bootstrap';
import Chartist from 'chartist';
import axios from 'axios';
import FadeIn from 'react-fade-in';
import $ from 'jquery';
import StatisticsTrendChart from './StatisticsTrendChart';
export default class Statistics extends Component {
constructor(props) {
super(props);
this.state = {
stressTrend: [],
depressionTrend: [],
anxietyTrend: [],
};
}
async getAllTrends() {
axios.get(`http://localhost:3000/users/5db1abf4e12aa5442862e8a6/statistics/trends`)
.then((res) => {
console.log(res.data)
this.setState({
stressTrend: res.data.stressArr,
depressionTrend: res.data.depressionArr,
anxietyTrend: res.data.anxietyArr
})
console.log(this.state)
this.generateChart("#chartAll", [this.state.stressTrend, this.state.depressionTrend, this.state.anxietyTrend])
this.generateChart("#chartStress", [this.state.stressTrend])
this.generateChart("#chartDepression", [this.state.depressionTrend])
this.generateChart("#chartAnxiety", [this.state.anxietyTrend])
})
.catch((e) => {
alert("bye")
console.log(e)
})
}
generateChart(idSelector, data) {
new Chartist.Line(idSelector, {
labels: ['Entries'],
series: data
}, {
high: 100,
low: 0,
axisY: {
onlyInteger: true,
referenceValue: 5
},
axisX: {
// We can disable the grid for this axis
showGrid: false,
// and also don't show the label
showLabel: false
},
fullWidth: true,
});
}
hideCharts(chartIdArr) {
chartIdArr.forEach(chart => $(chart).css("display","none"))
}
componentDidMount() {
this.getAllTrends();
}
render() {
return (
<FadeIn delay={150} transitionDuration={300}>
<div className="standardBox">
<Row>
<Col>
<p className="standardBox-title">Statistics and Trends</p>
</Col>
<Col className="text-right">
</Col>
</Row>
</div>
<StatisticsTrendChart name="Trends of Stress, Depression, Anxiety" chartId="chartAll"/>
<StatisticsTrendChart name="Trends of Stress" chartId="chartStress"/>
<StatisticsTrendChart name="Trends of Depression" chartId="chartDepression"/>
<StatisticsTrendChart name="Trends of Anxiety" chartId="chartAnxiety"/>
</FadeIn>
)
}
}<file_sep>/src/components/Assessments/PHQ-9.js
import React, { Component } from 'react';
import { Row, Col, Button, Form } from 'react-bootstrap';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import axios from 'axios';
import $ from 'jquery';
import FadeIn from 'react-fade-in';
export default class PHQ9 extends Component {
constructor(props) {
super(props);
this.state = {
postSubmitScore: 0,
postSubmitReturnMessage: ""
};
}
componentDidMount() {
$("#PHQ9_postSubmit").css("display", "none");
}
async handlePHQ9Submit(e) {
e.preventDefault();
let PHQ9Entry = {
submissionArr: [
e.target.q1.value,
e.target.q2.value,
e.target.q3.value,
e.target.q4.value,
e.target.q5.value,
e.target.q6.value,
e.target.q7.value,
e.target.q8.value,
e.target.q9.value
]
}
await axios.post('http://localhost:3000/users/5db1abf4e12aa5442862e8a6/assessments/PHQ9', PHQ9Entry)
.then((res) => {
if (res.status == 200) {
$("#box").fadeOut(300);
$("#PHQ9_preSubmit").fadeOut(300);
$("#box").fadeIn(400);
$("#PHQ9_postSubmit").fadeIn(400);
$("#postSubmitScore").text(res.data.returnMessage.score)
$("#postSubmitReturnMessage").text(res.data.returnMessage.message)
}
})
.catch((error) => alert(error))
}
render() {
return (
<FadeIn delay={150} transitionDuration={300}>
<div className="standardBox" id="box">
<div id="PHQ9_preSubmit">
<Row>
<Col>
<p className="standardBox-title">Patient Health Questionnaire-9</p>
</Col>
</Row>
<Row className="my-3">
<Col>
<p className="standardBox-text-subtitle mb-1">What is it?</p>
PHQ-9 is used to provisionally diagnose depression and grade the severity of symptoms in general medical and mental health settings. It determines severity of initial symptoms and monitors symptoms changes and treatment effects over time. Higher scores are associated with decreased functional status and increased symptom-related difficulties, sick days, and healthcare utilization.
</Col>
</Row>
<Row className="my-3">
<Col>
<p className="standardBox-text-subtitle mb-1">Rating System</p>
Patients answer questions using numbers. A value of 0 means not at all. A value of 1 means for several days. A value of 2 means for more than half the days of the week. A value of 3 means nearly every day.
</Col>
</Row>
<div className="mt-4">
<Form onSubmit={this.handlePHQ9Submit}>
<Form.Group controlId="q1" className="my-2">
<Row>
<Col>
<Form.Label> <b className="mr-4">Q1.</b>Little interest or pleasure in doing things? </Form.Label>
</Col>
<Col xs={2} sm={2} md={2} lg={2} xl={2} className="text-right">
<Form.Control required name="q1" type="number" min="0" max="3" />
</Col>
</Row>
</Form.Group>
<Form.Group controlId="q2" className="my-2">
<Row>
<Col>
<Form.Label> <b className="mr-4">Q2.</b>Feeling down, depressed, or hopeless? </Form.Label>
</Col>
<Col xs={2} sm={2} md={2} lg={2} xl={2} className="text-right">
<Form.Control required name="q2" type="number" min="0" max="3" />
</Col>
</Row>
</Form.Group>
<Form.Group controlId="q3" className="my-2">
<Row>
<Col>
<Form.Label> <b className="mr-4">Q3.</b>Trouble falling or staying asleep, or sleeping too much? </Form.Label>
</Col>
<Col xs={2} sm={2} md={2} lg={2} xl={2} className="text-right">
<Form.Control required name="q3" type="number" min="0" max="3" />
</Col>
</Row>
</Form.Group>
<Form.Group controlId="q4" className="my-2">
<Row>
<Col>
<Form.Label> <b className="mr-4">Q4.</b>Feeling tired or having little energy? </Form.Label>
</Col>
<Col xs={2} sm={2} md={2} lg={2} xl={2} className="text-right">
<Form.Control required name="q4" type="number" min="0" max="3" />
</Col>
</Row>
</Form.Group>
<Form.Group controlId="q5" className="my-2">
<Row>
<Col>
<Form.Label> <b className="mr-4">Q5.</b>Poor appetite or overeating? </Form.Label>
</Col>
<Col xs={2} sm={2} md={2} lg={2} xl={2} className="text-right">
<Form.Control required name="q5" type="number" min="0" max="3" />
</Col>
</Row>
</Form.Group>
<Form.Group controlId="q6" className="my-2">
<Row>
<Col>
<Form.Label> <b className="mr-4">Q6.</b>Feeling bad about yourself or that you are a failure or have let yourself or your family down? </Form.Label>
</Col>
<Col xs={2} sm={2} md={2} lg={2} xl={2} className="text-right">
<Form.Control required name="q6" type="number" min="0" max="3" />
</Col>
</Row>
</Form.Group>
<Form.Group controlId="q7" className="my-2">
<Row>
<Col>
<Form.Label> <b className="mr-4">Q7.</b>Trouble concentrating on things, such as reading the newspaper or watching television? </Form.Label>
</Col>
<Col xs={2} sm={2} md={2} lg={2} xl={2} className="text-right">
<Form.Control required name="q7" type="number" min="0" max="3" />
</Col>
</Row>
</Form.Group>
<Form.Group controlId="q8" className="my-2">
<Row>
<Col>
<Form.Label> <b className="mr-4">Q8.</b>Moving or speaking so slowly that other people could have noticed? Or so fidgety or restless that you have been moving a lot more than usual? </Form.Label>
</Col>
<Col xs={2} sm={2} md={2} lg={2} xl={2} className="text-right">
<Form.Control required name="q8" type="number" min="0" max="3" />
</Col>
</Row>
</Form.Group>
<Form.Group controlId="q9" className="my-2">
<Row>
<Col>
<Form.Label> <b className="mr-4">Q9.</b>Thoughts that you would be better off dead or thoughts of hurting yourself in some way? </Form.Label>
</Col>
<Col xs={2} sm={2} md={2} lg={2} xl={2} className="text-right">
<Form.Control required name="q9" type="number" min="0" max="3" />
</Col>
</Row>
</Form.Group>
<Button className="button-create mt-2" type="submit">Calculate Score</Button>
</Form>
</div>
</div>
<div id="PHQ9_postSubmit">
<Row className="mb-3">
<Col>
<p className="standardBox-title text-center">Your Score: <span id="postSubmitScore"></span></p>
</Col>
</Row>
<Row className="my-3">
<Col>
<p className="standardBox-text-subtitle">Interpretation of Results</p>
<p id="postSubmitReturnMessage"></p>
</Col>
</Row>
<Row className="mt-4">
<Col>
<Button className="button-cancel" onClick={() => window.location.reload()}>Back</Button>
</Col>
<Col>
<Link to="/assessments" className="linkdec">
<Button className="button-cancel">Assessments</Button>
</Link>
</Col>
</Row>
</div>
</div>
</FadeIn>
)
}
}<file_sep>/src/App.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import axios from 'axios'
import { PrivateRoute } from './PrivateRoute';
// Auth Component Imports
import Welcome from './components/Authentication/Welcome';
import Register from './components/Authentication/Register';
import Login from './components/Authentication/Login';
// Protected Component Imports
import TopNavbar from './components/Navbar/TopNavbar';
import Journal from './components/Journal/Journal';
import Assessments from './components/Assessments/Assessments';
import PHQ9 from './components/Assessments/PHQ-9';
import GAD7 from './components/Assessments/GAD-7';
import Statistics from './components/Statistics/Statistics';
import Account from './components/Account/Account';
// CSS Imports
import 'bootstrap/dist/css/bootstrap.min.css';
import './components/Reusable/Loader.css';
import './components/Navbar/TopNavbar.css';
import './components/Journal/Journal.css';
import './components/Assessments/Assessments.css';
import './components/Account/Account.css';
import './App.css';
export default class App extends Component {
render() {
return (
<Router>
<div class="app">
<TopNavbar/>
<Switch>
<Route exact path="/" component={Welcome} />
<Route exact path="/register" component={Register} />
<Route exact path="/login" component={Login} />
<PrivateRoute exact path="/journal" component={Journal}/>
<PrivateRoute exact path="/assessments" component={Assessments}/>
<PrivateRoute exact path="/assessments/PHQ9" component={PHQ9}/>
<PrivateRoute exact path="/assessments/GAD7" component={GAD7}/>
<PrivateRoute exact path="/statistics" component={Statistics}/>
<PrivateRoute exact path="/account" component={Account}/>
</Switch>
</div>
</Router>
)
}
}
<file_sep>/src/components/Journal/Journal.js
import React, { Component } from "react";
import { Row, Col, Button } from "react-bootstrap";
import axios from "axios";
import SectionTitle from "../Reusable/SectionTitle";
import CreateNewJournal from "../Journal/CreateNewJournal";
import JournalEntryDisplay from "../Journal/JournalEntryDisplay";
import Loader from "../Reusable/Loader";
import FadeIn from "react-fade-in";
export default class Journal extends Component {
constructor(props) {
super(props);
this.state = {
journalEntries: [],
isReady: false,
userJournalsExist: false
};
}
async getUserJournals() {
axios
.get(`http://localhost:3000/users/<PASSWORD>/journals`)
.then(res => {
setTimeout(
() => this.setState({ journalEntries: res.data, isReady: true }),
200
);
})
.catch(e => {
console.log(e);
});
}
async getJWT() {
axios.defaults.headers.common["Authorization"] = localStorage.getItem(
"jwtToken"
);
}
componentDidMount() {
this.getJWT();
this.getUserJournals();
}
render() {
// if (!this.state.isReady) {
// return (
// <FadeIn>
// <p>...</p>
// <p>...</p>
// <p>...</p>
// <p>...</p>
// <p>...</p>
// <p>...</p>
// <p>...</p>
// <p>...</p>
// </FadeIn>
// )
// } else if (this.state.isReady) {
return (
<Row noGutters={true}>
<Col>
<FadeIn delay={150} transitionDuration={300}>
<CreateNewJournal />
<JournalEntryDisplay journals={this.state.journalEntries} />
</FadeIn>
</Col>
</Row>
);
}
}
<file_sep>/src/components/Assessments/Assessments.js
import React, { Component } from 'react';
import { Row, Col } from 'react-bootstrap';
import AvailableAssessments from './AvailableAssessments';
import AssessmentHistory from './AssessmentHistory';
import FadeIn from 'react-fade-in';
export default class Assessments extends Component {
constructor(props) {
super(props);
this.state = {
};
};
render() {
return (
<Row noGutters={true}>
<Col>
<FadeIn delay={150} transitionDuration={500}>
<AvailableAssessments />
<AssessmentHistory/>
</FadeIn>
</Col>
</Row>
)
}
} | db32c3983c9d94c7b78afd008df06c219e248d8e | [
"JavaScript"
]
| 13 | JavaScript | patrick-du/Serenity | 398e38708a7abf4cd0536cd4c36ff4e6c0e14e44 | 808ec7837feac2f01064e8d19dc29d1eaec56038 |
refs/heads/master | <repo_name>mindis/active-directory-b2c-android-native-nodejs-webapi<file_sep>/android-oauth-client/samples/src/main/java/com/microsoft/oauth/samples/azureb2c/Azureb2cConstants.java
package com.microsoft.oauth.samples.azureb2c;
public class Azureb2cConstants {
/* TODO: Update the following 3 constants */
/* Obtained from registering your app at portal.azure.com */
/* Labeled as Application ID in the Portal */
public static final String CLIENT_ID = "YOUR CLIENT ID";
/* Endpoints the app talks to, replace with your config info */
public static final String AUTHORIZATION_ENDPOINT_URL =
"https://login.microsoftonline.com/tfp/<Tenant Name e.g. mytenant.onmicrosoft.com>/<My SiSu Policy Name>/oauth2/v2.0/authorize";
public static final String TOKEN_SERVER_URL =
"https://login.microsoftonline.com/tfp/<Tenant Name e.g. mytenant.onmicrosoft.com>/<My SiSu Policy Name>/oauth2/v2.0/token";
/* Does not need to be updated */
public static final String REDIRECT_URL = "https://login.microsoftonline.com/tfp/oauth2/nativeclient";
private Azureb2cConstants() {
}
}
| 05c274eab4fb8d37ba6a08f532a6300aa0c4d157 | [
"Java"
]
| 1 | Java | mindis/active-directory-b2c-android-native-nodejs-webapi | 531cfcbbd9f588178f6a3df01f36da9460fa966d | f8fda13a08d554d56b12923d83ab004f4c4c5d1d |
refs/heads/master | <file_sep>class FARule < Struct.new(:state, :character, :next_state)
def applies_to?(state, character)
self.state == state && self.character == character
end
def follow
next_state
end
def inspect
"#<FARule #{state.inspect} --#{character}--> #{next_state.inspect}>"
end
end
require 'set'
class NFARulebook < Struct.new(:rules)
def next_states(states, character)
states.flat_map { |state| follow_rules_for(state, character) }.to_set
end
def follow_rules_for(state, character)
rules_for(state, character).map(&:follow)
end
def rules_for(state, character)
rules.select { |rule| rule.applies_to?(state, character)}
end
end
class NFA < Struct.new(:current_states, :accept_states, :rulebook)
def accepting?
(current_states & accept_states).any?
end
def read_character(character)
self.current_states = rulebook.next_states(current_states, character)
end
def read_string(string)
string.chars.each do |character|
read_character(character)
end
end
end
class NFADesign < Struct.new(:start_state, :accept_states, :rulebook)
def accepts?(string)
to_nfa.tap { |nfa| nfa.read_string(string) }.accepting?
end
def to_nfa
NFA.new(Set[start_state], accept_states, rulebook)
end
end
rulebook = NFARulebook.new([
FARule.new(1, 'a', 1), FARule.new(1, 'b', 1), FARule.new(1, 'b', 2),
FARule.new(2, 'a', 3), FARule.new(2, 'b', 3),
FARule.new(3, 'a', 4), FARule.new(3, 'b', 4)
])
rulebook.next_states(Set[1], 'b')
rulebook.next_states(Set[1, 2], 'a')
NFA.new(Set[1], [4], rulebook).accepting?
NFA.new(Set[1, 2, 4], [4], rulebook).accepting?
nfa = NFA.new(Set[1], [4], rulebook); nfa.accepting?
nfa.read_character('b'); nfa.accepting?
nfa.read_character('a'); nfa.accepting?
nfa.read_character('b'); nfa.accepting?
nfa = NFA.new(Set[1], [4], rulebook)
nfa.accepting?
nfa.read_string('bbbbb'); nfa.accepting?
nfa_design = NFADesign.new(1, [4], rulebook)
nfa_design.accepts?('bab')
nfa_design.accepts?('bbbbb')
nfa_design.accepts?('bbabb')<file_sep>class SKISymbol < Struct.new(:name)
def to_s
name.to_s
end
def inspect
to_s
end
def combinator
self
end
def arguments
[]
end
def callable?(*arguments)
false
end
def reducible?
false
end
def as_a_function_of(name)
if self.name == name
I
else
SKICall.new(K, self)
end
end
def to_iota
self
end
end
class SKICall < Struct.new(:left, :right)
def to_s
"#{left}[#{right}]"
end
def inspect
to_s
end
def combinator
left.combinator
end
def arguments
left.arguments + [right]
end
def reducible?
left.reducible? || right.reducible? || combinator.callable?(*arguments)
end
def reduce
if left.reducible?
SKICall.new(left.reduce, right)
elsif right.reducible?
SKICall.new(left, right.reduce)
else
combinator.call(*arguments)
end
end
def as_a_function_of(name)
left_function = left.as_a_function_of(name)
right_function = right.as_a_function_of(name)
SKICall.new(SKICall.new(S, left_function), right_function)
end
def to_iota
SKICall.new(left.to_iota, right.to_iota)
end
end
class SKICombinator < SKISymbol
def as_a_function_of(name)
SKICall.new(K, self)
end
end
S, K, I = [:S, :K, :I].map { |name| SKICombinator.new(name) }
# S[a][b][c]をa[c][b[c]]に簡約する
def S.call(a, b, c)
SKICall.new(SKICall.new(a, c), SKICall.new(b, c))
end
def S.callable?(*arguments)
arguments.length == 3
end
def S.to_iota
SKICall.new(IOTA, SKICall.new(IOTA, SKICall.new(IOTA, SKICall.new(IOTA, IOTA))))
end
# K[a][b]をaに簡約する
def K.call(a, b)
a
end
def K.callable?(*arguments)
arguments.length == 2
end
def K.to_iota
SKICall.new(IOTA, SKICall.new(IOTA, SKICall.new(IOTA, IOTA)))
end
# I[a]をaに簡約する
def I.call(a)
a
end
def I.callable?(*arguments)
arguments.length == 1
end
def I.to_iota
SKICall.new(IOTA, IOTA)
end
IOTA = SKICombinator.new('ι')
# ι[a]をa[S][K]に簡約する
def IOTA.call(a)
SKICall.new(SKICall.new(a, S), K)
end
def IOTA.callable?(*arguments)
arguments.length == 1
end
expression = S.to_iota
# while expression.reducible?
# puts expression
# expression = expression.reduce
# end; puts expression
expression = K.to_iota
# while expression.reducible?
# puts expression
# expression = expression.reduce
# end; puts expression
expression = I.to_iota
# while expression.reducible?
# puts expression
# expression = expression.reduce
# end; puts expression
x = SKISymbol.new(:x)
identity = SKICall.new(SKICall.new(S, K), SKICall.new(K, K))
expression = SKICall.new(identity, x)
# while expression.reducible?
# puts expression
# expression = expression.reduce
# end; puts expression
class LCVariable < Struct.new(:name)
def to_s
name.to_s
end
def inspect
to_s
end
def replace(name, replacement)
if self.name == name
replacement
else
self
end
end
def callable?
false
end
def reducible?
false
end
def to_ski
SKISymbol.new(name)
end
end
class LCFunction < Struct.new(:parameter, :body)
def to_s
"-> #{parameter} { #{body} }"
end
def inspect
to_s
end
def replace(name, replacement)
if parameter == name
self
else
LCFunction.new(parameter, body.replace(name, replacement))
end
end
def call(argument)
body.replace(parameter, argument)
end
def callable?
true
end
def reducible?
false
end
def to_ski
body.to_ski.as_a_function_of(parameter)
end
end
class LCCall < Struct.new(:left, :right)
def to_s
"#{left}[#{right}]"
end
def inspect
to_s
end
def replace(name, replacement)
LCCall.new(left.replace(name, replacement), right.replace(name, replacement))
end
def callable?
false
end
def reducible?
left.reducible? || right.reducible? || left.callable?
end
def reduce
if left.reducible?
LCCall.new(left.reduce, right)
elsif right.reducible?
LCCall.new(left, right.reduce)
else
left.call(right)
end
end
def to_ski
SKICall.new(left.to_ski, right.to_ski)
end
end
two =
LCFunction.new(:p,
LCFunction.new(:x,
LCCall.new(LCVariable.new(:p), LCCall.new(LCVariable.new(:p), LCVariable.new(:x)))
)
)
two.to_ski
two.to_ski.to_iota
inc, zero = SKISymbol.new(:inc), SKISymbol.new(:zero)
expression = SKICall.new(SKICall.new(two.to_ski.to_iota, inc), zero)
expression = expression.reduce while expression.reducible?
expression<file_sep>class Sign < Struct.new(:name)
NEGATIVE, ZERO, POSITIVE = [:negative, :zero, :positive].map { |name| new(name) }
UNKNOWN = new(:unknown)
def inspect
"#<Sign #{name}>"
end
def *(other_sign)
if [self, other_sign].include?(ZERO)
ZERO
elsif [self, other_sign].include?(UNKNOWN)
UNKNOWN
elsif self == other_sign
POSITIVE
else
NEGATIVE
end
end
def +(other_sign)
if self == other_sign || other_sign == ZERO
self
elsif self == ZERO
other_sign
else
UNKNOWN
end
end
def <=(other_sign)
self == other_sign || other_sign == UNKNOWN
end
end
class Numeric
def sign
if self < 0
Sign::NEGATIVE
elsif zero?
Sign::ZERO
else
Sign::POSITIVE
end
end
end
def calculate(x, y, z)
(x * y) * (x * z)
end
def sum_of_squares(x, y)
(x * x) + (y * y)
end
Sign::POSITIVE + Sign::POSITIVE
Sign::NEGATIVE + Sign::ZERO
Sign::NEGATIVE + Sign::POSITIVE
Sign::POSITIVE + Sign::UNKNOWN
Sign::UNKNOWN + Sign::ZERO
Sign::POSITIVE + Sign::NEGATIVE + Sign::NEGATIVE
(Sign::POSITIVE + Sign::NEGATIVE) * Sign::ZERO + Sign::POSITIVE
(10 + 3).sign == (10.sign + 3.sign)
(-5 + 0).sign == (-5.sign + 0.sign)
(6 + -9).sign == (6.sign + -9.sign)
(6 + -9).sign
6.sign + -9.sign
Sign::POSITIVE <= Sign::POSITIVE
Sign::POSITIVE <= Sign::UNKNOWN
Sign::POSITIVE <= Sign::NEGATIVE
(6 * -9).sign <= (6.sign * -9.sign)
(-5 + 0).sign <= (-5.sign + 0.sign)
(6 + -9).sign <= (6.sign + -9.sign)
inputs = Sign::NEGATIVE, Sign::ZERO, Sign::NEGATIVE
outputs = inputs.product(inputs).map { |x, y| sum_of_squares(x, y) }
outputs.uniq<file_sep>require 'treetop'
require './lambda_calculus'
parser= LambdaCalculusParser.new
result = parser.parse('-> x { x[x] } [-> y { y }]')
p result.get<file_sep>class LCVariable < Struct.new(:name)
def to_s
name.to_s
end
def inspect
to_s
end
end
class LCFunction < Struct.new(:parameter, :body)
def to_s
"-> #{parameter} { #{body} }"
end
def inspect
to_s
end
end
class LCCall < Struct.new(:left, :right)
def to_s
"#{left}[#{right}]"
end
def inspect
to_s
end
end
one =
LCFunction.new(:p,
LCFunction.new(:x,
LCCall.new(LCVariable.new(:p), LCVariable.new(:x))
)
)
increment =
LCFunction.new(:n,
LCFunction.new(:p,
LCFunction.new(:x,
LCCall.new(
LCVariable.new(:p),
LCCall.new(
LCCall.new(LCVariable.new(:n), LCVariable.new(:p)),
LCVariable.new(:x)
)
)
)
)
)
add =
LCFunction.new(:m,
LCFunction.new(:n,
LCCall.new(LCCall.new(LCVariable.new(:n), increment), LCVariable.new(:m))
)
)
# 参照
# ADD = -> m { -> n { n[INCREMENT][m] } }<file_sep>class Tape < Struct.new(:left, :middle, :right, :blank)
def inspect
"#<Tape #{left.join}(#{middle})#{right.join}>"
end
def write(character)
Tape.new(left, character, right, blank)
end
def move_head_left
Tape.new(left[0..-2], left.last || blank, [middle] + right, blank)
end
def move_head_right
Tape.new(left + [middle], right.first || blank, right.drop(1), blank)
end
end
class TMConfiguration < Struct.new(:state, :tape)
end
class TMRule < Struct.new(:state, :character, :next_state,
:write_character, :direction)
def applies_to?(configuration)
state == configuration.state && character == configuration.tape.middle
end
def follow(configuration)
TMConfiguration.new(next_state, next_tape(configuration))
end
def next_tape(configuration)
written_tape = configuration.tape.write(write_character)
case direction
when :left
written_tape.move_head_left
when :right
written_tape.move_head_right
end
end
end
class DTMRulebook < Struct.new(:rules)
def next_configuration(configuration)
rule_for(configuration).follow(configuration)
end
def rule_for(configuration)
rules.detect { |rule| rule.applies_to?(configuration) }
end
def applies_to?(configuration)
!rule_for(configuration).nil?
end
end
class DTM < Struct.new(:current_configuration, :accept_states, :rulebook)
def accepting?
accept_states.include?(current_configuration.state)
end
def step
self.current_configuration = rulebook.next_configuration(current_configuration)
end
def stuck?
!accepting? && !rulebook.applies_to?(current_configuration)
end
def run
step until accepting? || stuck?
end
end
tape = Tape.new(['1', '0', '1'], '1', [], '_')
tape.middle
tape
tape.move_head_left
tape.write('0')
tape.move_head_right
tape.move_head_right.write('0')
rule = TMRule.new(1, '0', 2, '1', :right)
rule.applies_to?(TMConfiguration.new(1, Tape.new([], '0', [], '_')))
rule.applies_to?(TMConfiguration.new(1, Tape.new([], '1', [], '_')))
rule.applies_to?(TMConfiguration.new(2, Tape.new([], '0', [], '_')))
rule.follow(TMConfiguration.new(1, Tape.new([], '0', [], '_')))
# 「2進数をインクリメントする」チューリングマシンのDTMRulebook
rulebook = DTMRulebook.new([
TMRule.new(1, '0', 2, '1', :right),
TMRule.new(1, '1', 1, '0', :left),
TMRule.new(1, '_', 2, '1', :right),
TMRule.new(2, '0', 2, '0', :right),
TMRule.new(2, '1', 2, '1', :right),
TMRule.new(2, '_', 3, '_', :left)
])
configuration = TMConfiguration.new(1, tape)
configuration = rulebook.next_configuration(configuration)
configuration = rulebook.next_configuration(configuration)
configuration = rulebook.next_configuration(configuration)
dtm = DTM.new(TMConfiguration.new(1, tape), [3], rulebook)
dtm.current_configuration
dtm.accepting?
dtm.step; dtm.current_configuration
dtm.accepting?
dtm.run
dtm.current_configuration
dtm.accepting?
# 行き詰まり状態
tape = Tape.new(['1', '2', '1'], '1', [], '_')
dtm = DTM.new(TMConfiguration.new(1, tape), [3], rulebook)
dtm.run
dtm.current_configuration
dtm.accepting?
dtm.stuck?
# 'aaabbbccc'のような文字列を認識するためのチューリングマシン
rulebook = DTMRulebook.new([
# 状態1:aを探して右にスキャンする
TMRule.new(1, 'X', 1, 'X', :right), # Xをスキップする
TMRule.new(1, 'a', 2, 'X', :right), # aを消して、状態2に進む
TMRule.new(1, '_', 6, '_', :left), # 空白を見つけて、状態6(受理状態)に進む
# 状態2:bを探して右にスキャンする
TMRule.new(2, 'a', 2, 'a', :right), # aをスキップする
TMRule.new(2, 'X', 2, 'X', :right), # Xをスキップする
TMRule.new(2, 'b', 3, 'X', :right), # bを消して、状態3に進む
# 状態3:cを探して右にスキャンする
TMRule.new(3, 'b', 3, 'b', :right), # bをスキップする
TMRule.new(3, 'X', 3, 'X', :right), # Xをスキップする
TMRule.new(3, 'c', 4, 'X', :right), # cを消して、状態4に進む
# 状態4:文字列の末尾を探して右にスキャンする
TMRule.new(4, 'c', 4, 'c', :right), # cをスキップする
TMRule.new(4, '_', 5, '_', :left), # 空白を見つけて、状態5に進む
# 状態5:文字列の先頭を探して左にスキャンする
TMRule.new(5, 'a', 5, 'a', :left), # aをスキップする
TMRule.new(5, 'b', 5, 'b', :left), # bをスキップする
TMRule.new(5, 'c', 5, 'c', :left), # cをスキップする
TMRule.new(5, 'X', 5, 'X', :left), # Xをスキップする
TMRule.new(5, '_', 1, '_', :right) # 空白を見つけて、状態1に進む
])
tape = Tape.new([], 'a', ['a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'], '_')
dtm = DTM.new(TMConfiguration.new(1, tape), [6], rulebook)
10.times { dtm.step }; dtm.current_configuration
25.times { dtm.step }; dtm.current_configuration
dtm.run; dtm.current_configuration
# 文字列の先頭にある文字を末尾にコピーする(内部ストレージ)
rulebook = DTMRulebook.new([
# 状態1:テープから先頭の文字を読む
TMRule.new(1, 'a', 2, 'a', :right), # aを覚える
TMRule.new(1, 'b', 3, 'b', :right), # bを覚える
TMRule.new(1, 'c', 4, 'c', :right), # cを覚える
# 状態2:文字列の末尾を探して右にスキャンする(aを覚えている)
TMRule.new(2, 'a', 2, 'a', :right), # aをスキップする
TMRule.new(2, 'b', 2, 'b', :right), # bをスキップする
TMRule.new(2, 'c', 2, 'c', :right), # cをスキップする
TMRule.new(2, '_', 5, 'a', :right), # 空白を見つけて、aを書く
# 状態3:文字列の末尾を探して右にスキャンする(bを覚えている)
TMRule.new(3, 'a', 3, 'a', :right), # aをスキップする
TMRule.new(3, 'b', 3, 'b', :right), # bをスキップする
TMRule.new(3, 'c', 3, 'c', :right), # cをスキップする
TMRule.new(3, '_', 5, 'b', :right), # 空白を見つけて、bを書く
# 状態4:文字列の末尾を探して右にスキャンする(cを覚えている)
TMRule.new(4, 'a', 4, 'a', :right), # aをスキップする
TMRule.new(4, 'b', 4, 'b', :right), # bをスキップする
TMRule.new(4, 'c', 4, 'c', :right), # cをスキップする
TMRule.new(4, '_', 5, 'c', :right) # 空白を見つけて、cを書く
])
tape = Tape.new([], 'b', ['c', 'b', 'c', 'a'], '_')
dtm = DTM.new(TMConfiguration.new(1, tape), [5], rulebook)
dtm.run; dtm.current_configuration.tape
# 「数をインクリメントする」機械から「数に3を足す」機械を構築する
def increment_rules(start_state, return_state)
incrementing = start_state
finishing = Object.new
finished = return_state
[
TMRule.new(incrementing, '0', finishing, '1', :right),
TMRule.new(incrementing, '1', incrementing, '0', :left),
TMRule.new(incrementing, '_', finishing, '1', :right),
TMRule.new(finishing, '0', finishing, '0', :right),
TMRule.new(finishing, '1', finishing, '1', :right),
TMRule.new(finishing, '_', finished, '_', :left)
]
end
added_zero, added_one, added_two, added_three = 0, 1, 2, 3
rulebook = DTMRulebook.new(
increment_rules(added_zero, added_one) +
increment_rules(added_one, added_two) +
increment_rules(added_two, added_three)
)
rulebook.rules.length
tape = Tape.new(['1', '0', '1'], '1', [], '_')
dtm = DTM.new(TMConfiguration.new(added_zero, tape), [added_three], rulebook)
dtm.run; dtm.current_configuration.tape<file_sep>class LCVariable < Struct.new(:name)
def to_s
name.to_s
end
def inspect
to_s
end
def replace(name, replacement)
if self.name == name
replacement
else
self
end
end
def callable?
false
end
def reducible?
false
end
end
class LCFunction < Struct.new(:parameter, :body)
def to_s
"-> #{parameter} { #{body} }"
end
def inspect
to_s
end
def replace(name, replacement)
if parameter == name
self
else
LCFunction.new(parameter, body.replace(name, replacement))
end
end
def call(argument)
body.replace(parameter, argument)
end
def callable?
true
end
def reducible?
false
end
end
class LCCall < Struct.new(:left, :right)
def to_s
"#{left}[#{right}]"
end
def inspect
to_s
end
def replace(name, replacement)
LCCall.new(left.replace(name, replacement), right.replace(name, replacement))
end
def callable?
false
end
def reducible?
left.reducible? || right.reducible? || left.callable?
end
def reduce
if left.reducible?
LCCall.new(left.reduce, right)
elsif right.reducible?
LCCall.new(left, right.reduce)
else
left.call(right)
end
end
end
one =
LCFunction.new(:p,
LCFunction.new(:x,
LCCall.new(LCVariable.new(:p), LCVariable.new(:x))
)
)
increment =
LCFunction.new(:n,
LCFunction.new(:p,
LCFunction.new(:x,
LCCall.new(
LCVariable.new(:p),
LCCall.new(
LCCall.new(LCVariable.new(:n), LCVariable.new(:p)),
LCVariable.new(:x)
)
)
)
)
)
add =
LCFunction.new(:m,
LCFunction.new(:n,
LCCall.new(LCCall.new(LCVariable.new(:n), increment), LCVariable.new(:m))
)
)
expression = LCCall.new(LCCall.new(add, one), one)
# while expression.reducible?
# puts expression
# expression = expression.reduce
# end; puts expression
inc, zero = LCVariable.new(:inc), LCVariable.new(:zero)
expression = LCCall.new(LCCall.new(expression, inc), zero)
# while expression.reducible?
# puts expression
# expression = expression.reduce
# end; puts expression
# parse_tree = LambdaCalculusParser.new.parse('-> x { x[x] } [-> y { y }]')<file_sep>ZERO = -> p { -> x { x } }
ONE = -> p { -> x { p[x] } }
TWO = -> p { -> x { p[p[x]] } }
THREE = -> p { -> x { p[p[p[x]]] } }
FIVE = -> p { -> x { p[p[p[p[p[x]]]]]}}
FIFTEEN = -> p { -> x { p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[x]]]]]]]]]]]]]]]}}
HUNDRED = -> p { -> x { p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[x]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]}}
def to_integer(proc)
proc[-> n { n + 1 }][0]
end
TRUE = -> x { -> y { x } }
FALSE = -> x { -> y { y } }
def to_boolean(proc)
IF[proc][true][false]
end
IF = -> b { b }
IS_ZERO = -> n { n[-> x { FALSE }][TRUE] }
PAIR = -> x { -> y { -> f { f[x][y] } } }
LEFT = -> p { p[-> x { -> y { x } } ] }
RIGHT = -> p { p[-> x { -> y { y } } ]}
INCREMENT = -> n { -> p { -> x { p[n[p][x]] } } }
SLIDE = -> p { PAIR[RIGHT[p]][INCREMENT[RIGHT[p]]] }
DECREMENT = -> n { LEFT[n[SLIDE][PAIR[ZERO][ZERO]]] }
ADD = -> m { -> n { n[INCREMENT][m] } }
SUBTRACT = -> m { -> n { n[DECREMENT][m] } }
MULTIPLY = -> m { -> n { n[ADD[m]][ZERO] } }
POWER = -> m { -> n { n[MULTIPLY[m]][ONE] } }
IS_LESS_OR_EQUAL = -> m { -> n { IS_ZERO[SUBTRACT[m][n]] } }
Z = -> f { -> x { f[-> y { x[x][y] }] }[-> x { f[->y { x[x][y] }] }] }
MOD =
Z[->f { -> m { -> n {
IF[IS_LESS_OR_EQUAL[n][m]][
-> x {
f[SUBTRACT[m][n]][n][x]
}
][
m
]
} } }]
EMPTY = PAIR[TRUE][TRUE]
UNSHIFT = -> l { -> x {
PAIR[FALSE][PAIR[x][l]]
} }
IS_EMPTY = LEFT
FIRST = -> l { LEFT[RIGHT[l]] }
REST = -> l { RIGHT[RIGHT[l]] }
RANGE =
Z[-> f {
-> m { ->n {
IF[IS_LESS_OR_EQUAL[m][n]][
-> x {
UNSHIFT[f[INCREMENT[m]][n]][m][x]
}
][
EMPTY
]
} }
}]
FOLD =
Z[-> f {
-> l { -> x { -> g {
IF[IS_EMPTY[l]][
x
][
-> y {
g[f[REST[l]][x][g]][FIRST[l]][y]
}
]
} } }
}]
MAP =
-> k { -> f {
FOLD[k][EMPTY][
-> l { -> x { UNSHIFT[l][f[x]] } }
]
} }
TEN = MULTIPLY[TWO][FIVE]
B = TEN
F = INCREMENT[B]
I = INCREMENT[F]
U = INCREMENT[I]
ZED = INCREMENT[U]
FIZZ = UNSHIFT[UNSHIFT[UNSHIFT[UNSHIFT[EMPTY][ZED]][ZED]][I]][F]
BUZZ = UNSHIFT[UNSHIFT[UNSHIFT[UNSHIFT[EMPTY][ZED]][ZED]][U]][B]
FIZZBUZZ = UNSHIFT[UNSHIFT[UNSHIFT[UNSHIFT[BUZZ][ZED]][ZED]][I]][F]
def to_char(c)
'0123456789BFiuz'.slice(to_integer(c))
end
def to_string(s)
to_array(s).map { |c| to_char(c) }.join
end
DIV =
Z[-> f { -> m { -> n {
IF[IS_LESS_OR_EQUAL[n][m]][
-> x {
INCREMENT[f[SUBTRACT[m][n]][n]][x]
}
][
ZERO
]
} } }]
PUSH =
-> l {
-> x {
FOLD[l][UNSHIFT[EMPTY][x]][UNSHIFT]
}
}
TO_DIGITS =
Z[-> f { -> n { PUSH[
IF[IS_LESS_OR_EQUAL[n][DECREMENT[TEN]]][
EMPTY
][
-> x {
f[DIV[n][TEN]][x]
}
]
][MOD[n][TEN]] } }]
ZEROS = Z[-> f { UNSHIFT[f][ZERO] }]
def to_array(l, count = nil)
array = []
until to_boolean(IS_EMPTY[l]) || count == 0
array.push(FIRST[l])
l = REST[l]
count = count - 1 unless count.nil?
end
array
end
TAPE = -> l { -> m { -> r { -> b { PAIR[PAIR[l][m]][PAIR[r][b]] } } } }
TAPE_LEFT = -> t { LEFT[LEFT[t]] }
TAPE_MIDDLE = -> t { RIGHT[LEFT[t]] }
TAPE_RIGHT = -> t { LEFT[RIGHT[t]] }
TAPE_BLANK = -> t { RIGHT[RIGHT[t]] }
TAPE_WRITE = -> t { -> c { TAPE[TAPE_LEFT[t]][c][TAPE_RIGHT[t]][TAPE_BLANK[t]] } }
TAPE_MOVE_HEAD_RIGHT =
-> t {
TAPE[
PUSH[TAPE_LEFT[t]][TAPE_MIDDLE[t]]
][
IF[IS_EMPTY[TAPE_RIGHT[t]]][
TAPE_BLANK[t]
][
FIRST[TAPE_RIGHT[t]]
]
][
IF[IS_EMPTY[TAPE_RIGHT[t]]][
EMPTY
][
REST[TAPE_RIGHT[t]]
]
][
TAPE_BLANK[t]
]
}
current_tape = TAPE[EMPTY][ZERO][EMPTY][ZERO]
current_tape = TAPE_WRITE[current_tape][ONE]
current_tape = TAPE_MOVE_HEAD_RIGHT[current_tape]
current_tape = TAPE_WRITE[current_tape][TWO]
current_tape = TAPE_MOVE_HEAD_RIGHT[current_tape]
current_tape = TAPE_WRITE[current_tape][THREE]
current_tape = TAPE_MOVE_HEAD_RIGHT[current_tape]
to_array(TAPE_LEFT[current_tape]).map { |p| to_integer(p) }
to_integer(TAPE_MIDDLE[current_tape])
to_array(TAPE_RIGHT[current_tape]).map { |p| to_integer(p) }<file_sep>class SKISymbol < Struct.new(:name)
def to_s
name.to_s
end
def inspect
to_s
end
def combinator
self
end
def arguments
[]
end
def callable?(*arguments)
false
end
def reducible?
false
end
def as_a_function_of(name)
if self.name == name
I
else
SKICall.new(K, self)
end
end
end
class SKICall < Struct.new(:left, :right)
def to_s
"#{left}[#{right}]"
end
def inspect
to_s
end
def combinator
left.combinator
end
def arguments
left.arguments + [right]
end
def reducible?
left.reducible? || right.reducible? || combinator.callable?(*arguments)
end
def reduce
if left.reducible?
SKICall.new(left.reduce, right)
elsif right.reducible?
SKICall.new(left, right.reduce)
else
combinator.call(*arguments)
end
end
def as_a_function_of(name)
left_function = left.as_a_function_of(name)
right_function = right.as_a_function_of(name)
SKICall.new(SKICall.new(S, left_function), right_function)
end
end
class SKICombinator < SKISymbol
def as_a_function_of(name)
SKICall.new(K, self)
end
end
S, K, I = [:S, :K, :I].map { |name| SKICombinator.new(name) }
# S[a][b][c]をa[c][b[c]]に簡約する
def S.call(a, b, c)
SKICall.new(SKICall.new(a, c), SKICall.new(b, c))
end
def S.callable?(*arguments)
arguments.length == 3
end
# K[a][b]をaに簡約する
def K.call(a, b)
a
end
def K.callable?(*arguments)
arguments.length == 2
end
# I[a]をaに簡約する
def I.call(a)
a
end
def I.callable?(*arguments)
arguments.length == 1
end
x = SKISymbol.new(:x)
y, z = SKISymbol.new(:y), SKISymbol.new(:z)
S.call(x, y, z)
expression = SKICall.new(SKICall.new(SKICall.new(S, x), y), z)
combinator = expression.left.left.left
first_argument = expression.left.left.right
second_argument = expression.left.right
third_argument = expression.right
combinator.call(first_argument, second_argument, third_argument)
expression
combinator = expression.combinator
arguments = expression.arguments
combinator.call(*arguments)
expression = SKICall.new(SKICall.new(x, y), z)
combinator = expression.combinator
arguments = expression.arguments
# combinator.call(*arguments)
expression = SKICall.new(SKICall.new(S, x), y)
combinator = expression.combinator
arguments = expression.arguments
# combinator.call(*arguments)
expression = SKICall.new(SKICall.new(x, y), z)
expression.combinator.callable?(*expression.arguments)
expression = SKICall.new(SKICall.new(S, x), y)
expression.combinator.callable?(*expression.arguments)
expression = SKICall.new(SKICall.new(SKICall.new(S, x), y), z)
expression.combinator.callable?(*expression.arguments)
# swap = SKICall.new(SKICall.new(S, SKICall.new(K, SKICall.new(S, I))), K)
# expression = SKICall.new(SKICall.new(swap, x), y)
# while expression.reducible?
# puts expression
# expression = expression.reduce
# end; puts expression
original = SKICall.new(SKICall.new(S, K), I)
function = original.as_a_function_of(:x)
expression = SKICall.new(function, y)
# while expression.reducible?
# puts expression
# expression = expression.reduce
# end; puts expression
original = SKICall.new(SKICall.new(S, x), I)
function = original.as_a_function_of(:x)
expression = SKICall.new(function, y)
# while expression.reducible?
# puts expression
# expression = expression.reduce
# end; puts expression
class LCVariable < Struct.new(:name)
def to_s
name.to_s
end
def inspect
to_s
end
def replace(name, replacement)
if self.name == name
replacement
else
self
end
end
def callable?
false
end
def reducible?
false
end
def to_ski
SKISymbol.new(name)
end
end
class LCFunction < Struct.new(:parameter, :body)
def to_s
"-> #{parameter} { #{body} }"
end
def inspect
to_s
end
def replace(name, replacement)
if parameter == name
self
else
LCFunction.new(parameter, body.replace(name, replacement))
end
end
def call(argument)
body.replace(parameter, argument)
end
def callable?
true
end
def reducible?
false
end
def to_ski
body.to_ski.as_a_function_of(parameter)
end
end
class LCCall < Struct.new(:left, :right)
def to_s
"#{left}[#{right}]"
end
def inspect
to_s
end
def replace(name, replacement)
LCCall.new(left.replace(name, replacement), right.replace(name, replacement))
end
def callable?
false
end
def reducible?
left.reducible? || right.reducible? || left.callable?
end
def reduce
if left.reducible?
LCCall.new(left.reduce, right)
elsif right.reducible?
LCCall.new(left, right.reduce)
else
left.call(right)
end
end
def to_ski
SKICall.new(left.to_ski, right.to_ski)
end
end
two =
LCFunction.new(:p,
LCFunction.new(:x,
LCCall.new(LCVariable.new(:p), LCCall.new(LCVariable.new(:p), LCVariable.new(:x)))
)
)
inc, zero = SKISymbol.new(:inc), SKISymbol.new(:zero)
expression = SKICall.new(SKICall.new(two.to_ski, inc), zero)
# while expression.reducible?
# puts expression
# expression = expression.reduce
# end; puts expression
identity = SKICall.new(SKICall.new(S, K), K)
expression = SKICall.new(identity, x)
# while expression.reducible?
# puts expression
# expression = expression.reduce
# end; puts expression <file_sep>def zero
0
end
def increment(n)
n + 1
end
def two
increment(increment(zero))
end
def three
increment(two)
end
def add_three(x)
increment(increment(increment(x)))
end
def recurse(f, g, *values)
*other_values, last_value = values
if last_value.zero?
send(f, *other_values)
else
easier_last_value = last_value - 1
easier_values = other_values + [easier_last_value]
easier_result = recurse(f, g, *easier_values)
send(g, *easier_values, easier_result)
end
end
def add_zero_to_x(x)
x
end
def increment_easier_result(x, easier_y, easier_result)
increment(easier_result)
end
def add(x, y)
recurse(:add_zero_to_x, :increment_easier_result, x, y)
end
def multiply_x_by_zero(x)
zero
end
def add_x_to_easier_result(x, easier_y, easier_result)
add(x, easier_result)
end
def multiply(x, y)
recurse(:multiply_x_by_zero, :add_x_to_easier_result, x, y)
end
def easier_x(easier_x, easier_result)
easier_x
end
def decrement(x)
recurse(:zero, :easier_x, x)
end
def subtract_zero_from_x(x)
x
end
def decrement_easier_result(x, easier_y, easier_result)
decrement(easier_result)
end
def subtract(x, y)
recurse(:subtract_zero_from_x, :decrement_easier_result, x, y)
end
def six
multiply(two, three)
end
def minimize
n = 0
n = n + 1 until yield(n).zero?
n
end
def divide(x, y)
minimize { |n| subtract(increment(x), multiply(y, increment(n))) }
end<file_sep>class TagRule < Struct.new(:first_character, :append_characters)
def applies_to?(string)
string.chars.first == first_character
end
def follow(string)
string + append_characters
end
end
class TagRulebook < Struct.new(:deletion_number, :rules)
def next_string(string)
rule_for(string).follow(string).slice(deletion_number..-1)
end
def rule_for(string)
rules.detect { |r| r.applies_to?(string) }
end
def applies_to?(string)
!rule_for(string).nil? && string.length >= deletion_number
end
end
class TagSystem < Struct.new(:current_string, :rulebook)
def step
self.current_string = rulebook.next_string(current_string)
end
def run
while rulebook.applies_to?(current_string)
puts current_string
step
end
puts current_string
end
end
# 数を倍にする
# rulebook = TagRulebook.new(2, [TagRule.new('a', 'cc'), TagRule.new('b', 'dddd')])
# system = TagSystem.new('aabbbbbb', rulebook)
# system.run
# 数を半分にする
# rulebook = TagRulebook.new(2, [TagRule.new('a', 'cc'), TagRule.new('b', 'd')])
# system = TagSystem.new('aabbbbbbbbbbbb', rulebook)
# system.run
# 数をインクリメントする
# rulebook = TagRulebook.new(2, [TagRule.new('a', 'ccdd'), TagRule.new('b', 'dd')])
# system = TagSystem.new('aabbbb', rulebook)
# system.run
# 数を倍にしてから、インクリメントする
# rulebook = TagRulebook.new(2, [
# TagRule.new('a', 'cc'), TagRule.new('b', 'dddd'), # 倍にする
# TagRule.new('c', 'eeff'), TagRule.new('d', 'ff') # インクリメントする
# ])
# system = TagSystem.new('aabbbb', rulebook)
# system.run
# 数が偶数か奇数かをテストする
# rulebook = TagRulebook.new(2, [
# TagRule.new('a', 'cc'), TagRule.new('b', 'd'),
# TagRule.new('c', 'eo'), TagRule.new('d', ''),
# TagRule.new('e', 'e')
# ])
# 入力した数が偶数の場合
# system = TagSystem.new('aabbbbbbbb', rulebook)
# system.run
# 入力した数が奇数の場合
# system = TagSystem.new('aabbbbbbbbbb', rulebook)
# system.run<file_sep>def euclid(x, y)
until x == y
if x > y
x = x - y
else
y = y - x
end
end
x
end<file_sep>data = %q{
program = "data = %q{#{data}}" + data
x = 1
y = 2
puts x + y
}
program = "data = %q{#{data}}" + data
x = 1
y = 2
puts x + y<file_sep>ZERO = -> p { -> x { x } }
ONE = -> p { -> x { p[x] } }
TWO = -> p { -> x { p[p[x]] } }
THREE = -> p { -> x { p[p[p[x]]] } }
FIVE = -> p { -> x { p[p[p[p[p[x]]]]]}}
FIFTEEN = -> p { -> x { p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[x]]]]]]]]]]]]]]]}}
HUNDRED = -> p { -> x { p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[x]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]}}
def to_integer(proc)
proc[-> n { n + 1 }][0]
end
TRUE = -> x { -> y { x } }
FALSE = -> x { -> y { y } }
def to_boolean(proc)
IF[proc][true][false]
end
IF = -> b { b }
IS_ZERO = -> n { n[-> x { FALSE }][TRUE] }
PAIR = -> x { -> y { -> f { f[x][y] } } }
LEFT = -> p { p[-> x { -> y { x } } ] }
RIGHT = -> p { p[-> x { -> y { y } } ]}
INCREMENT = -> n { -> p { -> x { p[n[p][x]] } } }
SLIDE = -> p { PAIR[RIGHT[p]][INCREMENT[RIGHT[p]]] }
DECREMENT = -> n { LEFT[n[SLIDE][PAIR[ZERO][ZERO]]] }
ADD = -> m { -> n { n[INCREMENT][m] } }
SUBTRACT = -> m { -> n { n[DECREMENT][m] } }
MULTIPLY = -> m { -> n { n[ADD[m]][ZERO] } }
POWER = -> m { -> n { n[MULTIPLY[m]][ONE] } }
IS_LESS_OR_EQUAL = -> m { -> n { IS_ZERO[SUBTRACT[m][n]] } }
Z = -> f { -> x { f[-> y { x[x][y] }] }[-> x { f[->y { x[x][y] }] }] }
MOD =
Z[->f { -> m { -> n {
IF[IS_LESS_OR_EQUAL[n][m]][
-> x {
f[SUBTRACT[m][n]][n][x]
}
][
m
]
} } }]
(ONE..HUNDRED).map do |n|
IF[IS_ZERO[MOD[n][FIFTEEN]]][
'FizzBuzz'
][IF[IS_ZERO[MOD[n][THREE]]][
'Fizz'
][IF[IS_ZERO[MOD[n][FIVE]]][
'Buzz'
][
n.to_s
]]]
end
<file_sep>data = %q{
program = "data = %q{#{data}}" + data
puts program
}
program = "data = %q{#{data}}" + data
puts program<file_sep>class LCVariable < Struct.new(:name)
def to_s
name.to_s
end
def inspect
to_s
end
def replace(name, replacement)
if self.name == name
replacement
else
self
end
end
end
class LCFunction < Struct.new(:parameter, :body)
def to_s
"-> #{parameter} { #{body} }"
end
def inspect
to_s
end
def replace(name, replacement)
if parameter == name
self
else
LCFunction.new(parameter, body.replace(name, replacement))
end
end
end
class LCCall < Struct.new(:left, :right)
def to_s
"#{left}[#{right}]"
end
def inspect
to_s
end
def replace(name, replacement)
LCCall.new(left.replace(name, replacement), right.replace(name, replacement))
end
end
expression = LCVariable.new(:x)
expression.replace(:x, LCFunction.new(:y, LCVariable.new(:y)))
expression.replace(:z, LCFunction.new(:y, LCVariable.new(:y)))
expression =
LCCall.new(
LCCall.new(
LCCall.new(
LCVariable.new(:a),
LCVariable.new(:b)
),
LCVariable.new(:c)
),
LCVariable.new(:b)
)
expression.replace(:a, LCVariable.new(:x))
expression.replace(:b, LCFunction.new(:x, LCVariable.new(:x)))<file_sep>require 'stringio'
def evaluate(program, input)
old_stdin, old_stdout = $stdin, $stdout
$stdin, $stdout = StringIO.new(input), (output = StringIO.new)
begin
eval program
rescue Exception => e
output.puts(e)
ensure
$stdin, $stdout = old_stdin, old_stdout
end
output.string
end
def evaluate_on_itself(program)
evaluate(program, program)
end<file_sep>ZERO = -> p { -> x { x } }
ONE = -> p { -> x { p[x] } }
TWO = -> p { -> x { p[p[x]] } }
THREE = -> p { -> x { p[p[p[x]]] } }
FIVE = -> p { -> x { p[p[p[p[p[x]]]]]}}
FIFTEEN = -> p { -> x { p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[x]]]]]]]]]]]]]]]}}
HUNDRED = -> p { -> x { p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[x]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]}}
def to_integer(proc)
proc[-> n { n + 1 }][0]
end
TRUE = -> x { -> y { x } }
FALSE = -> x { -> y { y } }
def to_boolean(proc)
IF[proc][true][false]
end
IF = -> b { b }
(ONE..HUNDRED).map do |n|
IF[(n % FIFTEEN).zero?][
'FizzBuzz'
][IF[(n % THREE).zero?][
'Fizz'
][IF[(n % FIVE).zero?][
'Buzz'
][
n.to_s
]]]
end
<file_sep>class Number < Struct.new(:value)
end
class Add < Struct.new(:left, :right)
end
class Multiply < Struct.new(:left, :right)
end<file_sep>class TagRule < Struct.new(:first_character, :append_characters)
def applies_to?(string)
string.chars.first == first_character
end
def follow(string)
string + append_characters
end
end
class CyclicTagRule < TagRule
FIRST_CHARACTER = '1'
def initialize(append_characters)
super(FIRST_CHARACTER, append_characters)
end
def inspect
"#<CyclicTagRule #{append_characters.inspect}>"
end
end
class TagRulebook < Struct.new(:deletion_number, :rules)
def next_string(string)
rule_for(string).follow(string).slice(deletion_number..-1)
end
def rule_for(string)
rules.detect { |r| r.applies_to?(string) }
end
def applies_to?(string)
!rule_for(string).nil? && string.length >= deletion_number
end
end
class CyclicTagRulebook < Struct.new(:rules)
DELETION_NUMBER = 1
def initialize(rules)
super(rules.cycle)
end
def applies_to?(string)
string.length >= DELETION_NUMBER
end
def next_string(string)
follow_next_rule(string).slice(DELETION_NUMBER..-1)
end
def follow_next_rule(string)
rule = rules.next
if rule.applies_to?(string)
rule.follow(string)
else
string
end
end
end
class TagSystem < Struct.new(:current_string, :rulebook)
def step
self.current_string = rulebook.next_string(current_string)
end
def run
while rulebook.applies_to?(current_string)
puts current_string
step
end
puts current_string
end
end
rulebook = CyclicTagRulebook.new([
CyclicTagRule.new('1'), CyclicTagRule.new('0010'), CyclicTagRule.new('10')
])
system = TagSystem.new('11', rulebook)
# 16.times do
# puts system.current_string
# system.step
# end; puts system.current_string
# 20.times do
# puts system.current_string
# system.step
# end; puts system.current_string<file_sep>class LCVariable < Struct.new(:name)
def to_s
name.to_s
end
def inspect
to_s
end
def replace(name, replacement)
if self.name == name
replacement
else
self
end
end
end
class LCFunction < Struct.new(:parameter, :body)
def to_s
"-> #{parameter} { #{body} }"
end
def inspect
to_s
end
def replace(name, replacement)
if parameter == name
self
else
LCFunction.new(parameter, body.replace(name, replacement))
end
end
def call(argument)
body.replace(parameter, argument)
end
end
class LCCall < Struct.new(:left, :right)
def to_s
"#{left}[#{right}]"
end
def inspect
to_s
end
def replace(name, replacement)
LCCall.new(left.replace(name, replacement), right.replace(name, replacement))
end
end
function =
LCFunction.new(:x,
LCFunction.new(:y,
LCCall.new(LCVariable.new(:x), LCVariable.new(:y))
)
)
argument = LCFunction.new(:z, LCVariable.new(:z))
function.call(argument)<file_sep>class TagRule < Struct.new(:first_character, :append_characters)
def applies_to?(string)
string.chars.first == first_character
end
def follow(string)
string + append_characters
end
end
class TagRulebook < Struct.new(:deletion_number, :rules)
def next_string(string)
rule_for(string).follow(string).slice(deletion_number..-1)
end
def rule_for(string)
rules.detect { |r| r.applies_to?(string) }
end
end
class TagSystem < Struct.new(:current_string, :rulebook)
def step
self.current_string = rulebook.next_string(current_string)
end
end
# rulebook = TagRulebook.new(2, [TagRule.new('a', 'aa'), TagRule.new('b', 'bbbb')])
# system = TagSystem.new('aabbbbbb', rulebook)
# 4.times do
# puts system.current_string
# system.step
# end; puts system.current_string<file_sep>def multiples_of(n)
Enumerator.new do |yielder|
value = n
loop do
yielder.yield(value)
value = value + n
end
end
end<file_sep>class Number < Struct.new(:value)
def to_s
value.to_s
end
def inspect
"<<#{self}>>"
end
def evaluate(environment)
self
end
end
class Boolean < Struct.new(:value)
def to_s
value.to_s
end
def inspect
"<<#{self}>>"
end
def evaluate(environment)
self
end
end
class Variable < Struct.new(:name)
def to_s
name.to_s
end
def inspect
"<<#{self}>>"
end
def evaluate(environment)
environment[name]
end
end
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
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 DoNothing
def to_s
'do-nothing'
end
def inspect
"<<#{self}>>"
end
def ==(other_statement)
other_statement.instance_of?(DoNothing)
end
def evaluate(environment)
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<file_sep>class Number < Struct.new(:value)
def to_s
value.to_s
end
def inspect
"<<#{self}>>"
end
def evaluate(environment)
self
end
def type(context)
Type::NUMBER
end
end
class Boolean < Struct.new(:value)
def to_s
value.to_s
end
def inspect
"<<#{self}>>"
end
def evaluate(environment)
self
end
def type(context)
Type::BOOLEAN
end
end
class Variable < Struct.new(:name)
def to_s
name.to_s
end
def inspect
"<<#{self}>>"
end
def evaluate(environment)
environment[name]
end
def type(context)
context[name]
end
end
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
def type(context)
if left.type(context) == Type::NUMBER && right.type(context) == Type::NUMBER
Type::NUMBER
end
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
def type(context)
if left.type(context) == Type::NUMBER && right.type(context) == Type::NUMBER
Type::NUMBER
end
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
def type(context)
if left.type(context) == Type::NUMBER && right.type(context) == Type::NUMBER
Type::BOOLEAN
end
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
def type(context)
if context[name] == expression.type(context)
Type::VOID
end
end
end
class DoNothing
def to_s
'do-nothing'
end
def inspect
"<<#{self}>>"
end
def ==(other_statement)
other_statement.instance_of?(DoNothing)
end
def evaluate(environment)
environment
end
def type(context)
Type::VOID
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
def type(context)
if condition.type(context) == Type::BOOLEAN &&
consequence.type(context) == Type::VOID &&
alternative.type(context) == Type::VOID
Type::VOID
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
def type(context)
if first.type(context) == Type::VOID && second.type(context) == Type::VOID
Type::VOID
end
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
def type(context)
if condition.type(context) == Type::BOOLEAN && body.type(context) == Type::VOID
Type::VOID
end
end
end
class Type < Struct.new(:name)
NUMBER, BOOLEAN = [:number, :boolean].map { |name| new(name) }
VOID = new(:void)
def inspect
"#<Type #{name}>"
end
end
# Add.new(Number.new(1), Number.new(2)).evaluate({})
# Add.new(Number.new(1), Boolean.new(true)).evaluate({})
# Add.new(Number.new(1), Number.new(2)).type
# Add.new(Number.new(1), Boolean.new(true)).type
# LessThan.new(Number.new(1), Number.new(2)).type
# LessThan.new(Number.new(1), Boolean.new(true)).type
expression = Add.new(Variable.new(:x), Variable.new(:y))
expression.type({})
expression.type({ x: Type::NUMBER, y: Type::NUMBER })
expression.type({ x: Type::NUMBER, y: Type::BOOLEAN })
If.new(
LessThan.new(Number.new(1), Number.new(2)), DoNothing.new, DoNothing.new
).type({})
If.new(
Add.new(Number.new(1), Number.new(2)), DoNothing.new, DoNothing.new
).type({})
While.new(Variable.new(:x), DoNothing.new).type({ x: Type::BOOLEAN })
While.new(Variable.new(:x), DoNothing.new).type({ x: Type::NUMBER })
statement =
While.new(
LessThan.new(Variable.new(:x), Number.new(5)),
Assign.new(:x, Add.new(Variable.new(:x), Number.new(3)))
)
statement.type({})
statement.type({ x: Type::NUMBER })
statement.type({ x: Type::BOOLEAN })
statement =
Sequence.new(
Assign.new(:x, Number.new(0)),
While.new(
Boolean.new(true),
Assign.new(:x, Add.new(Variable.new(:x), Number.new(1)))
)
)
statement.type({ x: Type::NUMBER })
# statement.evaluate({})
statement = Sequence.new(statement, Assign.new(:x, Boolean.new(true)))
statement.type({ x: Type::NUMBER })
statement =
Sequence.new(
If.new(
Variable.new(:b),
Assign.new(:x, Number.new(6)),
Assign.new(:x, Boolean.new(true))
),
Sequence.new(
If.new(
Variable.new(:b),
Assign.new(:y, Variable.new(:x)),
Assign.new(:y, Number.new(1))
),
Assign.new(:z, Add.new(Variable.new(:y), Number.new(1)))
)
)
statement.evaluate({ b: Boolean.new(true) })
statement.evaluate({ b: Boolean.new(false) })
statement.type({})
context = { b: Type::BOOLEAN, y: Type::NUMBER, z: Type::NUMBER }
statement.type(context)
statement.type(context.merge({ x: Type::NUMBER }))
statement.type(context.merge({ x: Type::BOOLEAN }))
# statement = Assign.new(:x, Add.new(Variable.new(:x), Number.new(1)))
# statement.type({ x: Type::NUMBER })
# statement.evaluate({})<file_sep>ZERO = -> p { -> x { x } }
ONE = -> p { -> x { p[x] } }
TWO = -> p { -> x { p[p[x]] } }
THREE = -> p { -> x { p[p[p[x]]] } }
FIVE = -> p { -> x { p[p[p[p[p[x]]]]]}}
FIFTEEN = -> p { -> x { p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[x]]]]]]]]]]]]]]]}}
HUNDRED = -> p { -> x { p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[p[x]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]}}
def to_integer(proc)
proc[-> n { n + 1 }][0]
end
(ONE..HUNDRED).map do |n|
if (n % FIFTEEN).zero?
'FizzBuzz'
elsif (n % THREE).zero?
'Fizz'
elsif (n % FIVE).zero?
'Buzz'
else
n.to_s
end
end | 1050ffa0c6875966de66647b86a211dbbff183e3 | [
"Ruby"
]
| 26 | Ruby | tk0358/understanding_computation | f28e067e4e02422142707b8b37878a2ba279f34d | 5cd0f60d47a2552704a365ba0a6989d5c090642d |
refs/heads/master | <repo_name>barisylmz53/NDP_Project<file_sep>/Greyfurt.cs
/****************************************************************************
** SAKARYA ÜNİVERSİTESİ
** BİLGİSAYAR VE BİLİŞİM BİLİMLERİ FAKÜLTESİ
** BİLGİSAYAR MÜHENDİSLİĞİ BÖLÜMÜ
** NESNEYE DAYALI PROGRAMLAMA DERSİ
** 2020-2021 BAH<NAME>İ
**
** ÖDEV NUMARASI..........: 1. PROJE
** ÖĞRENCİ ADI............: <NAME>
** ÖĞRENCİ NUMARASI.......: G201210057
** DERSİN ALINDIĞI GRUP...: 2. ÖĞRETİM C GRUBU / CAN YÜZKOLLAR
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace G201210057_MUHAMMET_BARIŞ_YILMAZ
{
class Greyfurt : Olustur, IMeyveSik
{
private double _id;
private double _agirlik;
private double _verim;
public override void AgirlikOlustur()
{
Random rand = new Random();
_agirlik = rand.Next(70, 120);
}
public override void VerimOlustur()
{
Random rand = new Random();
_verim = rand.Next(30, 70);
}
public double SiviPureUret(double agirlik, double verim)
{
return (agirlik * verim) / 100;
}
public double[] MeyveUret()
{
double[] veri = new double[6];
_id = 6;
AgirlikOlustur(); veri[0] = _agirlik;
VerimOlustur(); veri[1] = _verim;
veri[2] = SiviPureUret(_agirlik, _verim);
veri[3] = VitaminHesaplaA(veri[2], _id);
veri[4] = VitaminHesaplaC(veri[2], _id);
veri[5] = _id;
return veri;
}
}
}
<file_sep>/Olustur.cs
/****************************************************************************
** SAKARYA ÜNİVERSİTESİ
** BİLGİSAYAR VE BİLİŞİM BİLİMLERİ FAKÜLTESİ
** BİLGİSAYAR MÜHENDİSLİĞİ BÖLÜMÜ
** NESNEYE DAYALI PROGRAMLAMA DERSİ
** 2020-2021 <NAME>İ
**
** ÖDEV NUMARASI..........: 1. PROJE
** ÖĞRENCİ ADI............: <NAME>
** ÖĞRENCİ NUMARASI.......: G201210057
** DERSİN ALINDIĞI GRUP...: 2. ÖĞRETİM C GRUBU / CAN YÜZKOLLAR
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace G201210057_MUHAMMET_BARIŞ_YILMAZ
{
abstract class Olustur : IVitamin
{
public abstract void AgirlikOlustur();
public abstract void VerimOlustur();
public double VitaminHesaplaA(double miktarPure,double id)
{
if(id==1)
{
return (miktarPure * 54) / 100;
}
else if(id==2)
{
return (miktarPure * 25) / 100;
}
else if(id==3)
{
return (miktarPure * 12) / 100;
}
else if(id==4)
{
return (miktarPure * 225) / 100;
}
else if(id==5)
{
return (miktarPure * 681) / 100;
}
else
{
return (miktarPure * 3) / 100;
}
}
public double VitaminHesaplaC(double miktarPure,double id)
{
if (id == 1)
{
return (miktarPure * 5) / 100;
}
else if (id == 2)
{
return (miktarPure * 5) / 100;
}
else if (id == 3)
{
return (miktarPure * 60) / 100;
}
else if (id == 4)
{
return (miktarPure * 45) / 100;
}
else if (id == 5)
{
return (miktarPure * 26) / 100;
}
else
{
return (miktarPure * 44) / 100;
}
}
}
}
<file_sep>/IVitamin.cs
/****************************************************************************
** SAKARYA ÜNİVERSİTESİ
** BİLGİSAYAR VE BİLİŞİM BİLİMLERİ FAKÜLTESİ
** BİLGİSAYAR MÜHENDİSLİĞİ BÖLÜMÜ
** NESNEYE DAYALI PROGRAMLAMA DERSİ
** 2020-2021 <NAME>
**
** ÖDEV NUMARASI..........: 1. PROJE
** ÖĞRENCİ ADI............: <NAME>
** ÖĞRENCİ NUMARASI.......: G201210057
** DERSİN ALINDIĞI GRUP...: 2. ÖĞRETİM C GRUBU / CAN YÜZKOLLAR
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace G201210057_MUHAMMET_BARIŞ_YILMAZ
{
interface IVitamin
{
double VitaminHesaplaA(double miktarPure, double id);
double VitaminHesaplaC(double miktarPure, double id);
}
}
<file_sep>/Form1.cs
/****************************************************************************
** SAKARYA ÜNİVERSİTESİ
** BİLGİSAYAR VE BİLİŞİM BİLİMLERİ FAKÜLTESİ
** BİLGİSAYAR MÜHENDİSLİĞİ BÖLÜMÜ
** NESNEYE DAYALI PROGRAMLAMA DERSİ
** 2020-2021 <NAME>
**
** ÖDEV NUMARASI..........: 1. PROJE
** ÖĞRENCİ ADI............: <NAME>
** ÖĞRENCİ NUMARASI.......: G201210057
** DERSİN ALINDIĞI GRUP...: 2. ÖĞRETİM C GRUBU / CAN YÜZKOLLAR
****************************************************************************/
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 G201210057_MUHAMMET_BARIŞ_YILMAZ
{
public partial class Form1 : Form
{
public double[] SiraKontrol(int sira)
{
double[] degerler = new double[6];
if(sira==0)
{
Armut meyve = new Armut();
degerler = meyve.MeyveUret();
}
else if(sira==1)
{
Cilek meyve = new Cilek();
degerler = meyve.MeyveUret();
}
else if(sira==2)
{
Elma meyve = new Elma();
degerler = meyve.MeyveUret();
}
else if(sira==3)
{
Greyfurt meyve = new Greyfurt();
degerler = meyve.MeyveUret();
}
else if(sira==4)
{
Mandalina meyve = new Mandalina();
degerler = meyve.MeyveUret();
}
else
{
Portakal meyve = new Portakal();
degerler = meyve.MeyveUret();
}
return degerler;
}
Random rand = new Random();
public Form1()
{
InitializeComponent();
}
int meyveSira,zaman_kontrol=0;
double geciciA, geciciC, geciciSiviPure;
private void BASLA_button1_Click(object sender, EventArgs e)
{
if (sayac_label3.Text=="0")
{
a_textBox1.Text = "0";
c_textBox2.Text = "0";
pure_textBox4.Text = "0";
sivi_textBox3.Text = "0";
meyveSira = rand.Next(0, 6);
pictureBox1.Image = ımageList1.Images[meyveSira];
double[] degerler = SiraKontrol(meyveSira);
if (degerler[5] == 1)
{
BILGILER_label1.Text = "Elma\n";
}
else if (degerler[5] == 2)
{
BILGILER_label1.Text = "Armut\n";
}
else if (degerler[5] == 3)
{
BILGILER_label1.Text = "Çilek\n";
}
else if (degerler[5] == 4)
{
BILGILER_label1.Text = "Portakal\n";
}
else if (degerler[5] == 5)
{
BILGILER_label1.Text = "Mandalina\n";
}
else if (degerler[5] == 6)
{
BILGILER_label1.Text = "Greyfurt\n";
}
BILGILER_label1.Text = BILGILER_label1.Text + "Ağirlik = " + degerler[0] + "\nVerim = " + degerler[1]+ "\nVitamin A = " + degerler[3] + "\nVitamin C = " + degerler[4] + "\nSivi/Püre ağirlik = " + degerler[2];
geciciSiviPure = degerler[2];
geciciA = degerler[3];
geciciC = degerler[4];
sayac_label3.Text = "60";
timer1.Enabled = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
zaman_kontrol = 1;
sayac_label3.Text = Convert.ToString(Convert.ToInt32(sayac_label3.Text) + (Convert.ToInt32(sayac_label3.Text)-Convert.ToInt32(sayac_label3.Text) - 1));
if(sayac_label3.Text == "0")
{
zaman_kontrol = 0;
timer1.Stop();
}
}
private void kati_button1_Click(object sender, EventArgs e)
{
if (zaman_kontrol == 1&&meyveSira<3)
{
a_textBox1.Text = Convert.ToString(Convert.ToDouble(a_textBox1.Text) + geciciA);
c_textBox2.Text = Convert.ToString(Convert.ToDouble(c_textBox2.Text) + geciciC);
pure_textBox4.Text = Convert.ToString(Convert.ToDouble(pure_textBox4.Text) + geciciSiviPure);
meyveSira = rand.Next(0, 6);
pictureBox1.Image = ımageList1.Images[meyveSira];
double[] degerler = SiraKontrol(meyveSira);
if (degerler[5] == 1)
{
BILGILER_label1.Text = "Elma\n";
}
else if (degerler[5] == 2)
{
BILGILER_label1.Text = "Armut\n";
}
else if (degerler[5] == 3)
{
BILGILER_label1.Text = "Çilek\n";
}
else if (degerler[5] == 4)
{
BILGILER_label1.Text = "Portakal\n";
}
else if (degerler[5] == 5)
{
BILGILER_label1.Text = "Mandalina\n";
}
else if (degerler[5] == 6)
{
BILGILER_label1.Text = "Greyfurt\n";
}
BILGILER_label1.Text = BILGILER_label1.Text + "Ağirlik = " + degerler[0] + "\nVerim = " + degerler[1] + "\nVitamin A = " + degerler[3] + "\nVitamin C = " + degerler[4] + "\nSivi/Püre ağirlik = " + degerler[2];
geciciSiviPure = degerler[2];
geciciA = degerler[3];
geciciC = degerler[4];
}
}
private void sivi_button2_Click(object sender, EventArgs e)
{
if(zaman_kontrol==1&&meyveSira>=3)
{
a_textBox1.Text = Convert.ToString(Convert.ToDouble(a_textBox1.Text) + geciciA);
c_textBox2.Text = Convert.ToString(Convert.ToDouble(c_textBox2.Text) + geciciC);
sivi_textBox3.Text = Convert.ToString(Convert.ToDouble(sivi_textBox3.Text) + geciciSiviPure);
meyveSira = rand.Next(0, 6);
pictureBox1.Image = ımageList1.Images[meyveSira];
double[] degerler = SiraKontrol(meyveSira);
if (degerler[5] == 1)
{
BILGILER_label1.Text = "Elma\n";
}
else if (degerler[5] == 2)
{
BILGILER_label1.Text = "Armut\n";
}
else if (degerler[5] == 3)
{
BILGILER_label1.Text = "Çilek\n";
}
else if (degerler[5] == 4)
{
BILGILER_label1.Text = "Portakal\n";
}
else if (degerler[5] == 5)
{
BILGILER_label1.Text = "Mandalina\n";
}
else if (degerler[5] == 6)
{
BILGILER_label1.Text = "Greyfurt\n";
}
BILGILER_label1.Text = BILGILER_label1.Text + "Ağirlik = " + degerler[0] + "\nVerim = " + degerler[1] + "\nVitamin A = " + degerler[3] + "\nVitamin C = " + degerler[4] + "\nSivi/Püre ağirlik = " + degerler[2];
geciciSiviPure = degerler[2];
geciciA = degerler[3];
geciciC = degerler[4];
}
}
}
}<file_sep>/Program.cs
/****************************************************************************
** SAKARYA ÜNİVERSİTESİ
** BİLGİSAYAR VE BİLİŞİM BİLİMLERİ FAKÜLTESİ
** BİLGİSAYAR MÜHENDİSLİĞİ BÖLÜMÜ
** NESNEYE DAYALI PROGRAMLAMA DERSİ
** 2020-2021 <NAME>
**
** ÖDEV NUMARASI..........: 1. PROJE
** ÖĞRENCİ ADI............: <NAME>
** ÖĞRENCİ NUMARASI.......: G201210057
** DERSİN ALINDIĞI GRUP...: 2. ÖĞRETİM C GRUBU / CAN YÜZKOLLAR
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace G201210057_MUHAMMET_BARIŞ_YILMAZ
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 161d5d3918294d1d35e6c169c6a958194de73517 | [
"C#"
]
| 5 | C# | barisylmz53/NDP_Project | 08f3d01f8e1c30e383e8b8d40d4e791582493226 | 13e5e6cdfb81144bab9886b2848d50dae1e52491 |
refs/heads/master | <repo_name>mikeghen/dss-615-spring-2018<file_sep>/module2/main.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Lab 1: Reading data from a file
csv_file = open('/Users/mikeghen/Desktop/dss615-spring-2018/module2/data/ripple_price.csv','r')
for line in csv_file:
print(line)
csv_file.close()
# Lab 2: Reading data from a CSV file
## Method 1: Treat the file like a file
with open('./data/ripple_price.csv') as csv_file:
for line in csv_file:
print(line)
print("outside the with", csv_file)
## Method 2: Use csv module from the Standard Library
import csv
csv_file = open('./data/ripple_price.csv')
csv_reader = csv.reader(csv_file)
for row in csv_reader:
print(row)
csv_file.close()
#
# # With with...
# with open('./data/ripple_price.csv') as csv_file:
# csv_reader = csv.reader(csv_file)
# for row in csv_reader:
# print(row)
# Lab 3: Writing to files
import csv
input_file = open('./data/ripple_price.csv','r')
output_file = open('./data/ripple_price.tsv','w')
csv_reader = csv.reader(input_file)
for row in csv_reader:
tsv_row = '\t'.join(row) + '\n'
output_file.write(tsv_row)
input_file.close()
output_file.flush()
output_file.close()
# # Lab 4: Reading tab seperated value (TSV) files
import csv
with open('./data/ripple_price.tsv') as tsv_file:
tsv_reader = csv.reader(tsv_file)
for row in tsv_reader:
print(row)
# Lab 4: Parsing data to keep what we want
import csv
input_file = open('./data/LoanStats_2017Q3.csv', 'r')
interesting_columns = ["loan_amnt","funded_amnt","funded_amnt_inv","term","int_rate","installment","grade"]
with open('./data/cleaned_LoanStats_2017Q3.csv', 'w') as output_file:
csv_reader = csv.reader(input_file)
# Pop off the first two rows from the CSV file
credits = csv_reader.next()
header = csv_reader.next()
for row in csv_reader:
row_count = len(row)
# NOTE: We only want to keep: "loan_amnt","funded_amnt","funded_amnt_inv",
# "term","int_rate","installment","grade"
print(row)
output_row = [ row[2],row[3],row[4],row[5],row[6],row[7],row[8] ]
output_line = ','.join(output_row) + '\n'
output_file.write(output_line)
input_file.close()
# Lab 5: Parsing data to and casting types
import csv
with open('./data/cleaned_LoanStats_2017Q3.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
row = csv_reader.next()
loan_amnt = int(row[0])
funded_amnt = int(row[1])
funded_amnt_inv = int(row[2])
term = int(row[3].strip().split(' ')[0]) # ['36','months']
int_rate = float(row[4].replace('%',''))/100
installment = float(row[5])
grade = row[6]
print("loan_amnt: ", type(loan_amnt), loan_amnt)
print("funded_amnt: ", type(funded_amnt), funded_amnt)
print("funded_amnt_inv: ", type(funded_amnt_inv), funded_amnt_inv)
print("term: ", type(term), term)
print("int_rate: ", type(int_rate), int_rate)
print("installment: ", type(installment), installment)
print("grade: ", type(grade), grade)
# End
<file_sep>/module4/etl.py
from pprint import pprint
SMA_WINDOW_SIZE = 5
def main():
extracted_data = extract('data/OPEC_ORB_TEST.csv')
transformed_data = transform(extracted_data)
def extract(filename):
"""
Extracts data from a CSV file and returns it as a list.
"""
extracted_data = []
with open(filename, 'r') as data_file:
for datum in data_file:
extracted_data.append(tuple(datum.strip().split('\t')))
return extracted_data[1:]
def transform(data):
"""
Transforms a list of x,y values to compute an SMA for y values.
Returns a list of tuples (x,y') where y' is the SMA value computed
"""
transformed_data = [] # The SMA data
for index, datum in enumerate(data):
if index < SMA_WINDOW_SIZE:
transformed_data.append((datum[0],0))
else:
sma = 0
for i in range(SMA_WINDOW_SIZE):
sma += float(data[index - i][1])
sma = sma/SMA_WINDOW_SIZE
transformed_data.append((datum[0],sma))
return transformed_data
main()
<file_sep>/module1/main.py
# Lab 1: Body Mass Index
height_meters = 2.1
weight_kilograms = 89.5
body_mass_index = weight_kilograms / (height_meters * height_meters)
print(body_mass_index)
# Lab 2: Slope of a line
m = 0.5
b = 3
x = 2
y = m * x + b
print(y)
m = 1//2
b = 3
x = 2
y = m * x + b
print(y)
# Lab 3: Word Math
hello = "Hello"
world = "World"
phrase = hello + " # " + world + "!"
print(phrase)
print(phrase.upper())
print(phrase.split('#'))
# Lab 4: List Math
students = ["Reinaldo", "Kelly", "Thomas", "Kin"]
num_students = len(students)
print(num_students)
first_student = students[0]
print(first_student)
last_student = students[-1]
print(last_student)
first_three_students = students[0:]
print(first_three_students)
last_three_students = students[-3:]
print(last_three_students)
first_student_initial = students[0][0]
print(first_student_initial)
# Lab 5: Structures
coordinates = [ [1,0], [2,0.5], [3,1], [4,1.5] ]
first_point = coordinates[0]
first_point_x = coordinates[0][0]
first_point_y = coordinates[0][1]
print(first_point)
slope = (coordinates[3][1] - coordinates[0][1]) / (coordinates[3][0] - coordinates[0][0])
print(slope)
# Lab 6: Decisions
costs = 150000
revenues = 145000
net_profit = revenues - costs
if costs > revenues:
print("Give up, you lost ${0:,.2f}.".format(net_profit))
elif costs < revenues:
print("Keep at it, you earned ${0:,.2f}.".format(net_profit))
else:
print("No taxable income!")
x = 6
if x == 5:
print(x)
# Lab 7: Iteration
principal = 1000
annual_interest = 0.035
account_balance = principal
for year in range(2015, 2020):
account_balance += (account_balance * annual_interest)
print("{0}: End of Year Balance = ${1:,.2f}".format(year, account_balance))
# Lab 8: List Loops
students = ["Reinaldo", "Kelly", "Thomas", "Kin"]
for student in students:
print(student)
<file_sep>/README.md
# Welcome to DSS 615: Python Programming
Python programming has become very popular due to its flexibility and availability as an open source tool. As with any type of programming, this course will rely upon students learning and retaining material from the very start of the course. By the completion of the course, students will be able to develop basic-to-intermediate applications in Python. Your hard work will definitely pay off.
## Outline
* **Module 1:** Introduction
* **Module 2:** Core Objects, Variables, Input and Output
* **Module 3:** Structures that Control Flow
* **Module 4:** Functions
* **Module 5:** Object Oriented Programming
* **Module 6:** Working with Data
* **Module 7:** Python in Practice
<file_sep>/module3/simple_moving_average.py
data = [
(9/18/17, 53.78)
(9/15/17, 53.64)
(9/14/17, 53.63)
(9/13/17, 52.92)
(9/12/17, 52.08)
(9/11/17, 51.82)
(9/8/17, 52.53)
(9/7/17, 52.48)
(9/6/17, 52.04)
]
transformed_data = [] # The SMA data
for index, datum in enumerate(data):
if index < SMA_WINDOW_SIZE:
transformed_data.append((datum[0],0))
else:
sma = 0
for i in range(SMA_WINDOW_SIZE):
sma += float(data[index - i][1])
sma = sma/SMA_WINDOW_SIZE
transformed_data.append((datum[0],sma))
<file_sep>/module2/make_csv.py
# Make CSV file
#
# This script creates a CSV file that contains a simple "stray whitespace" error.
#
# The code below makes the file using Faker and injects the whitespace error.
#
# We create a CSV file that looks like data from a hospital about individuals
# that have digestive illnesses.
#
from faker import Faker
from random import randint, normalvariate
fake = Faker()
with open('digestive_illnesses.csv','w') as illnesses_file:
# Write the illnesses_file header
header = 'Case ID, SSN, Birth Date, First Name, Last Name, Address, City, ICD9'
illnesses_file.write(header+'\n')
# Write rows of data to the illnesses_file, add the error
row = []
for i in range(1000):
first_name = fake.first_name().ljust(50)
last_name = fake.first_name().ljust(50)
street_address = fake.street_address().ljust(50)
city = fake.city().ljust(25)
birth_date = fake.date().replace('-','')
ssn = fake.ssn().replace('-','')
icd9 = "%03d"%normalvariate(550, 10)
identifier = "%09d"%randint(1, 999999999)
stray_white_space = '\n'
row = [ identifier,
ssn,
birth_date,
first_name,
last_name + stray_white_space, # Here's your issue
street_address,
city,
icd9]
row = ','.join(row)
illnesses_file.write(row+'\n')
<file_sep>/module2/README.md
# Module 2: Core Objects
The goal of Module 2 of this course is to reinforce the core programming concepts introduced in Module 1 and apply them to solve to problems you might encounter.
In addition to these existing concepts:
* Numbers (int, bool, float)
* Sequences (string, list)
* Relation and Logic Operators
* Conditionals
* For Loops
We will introduce the concept of **reading and writing files** with Python. We will use numbers, sequences, operators, conditionals, and for loops to work with data from files in the assignments. You will also complete a series of Projects from the text chosen to reinforce the concepts from Module 1.
## Reading Assignment:
* Python Documentation
* [The Python Tutorial](https://docs.python.org/3/tutorial/index.html)
* [An Informal Introduction to Python](https://docs.python.org/3/tutorial/introduction.html)
* More Control Flow Tools
* [if Statements](https://docs.python.org/3/tutorial/controlflow.html#if-statements)
* [for Statements](https://docs.python.org/3/tutorial/controlflow.html#for-statements)
* Input and Output
* The Python Standard Library
* [csv -- CSV File Reading and Writing](https://docs.python.org/3/library/csv.html?highlight=csv#module-csv)
* Textbook
* Chapter 5 sections 1, 2
* Reread Chapter 2 and 3 as needed to complete the Projects
## Programming Exercises:
* Text Book Projects (Choose 3)
* Chapter 2
* Project 1 (p. 74)
* Project 3 (p. 75)
* Project 4 (p. 75)
* Chapter 3
* Project 2 (p. 140)
* Project 3 (p. 140)
* Project 8 (p. 142)
* Instructor Exercises (See next pages for details)
* Fix a busted CSV file
* Build a better data set
## References
* [Health Codes from Synthea](https://github.com/synthetichealth/synthea/)
* [Lending Club Lending Data](https://www.lendingclub.com/info/download-data.action)
* [Kaggle, sudalairajkumar](https://kaggle.com/sudalairajkumar/cryptocurrencypricehistory/data)
<file_sep>/module3/README.md
# Module 3: Control Flow
The goal of Module 3 of this course is to **learn to control the flow of programs**. We will move beyond _simple scripts_ and start building what would be considered _applications_.
As we start to think about control flow, we will being to explore the concept of functions. As we move into the second half of this course where we focus on object oriented programing, functions become an important topic. We will start discussing it this week and continue more in subsequent weeks.
## Reading Assignment:
* Python Documentation
* The Python Tutorial
* [More Control Flow Tools](https://docs.python.org/3/tutorial/controlflow.html)
* [Defining Functions](https://docs.python.org/3/tutorial/controlflow.html#defining-functions)
* Textbook
* Chapter 4
* Chapter 5
**At the end of this module, you should have read chapters 1 through 5 in the textbook.**
## Programming Exercises:
* Text Book
* Section 2.1 exercises 62 - 78 even
* Section 2.2 exercises 80 - 92 even 100, 102, 110
* Section 2.3 exercises 53 - 58 even
* Section 2.4 exercises 60 - 104 even
* Section 3.1 exercises 46 - 85 even
* Section 3.2 exercises 34 - 42 even
* Section 3.3 exercises 20 - 30 even
* Section 3.4 exercises 52 - 63 even
* Instructor Exercises (Choose 1)
* Bank Account Application
* Measuring the impact of research institutions
## References
* [Health Codes from Synthea](https://github.com/synthetichealth/synthea/)
* [Lending Club Lending Data](https://www.lendingclub.com/info/download-data.action)
* [Kaggle, sudalairajkumar](https://kaggle.com/sudalairajkumar/cryptocurrencypricehistory/data)
<file_sep>/module5/main.py
# ## Lab 1: Reading a CSV file
# filename = './data/inpatient_payments_data.csv'
# is_header = True
#
# with open(filename, 'r') as inpatient_payments_data:
# for datum in inpatient_payments_data:
# values = datum.split(',')
#
# if is_header:
# header = [values[2], values[-4], values[-3], values[-2], values[-1]]
# is_header = False
# else:
# provider_name = values[2]
# total_discharges = values[-4].replace('$','')
# avg_covered_charges = values[-3].replace('$','')
# average_total_payments = values[-2].replace('$','')
# avg_medicare_payment = values[-1].replace('$','')
#
# # print(','.join([provider_name, total_discharges, avg_covered_charges, average_total_payments, avg_medicare_payment]))
# #
# # #
# # ## Lab 2: Working with Dictionaries
# from pprint import pprint
#
# bitcoin_data = {
# "ticker": {
# "base":"BTC",
# "target":"USD",
# "markets": [ { "market":"BitFinex",
# "price":"7764.00000000",
# "volume":195270.39909915
# },
# { "market":"Bitstamp",
# "price":"7830.93000000",
# "volume":70962.37875181
# }
# ]
# },
# "timestamp":1517960522
# }
#
# ticker_data = bitcoin_data["ticker"]
# timestamp = bitcoin_data["timestamp"]
#
# btc_markets_records = []
# for market_record in ticker_data["markets"]:
# record_tuple = ( timestamp,
# market_record["market"],
# market_record["price"],
# market_record["volume"])
#
# btc_markets_records.append(record_tuple)
#
# print("Dictionary:")
# pprint(bitcoin_data)
# print("\nList:")
# pprint(btc_markets_records)
# #
#
## Lab 3: Using the json module
import json
filename = './data/beyonce.json'
with open(filename, 'r') as beyonce_file:
beyonce_instagram = json.load(beyonce_file)
print(beyonce_instagram["instagram"])
# for key, value in beyonce_instagram.items():
# print(key, type(value))
# if type(value) == dict:
# for k, v in value.items():
# print("\t", k, type(v))
<file_sep>/module1/README.md
# Module 1: Introduction
The goal of Module 1 of this course is to get you up to speed with these basic programming concepts:
* Numbers (int, bool, float)
* Sequences (string, list)
* Relation and Logic Operators
* Conditionals
* For Loops
We will focus on these topics for the first 3 weeks of this course, apply them much more in Module 2 and 3. To get you up to speed, here is your assignment for this week.
## Reading Assignment:
* Textbook
* Chapter 1
* Chapter 2 sections 1, 2, and 4
* Chapter 3 sections 1, 2, and 4
* Python Documentation
* [The Standard Type Hierarchy](https://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy) (Python Data Model § 3.2)
* Read this section slowly focus on numbers.Numbers and Sequences. It is complicated but very important to understand what we mean by numbers and sequences when we talk about data
* Compound Statements
* [The If Statement](https://docs.python.org/3/reference/compound_stmts.html#the-if-statement) (Python Data Model § 8.1)
* [The For Statement](https://docs.python.org/3/reference/compound_stmts.html#the-for-statement) (Python Data Model § 8.3)
* Just read though these but you will really understand them more by using them in practice
## Programming Exercises:
* Text Book
* Section 2.1 exercises 31 - 65 odd
* Section 2.2 exercises 5 - 45 odd
* Section 2.4 exercises 1 - 29 odd
* Section 3.1 exercises 9 - 43 odd
* Section 3.2 exercises 1 - 13 odd
* Section 3.4 exercises 1 - 31 odd
<file_sep>/module3/menu.py
## Exchange Rate Calculator
print("Exchange Rate Calculator")
while True:
# Input
source_currency = input("Source Currency: ")
target_currency = input("Target Currency: ")
source_amount = eval(input("Starting Amount ({0}): ".format(source_currency)))
exchange_rate = eval(input("Exchange Rate ({1}/{0}): "
.format(target_currency,source_currency)))
fee = eval(input("Transfer fee (as a percentange of starting amount): "))
# Processing
transaction_fees = source_amount * fee / 100
target_amount = (source_amount - transaction_fees) * exchange_rate
# Output
print("Exchanged {0:,.2f} {1} for {2:,.2f} {3}".format(source_amount,
source_currency,
target_amount,
target_currency))
print("Paid {0:,.2f} {1} in fees.".format(transaction_fees,
source_currency))
<file_sep>/test.py
infile = open("Dev.txt", 'r')
dev = [line.rstrip() for line in infile]
infile.close()
dev[0], dev[-1] = dev[-1], dev[0]
word = ("").join(dev) print(word)
<file_sep>/module2/exchange_rates.py
from pprint import pprint
exchange_rates = [ ('BitFinex', 180.92000000, 12309, 0.25),
('Bittrex', 182.97999999, 4343, 0.1),
('C-Cex', 197.49000000, 5, 1.50),
('Exmo', 191.52000000, 342, 0.25),
('Hitbtc', 181.01500000, 2345, 0.10),
('Kraken', 179.23000000, 3442, 0.50),
('Livecoin', 190.00000000, 234, 0.25) ]
investment = float(input("Enter the amount to arbitrage: "))
# Find the expected return going from a -> b exchange
results = []
for a in range(len(exchange_rates)):
for b in range(len(exchange_rates)):
starting_balance = (investment - (investment * exchange_rates[a][3] / 100)) / exchange_rates[a][1]
ending_balance = (starting_balance - (starting_balance * exchange_rates[b][3] / 100)) * exchange_rates[b][1]
results.append( (exchange_rates[a][0],exchange_rates[b][0],ending_balance) )
sorted_results = sorted(results, key=lambda result: result[2])
pprint(sorted_results)
#
# bitrex = (investment - (investment * exchange_rates[1][3] / 100 )) / exchange_rates[1][1]
# ccex = (investment - (investment * exchange_rates[2][3] / 100)) / exchange_rates[2][1]
# exmo = (investment - (investment * exchange_rates[3][3] / 100)) / exchange_rates[3][1]
# hitbtc = (investment - (investment * exchange_rates[4][3] / 100)) / exchange_rates[4][1]
# kraken = (investment - (investment * exchange_rates[5][3] / 100)) / exchange_rates[5][1]
# livecoin = (investment - (investment * exchange_rates[6][3] / 100)) / exchange_rates[6][1]
#
# starting_balances = [bitfinex, bitrex, ccex, exmo, hitbtc, kraken, livecoin]
#
# pprint(starting_balances)
#
#
# bitfinex_bitrex = (bitfinex - (bitfinex * exchange_rates[1][3] / 100)) * exchange_rates[1][1]
# bitfinex_ccex = (bitfinex - (bitfinex * exchange_rates[2][3] / 100)) * exchange_rates[2][1]
# bitfinex_exmo = (bitfinex - (bitfinex * exchange_rates[3][3] / 100)) * exchange_rates[3][1]
# bitfinex_hitbtc = (bitfinex - (bitfinex * exchange_rates[4][3] / 100)) * exchange_rates[4][1]
# bitfinex_kraken = (bitfinex - (bitfinex * exchange_rates[5][3] / 100)) * exchange_rates[5][1]
# bitfinex_livecoin = (bitfinex - (bitfinex * exchange_rates[6][3] / 100)) * exchange_rates[6][1]
#
# ending_balances = [('bitrex',bitfinex_bitrex),
# ('ccex', bitfinex_ccex),
# ('exmo', bitfinex_exmo),
# ('hitbtc', bitfinex_hitbtc),
# ('kraken',bitfinex_kraken),
# ('livecoin', bitfinex_livecoin)]
#
# bitrex_bitfinix = (bitrex - (bitrex * exchange_rates[0][3] / 100)) * exchange_rates[0][1]
# bitrex_ccex = (bitrex - (bitrex * exchange_rates[2][3] / 100)) * exchange_rates[2][1]
# bitrex_exmo = (bitrex - (bitrex * exchange_rates[3][3] / 100)) * exchange_rates[3][1]
# bitrex_hitbtc = (bitrex - (bitrex * exchange_rates[4][3] / 100)) * exchange_rates[4][1]
# bitrex_kraken = (bitrex - (bitrex * exchange_rates[5][3] / 100)) * exchange_rates[5][1]
# bitrex_livecoin = (bitrex - (bitrex * exchange_rates[6][3] / 100)) * exchange_rates[6][1]
#
# ending_balances = [('bitrex_bitfinix',bitrex_bitfinix),
# ('ccex', bitrex_ccex),
# ('exmo', bitrex_exmo),
# ('hitbtc', bitrex_hitbtc),
# ('kraken',bitrex_kraken),
# ('livecoin', bitrex_livecoin)]
#
# pprint(ending_balances)
# Move from one exchange to another (A->B)
# Convert back to USD
# # NOTE: Getting real time
# import urllib.request
# import json
#
# url = 'https://api.cryptonator.com/api/full/btc-usd'
# response = urllib.request.urlopen(url)
# extracted_data = json.load(response)
#
# ticker_data = extracted_data["ticker"]
#
# ltc_markets_rates = []
# for market_record in ticker_data["markets"]:
# record_tuple = (market_record["market"], market_record["price"], market_record["volume"])
# ltc_markets_rates.append(record_tuple)
#
# print(ltc_markets_rates)
| 1b8c41cb286446c1f96e32ee4d9a81ac4460a983 | [
"Markdown",
"Python"
]
| 13 | Python | mikeghen/dss-615-spring-2018 | 904875aa2f6ffe6e2dce4e39fe43f2123ef094d8 | 00f186d9a1a446fcc14583c64d8e59f834da3520 |
refs/heads/main | <repo_name>KomKGT/ModBus_SmartHome<file_sep>/Version1.0_ModBus_SmartHome/QModBus-master/test_rtu/mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//add
counter = 1;
//add
QObject::connect(&mb, SIGNAL(error(QModBus::ModBusError)),
this, SLOT(process_error(QModBus::ModBusError)));
QObject::connect(&mb, &QModBus_RTU::connected,
this, &MainWindow::change_status);
QObject::connect(&mb, SIGNAL(disconnected()),
this, SLOT(change_status()));
QObject::connect(ui->connect_button, SIGNAL(clicked()),
this, SLOT(connect_btn_clicked()));
//read button
QObject::connect(ui->rd_button, SIGNAL(clicked()),
this, SLOT(read_regs()));
QObject::connect(&mb, SIGNAL(response_to_read_regs(int)),
this, SLOT(response_to_read_regs(int)));
//write button
QObject::connect(ui->wr_button, SIGNAL(clicked()),
this, SLOT(write_reg()));
QObject::connect(&mb, SIGNAL(response_to_write_reg(int)),
this, SLOT(response_to_write_reg(int)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::connect_btn_clicked()
{
qDebug() << "Pass";
if( mb.is_connected() )
disconnect_from_dev();
else
connect_to_dev();
}
void MainWindow::connect_to_dev()
{
ui->connect_button->setEnabled(false);
//GUI param to QModBus_RTU object
mb.device = ui->device_line_edit->text();
mb.baudrate = ui->baudrate_combo_box->currentText().toInt();
mb.parity = ui->parity_combo_box->currentText().at(0).toLatin1();
mb.data_bit = ui->data_bits_combo_box->currentText().toInt();
mb.stop_bit = ui->stop_bits_combo_box->currentText().toInt();
mb.set_slave(ui->slave_line_edit->text().toInt());
//show param in Edit
ui->log_plain_text_edit->appendPlainText(QString("###############################"));
ui->log_plain_text_edit->appendPlainText(QString("Device is: %1").arg(mb.device));
ui->log_plain_text_edit->appendPlainText(QString("Slave is: %1").arg(mb.get_slave()));
ui->log_plain_text_edit->appendPlainText(QString("Baudrate is: %1").arg(mb.baudrate));
ui->log_plain_text_edit->appendPlainText(QString("Parity is: %1").arg(mb.parity));
ui->log_plain_text_edit->appendPlainText(QString("Data_bit is: %1").arg(mb.data_bit));
ui->log_plain_text_edit->appendPlainText(QString("Stop_bit is: %1").arg(mb.stop_bit));
ui->log_plain_text_edit->appendPlainText(QString("-------------------------------"));
mb.connect();
}
void MainWindow::disconnect_from_dev()
{
ui->connect_button->setEnabled(false);
mb.disconnect();
}
void MainWindow::read_regs()
{
int addr = ui->rd_reg_line_edit->text().toInt();
int count = ui->rd_count_line_edit->text().toInt();
if( count > MODBUS_MAX_READ_REGISTERS)
{
ui->log_plain_text_edit->appendPlainText(QString("Error count reg is: %1").arg(count));
ui->log_plain_text_edit->insertPlainText(QString("Max count reg is: %1").arg(MODBUS_MAX_READ_REGISTERS));
return;
}
if( count <= 0)
{
ui->log_plain_text_edit->appendPlainText(QString("Error count reg is: %1").arg(count));
return;
}
ui->log_plain_text_edit->appendPlainText(QString("Read Start register: %1 ").arg(addr));
ui->log_plain_text_edit->insertPlainText(QString("Count: %1").arg(count));
ui->rd_button->setEnabled(false);
mb.read_regs(addr, count, rd_buf);
}
void MainWindow::write_reg()
{
int addr = ui->wr_reg_line_edit->text().toInt();
int value = ui->wr_val_line_edit->text().toInt();
ui->log_plain_text_edit->appendPlainText(QString("Write to register: %1 ").arg(addr));
ui->log_plain_text_edit->insertPlainText(QString("value: %1").arg(value));
ui->wr_button->setEnabled(false);
//add
ui->LightBTN->setEnabled(false);
//add
mb.write_reg(addr, value);
}
void MainWindow::response_to_read_regs(int status)
{
int i;
ui->rd_button->setEnabled(true);
if( status <= 0 )
return;
ui->log_plain_text_edit->appendPlainText(QString("Reading regs: %1").arg(status));
for(i = 0; i < status; i++)
{
ui->log_plain_text_edit->appendPlainText(QString("reg[%1] == %2").arg(i).arg(rd_buf[i]));
}
}
void MainWindow::response_to_write_reg(int status)
{
ui->wr_button->setEnabled(true);
//add
ui->LightBTN->setEnabled(true);
//add
if( status == 1 )
{
ui->log_plain_text_edit->appendPlainText(QString("Write done"));
}
}
void MainWindow::process_error(QModBus::ModBusError error)
{
//show error in Edit
ui->log_plain_text_edit->appendPlainText(QString("Error is: %1 strerror: ").arg(error));
ui->log_plain_text_edit->insertPlainText(QString::fromUtf8(mb.get_strerror()));
switch (error)
{
case QModBus::NoConnectionError:
case QModBus::CreateError:
case QModBus::ConnectionError:
{
ui->connect_button->setEnabled(true);
break;
}
case QModBus::ReadRegsError:
{
ui->rd_button->setEnabled(true);
break;
}
case QModBus::WriteRegError:
{
ui->wr_button->setEnabled(true);
break;
}
default:
break;
}
}
void MainWindow::change_status()
{
ui->connect_button->setEnabled(true);
qDebug() << "Check";
if( mb.is_connected() )
{
ui->log_plain_text_edit->appendPlainText("------ connected ------");
ui->connect_button->setText("Disconnect");
return;
}
ui->log_plain_text_edit->appendPlainText("------ disconnected ------\n");
ui->connect_button->setText("Connect");
}
void MainWindow::on_LightBTN_clicked()
{
if(counter%2==1)
{
ui->LightBTN->setText("Light:ON");
ui->wr_reg_line_edit->clear();
ui->wr_reg_line_edit->insert("2");
ui->wr_val_line_edit->clear();
ui->wr_val_line_edit->insert("1");
write_reg();
counter++;
}
else if(counter%2==0)
{
ui->LightBTN->setText("Light:OFF");
ui->wr_reg_line_edit->clear();
ui->wr_reg_line_edit->insert("2");
ui->wr_val_line_edit->clear();
ui->wr_val_line_edit->insert("0");
write_reg();
counter = 1;
}
}
<file_sep>/Version1.0_ModBus_SmartHome/QModBus-master/README.md
# QModBus is wrapper over libmodbus for Qt
### Note
This class is **deprecated**. It was developed when Qt did not support the work with the ModBus protocol.
Now you should use the standard Qt interface to work with ModBus(Since Qt 5.8):[Qt Modbus](https://doc.qt.io/qt-5/qtmodbus-backends.html).
### Examples from Qt Documentation
* [Modbus Slave example](https://doc.qt.io/qt-5/qtserialbus-modbus-slave-example.html)
* [Modbus Master example](https://doc.qt.io/qt-5/qtserialbus-modbus-master-example.html)
## Description
QModBus is abstract C++ class for Qt. QModBus is wrapper over libmodbus for Qt.
From this abstract class inherited two specific classes: **QModBus_TCP** and **QModBus_RTU**.
This class provides the opportunity to work with the library [(libmodbus ver 3.1.2)](http://www.libmodbus.org) in not blocking mode.
**The class has the following public methods:**
```C++
bool is_connected() { return connect_done; }
const char *get_strerror() { return strerror; }
void set_slave(int new_slave);
int get_slave() { return slave; }
void set_response_timeout(uint32_t sec, uint32_t usec);
void get_response_timeout(uint32_t *sec, uint32_t *usec);
```
**The class has the following public signals:**
```C++
signals:
void connected();
void disconnected();
void error(QModBus::ModBusError error);
void response_to_read_regs(int status);
void response_to_write_reg(int status);
void response_to_write_regs(int status);
```
**The class has the following public slots:**
```C++
public slots:
virtual void connect();
virtual void disconnect();
virtual void read_regs(int addr, int num_regs, uint16_t *dest);
virtual void write_reg(int addr, uint16_t value);
virtual void write_regs(int addr, int num_regs, const uint16_t *data);
```
**The class has the following public enums:**
```C++
enum ModBusError
{
NoConnectionError,
CreateError,
ConnectionError,
SetSlaveError,
ReadRegsError,
WriteRegError,
WriteRegsError,
UnknownError = -1
};
```
More details see: **[qmodbus.h](./src/include/qmodbus.h)**
***
## Usage
**To start working, perform the following steps:**
1. You need to include **[qmodbus.h](./src/include/qmodbus.h)** file in your **.cpp** file.
2. And add file **[qmodbus.cpp](./src/qmodbus.cpp)** to list of source files to compile (to qmake project file). (see an example)
***
## Examples
1. **[test_tcp](./test_tcp)** - how to work with the class QModBus_TCP

2. **[test_rtu](./test_rtu)** - how to work with the class QModBus_RTU

## Note:
> In OS Linux Device for test_rtu is: **/dev/tty*** default is: **/dev/ttyUSB0**
> In OS Windows Device for test_rtu is: **\\\\.\COM***
## Build tests
```console
qmake
make
```
## License
[BSD-3-Clause](./LICENSE).
## Copyright
Copyright (C) 2015 <NAME> - <EMAIL>
<file_sep>/Version1.0_ModBus_SmartHome/QModBus-master/libmodbus/win_x86/README.md
## This version of the library has been compiled in the system:
- Microsoft Windows Seven x64 Professional Edition Version 6.1 (build 7601) Service pack 1
- Thread model: win32
- gcc version 4.8.1 (GCC)
**Command for configure and make library in msys:**
```console
$ ./configure --prefix=/libmodbus-3.1.2/lib CFLAGS=-m32 CPPFLAGS=-m32
$ make
$ make install
```
# If you use another system or another compiler, for greater compatibility rebuild the library in your system
<file_sep>/Version1.0_ModBus_SmartHome/QModBus-master/src/include/qmodbus.h
/*
* qmodbus.h
*
*
* version 1.0
*
*
* Copyright (c) 2015, <NAME> - <EMAIL>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1 Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2 Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3 Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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.
*
*/
#ifndef QMODBUS_H
#define QMODBUS_H
#include <QObject>
#include <QString>
#include <QMutex>
#include <QMetaType>
#include <QEvent>
#include <modbus/modbus.h>
#include "qexecthread.h"
class QModBus : public QObject
{
Q_OBJECT
Q_ENUMS(ModBusError)
public:
enum ModBusError
{
NoConnectionError,
CreateError,
ConnectionError,
SetSlaveError,
ReadRegsError,
WriteRegError,
WriteRegsError,
UnknownError = -1
};
public:
virtual ~QModBus();
virtual bool event(QEvent *); //for fast delete
bool is_connected() { return connect_done; }
const char *get_strerror() { return strerror; }
void set_slave(int new_slave);
int get_slave() { return slave; }
void set_response_timeout(uint32_t sec, uint32_t usec);
void get_response_timeout(uint32_t *sec, uint32_t *usec);
signals:
void connected();
void disconnected();
void error(QModBus::ModBusError error);
void response_to_read_regs(int status);
void response_to_write_reg(int status);
void response_to_write_regs(int status);
//signals for inner use
void run_connect();
void run_disconnect();
void run_read_regs(int addr, int num_regs, uint16_t *dest);
void run_write_reg(int addr, uint16_t value);
void run_write_regs(int addr, int num_regs, const uint16_t *data);
public slots:
virtual void connect();
virtual void disconnect();
virtual void read_regs(int addr, int num_regs, uint16_t *dest);
virtual void write_reg(int addr, uint16_t value);
virtual void write_regs(int addr, int num_regs, const uint16_t *data);
protected slots:
void lock_connect();
void lock_disconnect();
void lock_read_regs(int addr, int num_regs, uint16_t *dest);
void lock_write_reg(int addr, uint16_t value);
void lock_write_regs(int addr, int num_regs, const uint16_t *data);
protected:
explicit QModBus();
QModBus(const QModBus& src);
QModBus& operator=(const QModBus&);
modbus_t *mb_ctx;
QMutex mb_ctx_mutex;
const char *strerror;
int slave;
uint32_t response_timeout_sec;
uint32_t response_timeout_usec;
virtual modbus_t* create_ctx() = 0;
void _connect();
void _disconnect();
void _set_slave(int new_slave);
void _set_response_timeout(uint32_t sec, uint32_t usec);
void _get_response_timeout(uint32_t *sec, uint32_t *usec);
int _test_mb_ctx();
int _read_regs(int addr, int num_regs, uint16_t *dest);
int _write_reg(int addr, uint16_t value);
int _write_regs(int addr, int num_regs, const uint16_t *data);
private:
bool connect_done;
QExecThread thread;
};
Q_DECLARE_METATYPE(QModBus::ModBusError)
class QModBus_TCP : public QModBus
{
Q_OBJECT
public:
explicit QModBus_TCP();
QString IP;
int port;
protected:
//no copy constructor
QModBus_TCP(const QModBus_TCP& src);
QModBus_TCP& operator=(const QModBus_TCP&);
virtual modbus_t* create_ctx();
};
class QModBus_RTU : public QModBus
{
Q_OBJECT
public:
explicit QModBus_RTU();
QString device;
int baudrate;
char parity;
int data_bit;
int stop_bit;
protected:
//no copy constructor
QModBus_RTU(const QModBus_RTU& src);
QModBus_RTU& operator=(const QModBus_RTU&);
virtual modbus_t* create_ctx();
};
#endif // QMODBUS_H
<file_sep>/Version1.0_ModBus_SmartHome/QModBus-master/libmodbus/unix_x86_64/README.md
## This version of the library has been compiled in the system:
- Ubuntu 14.04.01 3.13.0-37-generic
- gcc version 4.9.1
**Command for configure and make library:**
```console
$ ./configure --prefix=/home/xxx/projects/libmodbus/libmodbus-3.1.2/lib CFLAGS=-m64 CPPFLAGS=-m64
$ make
$ make install
```
# If you use another system or another compiler, for greater compatibility rebuild the library in your system
<file_sep>/Version1.0_ModBus_SmartHome/QModBus-master/src/qmodbus.cpp
/*
* qmodbus.cpp
*
*
* version 1.0
*
*
* Copyright (c) 2015, <NAME> - <EMAIL>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1 Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2 Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3 Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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.
*
*/
#include <errno.h>
#include <QMutexLocker>
#include "qmodbus.h"
#include "asyncdeltask.h"
QModBus::QModBus() :
QObject(NULL),
//protected
mb_ctx(NULL),
strerror(""),
slave(0),
response_timeout_sec(5),
response_timeout_usec(0),
//private
connect_done(false)
{
qRegisterMetaType<QModBus::ModBusError>("QModBus::ModBusError");
qRegisterMetaType<uint16_t>("uint16_t");
this->moveToThread(&thread);
thread.start();
}
QModBus::~QModBus()
{
thread.quit();
thread.wait();
_disconnect();
}
bool QModBus::event(QEvent *event)
{
// if was call delete_later() method
// We use AsyncDelTask class to remove
// the object asynchronously and does not block the GUI thread
if( event->type() == QEvent::DeferredDelete )
{
AsyncDelTask::async_del(this);
return true;
}
return QObject::event(event);
}
void QModBus::set_slave(int new_slave)
{
QMutexLocker locker(&mb_ctx_mutex);
_set_slave(new_slave);
}
void QModBus::set_response_timeout(uint32_t sec, uint32_t usec)
{
QMutexLocker locker(&mb_ctx_mutex);
_set_response_timeout(sec, usec);
}
void QModBus::get_response_timeout(uint32_t *sec, uint32_t *usec)
{
QMutexLocker locker(&mb_ctx_mutex);
_get_response_timeout(sec, usec);
}
void QModBus::connect()
{
QObject::connect(this, SIGNAL(run_connect()), this, SLOT(lock_connect()), Qt::UniqueConnection);
emit run_connect();
}
void QModBus::disconnect()
{
QObject::connect(this, SIGNAL(run_disconnect()), this, SLOT(lock_disconnect()), Qt::UniqueConnection);
emit run_disconnect();
}
void QModBus::read_regs(int addr, int num_regs, uint16_t *dest)
{
QObject::connect(this, SIGNAL(run_read_regs(int, int, uint16_t*)),
this, SLOT(lock_read_regs(int, int, uint16_t*)), Qt::UniqueConnection);
emit run_read_regs(addr, num_regs, dest);
}
void QModBus::write_reg(int addr, uint16_t value)
{
QObject::connect(this, SIGNAL(run_write_reg(int, uint16_t)),
this, SLOT(lock_write_reg(int, uint16_t)), Qt::UniqueConnection);
emit run_write_reg(addr, value);
}
void QModBus::write_regs(int addr, int num_regs, const uint16_t *data)
{
QObject::connect(this, SIGNAL(run_write_regs(int, int, const uint16_t*)),
this, SLOT(lock_write_regs(int, int, const uint16_t*)), Qt::UniqueConnection);
emit run_write_regs(addr, num_regs, data);
}
void QModBus::lock_connect()
{
QMutexLocker locker(&mb_ctx_mutex);
_connect();
}
void QModBus::lock_disconnect()
{
QMutexLocker locker(&mb_ctx_mutex);
_disconnect();
}
void QModBus::lock_read_regs(int addr, int num_regs, uint16_t *dest)
{
QMutexLocker locker(&mb_ctx_mutex);
int ret;
ret = _read_regs(addr, num_regs, dest);
emit response_to_read_regs(ret);
}
void QModBus::lock_write_reg(int addr, uint16_t value)
{
QMutexLocker locker(&mb_ctx_mutex);
int ret;
ret = _write_reg(addr, value);
emit response_to_write_reg(ret);
}
void QModBus::lock_write_regs(int addr, int num_regs, const uint16_t *data)
{
QMutexLocker locker(&mb_ctx_mutex);
int ret;
ret = _write_regs(addr, num_regs, data);
emit response_to_write_regs(ret);
}
void QModBus::_connect()
{
_disconnect();
mb_ctx = create_ctx();
if( mb_ctx == NULL )
{
strerror = "Can't create the libmodbus context";
emit error(QModBus::CreateError);
return;
}
//set timeout for modbus_connect function
_set_response_timeout(response_timeout_sec, response_timeout_usec);
if( modbus_connect(mb_ctx) == -1 )
{
strerror = modbus_strerror(errno);
emit error(QModBus::ConnectionError);
return;
}
connect_done = true;
_set_slave(slave);
_set_response_timeout(response_timeout_sec, response_timeout_usec);
emit connected(); //good job
}
void QModBus::_disconnect()
{
if( mb_ctx )
{
modbus_close(mb_ctx);
modbus_free(mb_ctx);
mb_ctx = NULL;
}
if(connect_done)
{
connect_done = false;
emit disconnected();
}
}
void QModBus::_set_slave(int new_slave)
{
slave = new_slave;
if( !is_connected() )
return;
if( modbus_set_slave(mb_ctx, slave) == -1 )
{
strerror = modbus_strerror(errno);
emit error(QModBus::SetSlaveError);
}
}
void QModBus::_set_response_timeout(uint32_t sec, uint32_t usec)
{
response_timeout_sec = sec;
response_timeout_usec = usec;
if( is_connected() )
modbus_set_response_timeout(mb_ctx, sec, usec);
}
void QModBus::_get_response_timeout(uint32_t *sec, uint32_t *usec)
{
if( is_connected() )
modbus_get_response_timeout(mb_ctx, sec, usec);
else
{
*sec = response_timeout_sec;
*usec = response_timeout_usec;
}
}
int QModBus::_test_mb_ctx()
{
if( mb_ctx == NULL )
{
strerror = "No Connection";
emit error(QModBus::NoConnectionError);
return -1;
}
return 0; //good job mb_ctx is valid
}
int QModBus::_read_regs(int addr, int num_regs, uint16_t *dest)
{
if( _test_mb_ctx() != 0 )
return -1;
int ret = modbus_read_registers(mb_ctx, addr, num_regs, dest);
if(ret == -1)
{
strerror = modbus_strerror(errno);
emit error(QModBus::ReadRegsError);
return -1;
}
return ret; // return the number of read registers
}
int QModBus::_write_reg(int addr, uint16_t value)
{
if( _test_mb_ctx() != 0 )
return -1;
int ret = modbus_write_register(mb_ctx, addr, value);
if( ret == -1 )
{
strerror = modbus_strerror(errno);
emit error(QModBus::WriteRegError);
return -1;
}
return ret; // return 1 if successful
}
int QModBus::_write_regs(int addr, int num_regs, const uint16_t *data)
{
if( _test_mb_ctx() != 0 )
return -1;
int ret = modbus_write_registers(mb_ctx, addr, num_regs, data);
if( ret == -1 )
{
strerror = modbus_strerror(errno);
emit error(QModBus::WriteRegsError);
return -1;
}
return ret; // return the number of written registers
}
//---------------------- QModBus_TCP ----------------------
QModBus_TCP::QModBus_TCP() :
QModBus(),
//public
IP("127.0.0.1"),
port(MODBUS_TCP_DEFAULT_PORT)
{
}
modbus_t* QModBus_TCP::create_ctx()
{
return modbus_new_tcp(IP.toStdString().c_str(), port);
}
//---------------------- QModBus_RTU ----------------------
QModBus_RTU::QModBus_RTU() :
QModBus(),
//public
device("/dev/ttyUSB0"),
baudrate(115200),
parity('N'),
data_bit(8),
stop_bit(1)
{
}
modbus_t* QModBus_RTU::create_ctx()
{
return modbus_new_rtu(device.toStdString().c_str(), baudrate, parity, data_bit, stop_bit);
}
<file_sep>/Version1.0_ModBus_SmartHome/QModBus-master/build-test_rtu-Desktop-Debug/release/moc_qmodbus.cpp
/****************************************************************************
** Meta object code from reading C++ file 'qmodbus.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../src/include/qmodbus.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'qmodbus.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.5.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_QModBus_t {
QByteArrayData data[42];
char stringdata0[521];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_QModBus_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_QModBus_t qt_meta_stringdata_QModBus = {
{
QT_MOC_LITERAL(0, 0, 7), // "QModBus"
QT_MOC_LITERAL(1, 8, 9), // "connected"
QT_MOC_LITERAL(2, 18, 0), // ""
QT_MOC_LITERAL(3, 19, 12), // "disconnected"
QT_MOC_LITERAL(4, 32, 5), // "error"
QT_MOC_LITERAL(5, 38, 20), // "QModBus::ModBusError"
QT_MOC_LITERAL(6, 59, 21), // "response_to_read_regs"
QT_MOC_LITERAL(7, 81, 6), // "status"
QT_MOC_LITERAL(8, 88, 21), // "response_to_write_reg"
QT_MOC_LITERAL(9, 110, 22), // "response_to_write_regs"
QT_MOC_LITERAL(10, 133, 11), // "run_connect"
QT_MOC_LITERAL(11, 145, 14), // "run_disconnect"
QT_MOC_LITERAL(12, 160, 13), // "run_read_regs"
QT_MOC_LITERAL(13, 174, 4), // "addr"
QT_MOC_LITERAL(14, 179, 8), // "num_regs"
QT_MOC_LITERAL(15, 188, 9), // "uint16_t*"
QT_MOC_LITERAL(16, 198, 4), // "dest"
QT_MOC_LITERAL(17, 203, 13), // "run_write_reg"
QT_MOC_LITERAL(18, 217, 8), // "uint16_t"
QT_MOC_LITERAL(19, 226, 5), // "value"
QT_MOC_LITERAL(20, 232, 14), // "run_write_regs"
QT_MOC_LITERAL(21, 247, 15), // "const uint16_t*"
QT_MOC_LITERAL(22, 263, 4), // "data"
QT_MOC_LITERAL(23, 268, 7), // "connect"
QT_MOC_LITERAL(24, 276, 10), // "disconnect"
QT_MOC_LITERAL(25, 287, 9), // "read_regs"
QT_MOC_LITERAL(26, 297, 9), // "write_reg"
QT_MOC_LITERAL(27, 307, 10), // "write_regs"
QT_MOC_LITERAL(28, 318, 12), // "lock_connect"
QT_MOC_LITERAL(29, 331, 15), // "lock_disconnect"
QT_MOC_LITERAL(30, 347, 14), // "lock_read_regs"
QT_MOC_LITERAL(31, 362, 14), // "lock_write_reg"
QT_MOC_LITERAL(32, 377, 15), // "lock_write_regs"
QT_MOC_LITERAL(33, 393, 11), // "ModBusError"
QT_MOC_LITERAL(34, 405, 17), // "NoConnectionError"
QT_MOC_LITERAL(35, 423, 11), // "CreateError"
QT_MOC_LITERAL(36, 435, 15), // "ConnectionError"
QT_MOC_LITERAL(37, 451, 13), // "SetSlaveError"
QT_MOC_LITERAL(38, 465, 13), // "ReadRegsError"
QT_MOC_LITERAL(39, 479, 13), // "WriteRegError"
QT_MOC_LITERAL(40, 493, 14), // "WriteRegsError"
QT_MOC_LITERAL(41, 508, 12) // "UnknownError"
},
"QModBus\0connected\0\0disconnected\0error\0"
"QModBus::ModBusError\0response_to_read_regs\0"
"status\0response_to_write_reg\0"
"response_to_write_regs\0run_connect\0"
"run_disconnect\0run_read_regs\0addr\0"
"num_regs\0uint16_t*\0dest\0run_write_reg\0"
"uint16_t\0value\0run_write_regs\0"
"const uint16_t*\0data\0connect\0disconnect\0"
"read_regs\0write_reg\0write_regs\0"
"lock_connect\0lock_disconnect\0"
"lock_read_regs\0lock_write_reg\0"
"lock_write_regs\0ModBusError\0"
"NoConnectionError\0CreateError\0"
"ConnectionError\0SetSlaveError\0"
"ReadRegsError\0WriteRegError\0WriteRegsError\0"
"UnknownError"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_QModBus[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
21, 14, // methods
0, 0, // properties
1, 196, // enums/sets
0, 0, // constructors
0, // flags
11, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 119, 2, 0x06 /* Public */,
3, 0, 120, 2, 0x06 /* Public */,
4, 1, 121, 2, 0x06 /* Public */,
6, 1, 124, 2, 0x06 /* Public */,
8, 1, 127, 2, 0x06 /* Public */,
9, 1, 130, 2, 0x06 /* Public */,
10, 0, 133, 2, 0x06 /* Public */,
11, 0, 134, 2, 0x06 /* Public */,
12, 3, 135, 2, 0x06 /* Public */,
17, 2, 142, 2, 0x06 /* Public */,
20, 3, 147, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
23, 0, 154, 2, 0x0a /* Public */,
24, 0, 155, 2, 0x0a /* Public */,
25, 3, 156, 2, 0x0a /* Public */,
26, 2, 163, 2, 0x0a /* Public */,
27, 3, 168, 2, 0x0a /* Public */,
28, 0, 175, 2, 0x09 /* Protected */,
29, 0, 176, 2, 0x09 /* Protected */,
30, 3, 177, 2, 0x09 /* Protected */,
31, 2, 184, 2, 0x09 /* Protected */,
32, 3, 189, 2, 0x09 /* Protected */,
// signals: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, 0x80000000 | 5, 4,
QMetaType::Void, QMetaType::Int, 7,
QMetaType::Void, QMetaType::Int, 7,
QMetaType::Void, QMetaType::Int, 7,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::Int, QMetaType::Int, 0x80000000 | 15, 13, 14, 16,
QMetaType::Void, QMetaType::Int, 0x80000000 | 18, 13, 19,
QMetaType::Void, QMetaType::Int, QMetaType::Int, 0x80000000 | 21, 13, 14, 22,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::Int, QMetaType::Int, 0x80000000 | 15, 13, 14, 16,
QMetaType::Void, QMetaType::Int, 0x80000000 | 18, 13, 19,
QMetaType::Void, QMetaType::Int, QMetaType::Int, 0x80000000 | 21, 13, 14, 22,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::Int, QMetaType::Int, 0x80000000 | 15, 13, 14, 16,
QMetaType::Void, QMetaType::Int, 0x80000000 | 18, 13, 19,
QMetaType::Void, QMetaType::Int, QMetaType::Int, 0x80000000 | 21, 13, 14, 22,
// enums: name, flags, count, data
33, 0x0, 8, 200,
// enum data: key, value
34, uint(QModBus::NoConnectionError),
35, uint(QModBus::CreateError),
36, uint(QModBus::ConnectionError),
37, uint(QModBus::SetSlaveError),
38, uint(QModBus::ReadRegsError),
39, uint(QModBus::WriteRegError),
40, uint(QModBus::WriteRegsError),
41, uint(QModBus::UnknownError),
0 // eod
};
void QModBus::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
QModBus *_t = static_cast<QModBus *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->connected(); break;
case 1: _t->disconnected(); break;
case 2: _t->error((*reinterpret_cast< QModBus::ModBusError(*)>(_a[1]))); break;
case 3: _t->response_to_read_regs((*reinterpret_cast< int(*)>(_a[1]))); break;
case 4: _t->response_to_write_reg((*reinterpret_cast< int(*)>(_a[1]))); break;
case 5: _t->response_to_write_regs((*reinterpret_cast< int(*)>(_a[1]))); break;
case 6: _t->run_connect(); break;
case 7: _t->run_disconnect(); break;
case 8: _t->run_read_regs((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< uint16_t*(*)>(_a[3]))); break;
case 9: _t->run_write_reg((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< uint16_t(*)>(_a[2]))); break;
case 10: _t->run_write_regs((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< const uint16_t*(*)>(_a[3]))); break;
case 11: _t->connect(); break;
case 12: _t->disconnect(); break;
case 13: _t->read_regs((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< uint16_t*(*)>(_a[3]))); break;
case 14: _t->write_reg((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< uint16_t(*)>(_a[2]))); break;
case 15: _t->write_regs((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< const uint16_t*(*)>(_a[3]))); break;
case 16: _t->lock_connect(); break;
case 17: _t->lock_disconnect(); break;
case 18: _t->lock_read_regs((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< uint16_t*(*)>(_a[3]))); break;
case 19: _t->lock_write_reg((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< uint16_t(*)>(_a[2]))); break;
case 20: _t->lock_write_regs((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< const uint16_t*(*)>(_a[3]))); break;
default: ;
}
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
switch (_id) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 2:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QModBus::ModBusError >(); break;
}
break;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (QModBus::*_t)();
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QModBus::connected)) {
*result = 0;
}
}
{
typedef void (QModBus::*_t)();
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QModBus::disconnected)) {
*result = 1;
}
}
{
typedef void (QModBus::*_t)(QModBus::ModBusError );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QModBus::error)) {
*result = 2;
}
}
{
typedef void (QModBus::*_t)(int );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QModBus::response_to_read_regs)) {
*result = 3;
}
}
{
typedef void (QModBus::*_t)(int );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QModBus::response_to_write_reg)) {
*result = 4;
}
}
{
typedef void (QModBus::*_t)(int );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QModBus::response_to_write_regs)) {
*result = 5;
}
}
{
typedef void (QModBus::*_t)();
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QModBus::run_connect)) {
*result = 6;
}
}
{
typedef void (QModBus::*_t)();
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QModBus::run_disconnect)) {
*result = 7;
}
}
{
typedef void (QModBus::*_t)(int , int , uint16_t * );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QModBus::run_read_regs)) {
*result = 8;
}
}
{
typedef void (QModBus::*_t)(int , uint16_t );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QModBus::run_write_reg)) {
*result = 9;
}
}
{
typedef void (QModBus::*_t)(int , int , const uint16_t * );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&QModBus::run_write_regs)) {
*result = 10;
}
}
}
}
const QMetaObject QModBus::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_QModBus.data,
qt_meta_data_QModBus, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *QModBus::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *QModBus::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_QModBus.stringdata0))
return static_cast<void*>(const_cast< QModBus*>(this));
return QObject::qt_metacast(_clname);
}
int QModBus::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 21)
qt_static_metacall(this, _c, _id, _a);
_id -= 21;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 21)
qt_static_metacall(this, _c, _id, _a);
_id -= 21;
}
return _id;
}
// SIGNAL 0
void QModBus::connected()
{
QMetaObject::activate(this, &staticMetaObject, 0, Q_NULLPTR);
}
// SIGNAL 1
void QModBus::disconnected()
{
QMetaObject::activate(this, &staticMetaObject, 1, Q_NULLPTR);
}
// SIGNAL 2
void QModBus::error(QModBus::ModBusError _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 2, _a);
}
// SIGNAL 3
void QModBus::response_to_read_regs(int _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 3, _a);
}
// SIGNAL 4
void QModBus::response_to_write_reg(int _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 4, _a);
}
// SIGNAL 5
void QModBus::response_to_write_regs(int _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 5, _a);
}
// SIGNAL 6
void QModBus::run_connect()
{
QMetaObject::activate(this, &staticMetaObject, 6, Q_NULLPTR);
}
// SIGNAL 7
void QModBus::run_disconnect()
{
QMetaObject::activate(this, &staticMetaObject, 7, Q_NULLPTR);
}
// SIGNAL 8
void QModBus::run_read_regs(int _t1, int _t2, uint16_t * _t3)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)) };
QMetaObject::activate(this, &staticMetaObject, 8, _a);
}
// SIGNAL 9
void QModBus::run_write_reg(int _t1, uint16_t _t2)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 9, _a);
}
// SIGNAL 10
void QModBus::run_write_regs(int _t1, int _t2, const uint16_t * _t3)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)) };
QMetaObject::activate(this, &staticMetaObject, 10, _a);
}
struct qt_meta_stringdata_QModBus_TCP_t {
QByteArrayData data[1];
char stringdata0[12];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_QModBus_TCP_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_QModBus_TCP_t qt_meta_stringdata_QModBus_TCP = {
{
QT_MOC_LITERAL(0, 0, 11) // "QModBus_TCP"
},
"QModBus_TCP"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_QModBus_TCP[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void QModBus_TCP::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObject QModBus_TCP::staticMetaObject = {
{ &QModBus::staticMetaObject, qt_meta_stringdata_QModBus_TCP.data,
qt_meta_data_QModBus_TCP, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *QModBus_TCP::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *QModBus_TCP::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_QModBus_TCP.stringdata0))
return static_cast<void*>(const_cast< QModBus_TCP*>(this));
return QModBus::qt_metacast(_clname);
}
int QModBus_TCP::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QModBus::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
struct qt_meta_stringdata_QModBus_RTU_t {
QByteArrayData data[1];
char stringdata0[12];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_QModBus_RTU_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_QModBus_RTU_t qt_meta_stringdata_QModBus_RTU = {
{
QT_MOC_LITERAL(0, 0, 11) // "QModBus_RTU"
},
"QModBus_RTU"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_QModBus_RTU[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void QModBus_RTU::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObject QModBus_RTU::staticMetaObject = {
{ &QModBus::staticMetaObject, qt_meta_stringdata_QModBus_RTU.data,
qt_meta_data_QModBus_RTU, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *QModBus_RTU::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *QModBus_RTU::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_QModBus_RTU.stringdata0))
return static_cast<void*>(const_cast< QModBus_RTU*>(this));
return QModBus::qt_metacast(_clname);
}
int QModBus_RTU::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QModBus::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
<file_sep>/Version1.0_ModBus_SmartHome/QModBus-master/build-test_rtu-Desktop-Debug/ui_mainwindow.h
/********************************************************************************
** Form generated from reading UI file 'mainwindow.ui'
**
** Created by: Qt User Interface Compiler version 5.5.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QPlainTextEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QWidget *centralWidget;
QGridLayout *gridLayout;
QVBoxLayout *verticalLayout_4;
QHBoxLayout *horizontalLayout_5;
QVBoxLayout *verticalLayout_3;
QVBoxLayout *verticalLayout;
QHBoxLayout *horizontalLayout;
QLabel *device_label;
QLineEdit *device_line_edit;
QLabel *slave_label;
QLineEdit *slave_line_edit;
QLabel *baudrate_label;
QComboBox *baudrate_combo_box;
QHBoxLayout *horizontalLayout_2;
QLabel *parity_label;
QComboBox *parity_combo_box;
QSpacerItem *horizontalSpacer_2;
QLabel *data_bits_label;
QComboBox *data_bits_combo_box;
QSpacerItem *horizontalSpacer_3;
QLabel *stop_bit_label;
QComboBox *stop_bits_combo_box;
QVBoxLayout *verticalLayout_2;
QHBoxLayout *horizontalLayout_3;
QLabel *rd_reg_label;
QLineEdit *rd_reg_line_edit;
QLabel *rd_count_label;
QLineEdit *rd_count_line_edit;
QPushButton *rd_button;
QHBoxLayout *horizontalLayout_4;
QLabel *wr_reg_label;
QLineEdit *wr_reg_line_edit;
QLabel *wr_val_label;
QLineEdit *wr_val_line_edit;
QPushButton *wr_button;
QSpacerItem *horizontalSpacer;
QPushButton *connect_button;
QPlainTextEdit *log_plain_text_edit;
QPushButton *LightBTN;
QStatusBar *statusBar;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QStringLiteral("MainWindow"));
MainWindow->resize(700, 495);
MainWindow->setMaximumSize(QSize(700, 1000));
MainWindow->setUnifiedTitleAndToolBarOnMac(false);
centralWidget = new QWidget(MainWindow);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
gridLayout = new QGridLayout(centralWidget);
gridLayout->setSpacing(6);
gridLayout->setContentsMargins(11, 11, 11, 11);
gridLayout->setObjectName(QStringLiteral("gridLayout"));
verticalLayout_4 = new QVBoxLayout();
verticalLayout_4->setSpacing(6);
verticalLayout_4->setObjectName(QStringLiteral("verticalLayout_4"));
horizontalLayout_5 = new QHBoxLayout();
horizontalLayout_5->setSpacing(6);
horizontalLayout_5->setObjectName(QStringLiteral("horizontalLayout_5"));
verticalLayout_3 = new QVBoxLayout();
verticalLayout_3->setSpacing(6);
verticalLayout_3->setObjectName(QStringLiteral("verticalLayout_3"));
verticalLayout = new QVBoxLayout();
verticalLayout->setSpacing(6);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
horizontalLayout = new QHBoxLayout();
horizontalLayout->setSpacing(6);
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
device_label = new QLabel(centralWidget);
device_label->setObjectName(QStringLiteral("device_label"));
horizontalLayout->addWidget(device_label);
device_line_edit = new QLineEdit(centralWidget);
device_line_edit->setObjectName(QStringLiteral("device_line_edit"));
device_line_edit->setMinimumSize(QSize(240, 0));
device_line_edit->setMaxLength(100);
horizontalLayout->addWidget(device_line_edit);
slave_label = new QLabel(centralWidget);
slave_label->setObjectName(QStringLiteral("slave_label"));
horizontalLayout->addWidget(slave_label);
slave_line_edit = new QLineEdit(centralWidget);
slave_line_edit->setObjectName(QStringLiteral("slave_line_edit"));
slave_line_edit->setMinimumSize(QSize(30, 0));
horizontalLayout->addWidget(slave_line_edit);
baudrate_label = new QLabel(centralWidget);
baudrate_label->setObjectName(QStringLiteral("baudrate_label"));
horizontalLayout->addWidget(baudrate_label);
baudrate_combo_box = new QComboBox(centralWidget);
baudrate_combo_box->setObjectName(QStringLiteral("baudrate_combo_box"));
baudrate_combo_box->setMinimumSize(QSize(100, 0));
horizontalLayout->addWidget(baudrate_combo_box);
verticalLayout->addLayout(horizontalLayout);
horizontalLayout_2 = new QHBoxLayout();
horizontalLayout_2->setSpacing(6);
horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2"));
parity_label = new QLabel(centralWidget);
parity_label->setObjectName(QStringLiteral("parity_label"));
horizontalLayout_2->addWidget(parity_label);
parity_combo_box = new QComboBox(centralWidget);
parity_combo_box->setObjectName(QStringLiteral("parity_combo_box"));
parity_combo_box->setMinimumSize(QSize(110, 0));
horizontalLayout_2->addWidget(parity_combo_box);
horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_2->addItem(horizontalSpacer_2);
data_bits_label = new QLabel(centralWidget);
data_bits_label->setObjectName(QStringLiteral("data_bits_label"));
horizontalLayout_2->addWidget(data_bits_label);
data_bits_combo_box = new QComboBox(centralWidget);
data_bits_combo_box->setObjectName(QStringLiteral("data_bits_combo_box"));
horizontalLayout_2->addWidget(data_bits_combo_box);
horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_2->addItem(horizontalSpacer_3);
stop_bit_label = new QLabel(centralWidget);
stop_bit_label->setObjectName(QStringLiteral("stop_bit_label"));
horizontalLayout_2->addWidget(stop_bit_label);
stop_bits_combo_box = new QComboBox(centralWidget);
stop_bits_combo_box->setObjectName(QStringLiteral("stop_bits_combo_box"));
horizontalLayout_2->addWidget(stop_bits_combo_box);
verticalLayout->addLayout(horizontalLayout_2);
verticalLayout_3->addLayout(verticalLayout);
verticalLayout_2 = new QVBoxLayout();
verticalLayout_2->setSpacing(6);
verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2"));
horizontalLayout_3 = new QHBoxLayout();
horizontalLayout_3->setSpacing(6);
horizontalLayout_3->setObjectName(QStringLiteral("horizontalLayout_3"));
rd_reg_label = new QLabel(centralWidget);
rd_reg_label->setObjectName(QStringLiteral("rd_reg_label"));
horizontalLayout_3->addWidget(rd_reg_label);
rd_reg_line_edit = new QLineEdit(centralWidget);
rd_reg_line_edit->setObjectName(QStringLiteral("rd_reg_line_edit"));
rd_reg_line_edit->setEnabled(true);
horizontalLayout_3->addWidget(rd_reg_line_edit);
rd_count_label = new QLabel(centralWidget);
rd_count_label->setObjectName(QStringLiteral("rd_count_label"));
horizontalLayout_3->addWidget(rd_count_label);
rd_count_line_edit = new QLineEdit(centralWidget);
rd_count_line_edit->setObjectName(QStringLiteral("rd_count_line_edit"));
horizontalLayout_3->addWidget(rd_count_line_edit);
rd_button = new QPushButton(centralWidget);
rd_button->setObjectName(QStringLiteral("rd_button"));
horizontalLayout_3->addWidget(rd_button);
verticalLayout_2->addLayout(horizontalLayout_3);
horizontalLayout_4 = new QHBoxLayout();
horizontalLayout_4->setSpacing(6);
horizontalLayout_4->setObjectName(QStringLiteral("horizontalLayout_4"));
wr_reg_label = new QLabel(centralWidget);
wr_reg_label->setObjectName(QStringLiteral("wr_reg_label"));
horizontalLayout_4->addWidget(wr_reg_label);
wr_reg_line_edit = new QLineEdit(centralWidget);
wr_reg_line_edit->setObjectName(QStringLiteral("wr_reg_line_edit"));
horizontalLayout_4->addWidget(wr_reg_line_edit);
wr_val_label = new QLabel(centralWidget);
wr_val_label->setObjectName(QStringLiteral("wr_val_label"));
horizontalLayout_4->addWidget(wr_val_label);
wr_val_line_edit = new QLineEdit(centralWidget);
wr_val_line_edit->setObjectName(QStringLiteral("wr_val_line_edit"));
horizontalLayout_4->addWidget(wr_val_line_edit);
wr_button = new QPushButton(centralWidget);
wr_button->setObjectName(QStringLiteral("wr_button"));
horizontalLayout_4->addWidget(wr_button);
verticalLayout_2->addLayout(horizontalLayout_4);
verticalLayout_3->addLayout(verticalLayout_2);
horizontalLayout_5->addLayout(verticalLayout_3);
horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_5->addItem(horizontalSpacer);
connect_button = new QPushButton(centralWidget);
connect_button->setObjectName(QStringLiteral("connect_button"));
horizontalLayout_5->addWidget(connect_button);
verticalLayout_4->addLayout(horizontalLayout_5);
log_plain_text_edit = new QPlainTextEdit(centralWidget);
log_plain_text_edit->setObjectName(QStringLiteral("log_plain_text_edit"));
log_plain_text_edit->setMinimumSize(QSize(0, 250));
verticalLayout_4->addWidget(log_plain_text_edit);
gridLayout->addLayout(verticalLayout_4, 0, 0, 1, 1);
LightBTN = new QPushButton(centralWidget);
LightBTN->setObjectName(QStringLiteral("LightBTN"));
LightBTN->setCheckable(true);
gridLayout->addWidget(LightBTN, 1, 0, 1, 1);
MainWindow->setCentralWidget(centralWidget);
statusBar = new QStatusBar(MainWindow);
statusBar->setObjectName(QStringLiteral("statusBar"));
MainWindow->setStatusBar(statusBar);
#ifndef QT_NO_SHORTCUT
device_label->setBuddy(device_line_edit);
baudrate_label->setBuddy(baudrate_combo_box);
parity_label->setBuddy(parity_combo_box);
data_bits_label->setBuddy(data_bits_combo_box);
stop_bit_label->setBuddy(stop_bits_combo_box);
#endif // QT_NO_SHORTCUT
retranslateUi(MainWindow);
baudrate_combo_box->setCurrentIndex(19);
data_bits_combo_box->setCurrentIndex(3);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QApplication::translate("MainWindow", "Test_RTU", 0));
device_label->setText(QApplication::translate("MainWindow", "Device:", 0));
#ifndef QT_NO_WHATSTHIS
device_line_edit->setWhatsThis(QString());
#endif // QT_NO_WHATSTHIS
device_line_edit->setText(QApplication::translate("MainWindow", "/dev/ttyUSB0", 0));
slave_label->setText(QApplication::translate("MainWindow", "Slave:", 0));
slave_line_edit->setText(QApplication::translate("MainWindow", "1", 0));
baudrate_label->setText(QApplication::translate("MainWindow", "Baudrate:", 0));
baudrate_combo_box->clear();
baudrate_combo_box->insertItems(0, QStringList()
<< QApplication::translate("MainWindow", "50", 0)
<< QApplication::translate("MainWindow", "75", 0)
<< QApplication::translate("MainWindow", "110", 0)
<< QApplication::translate("MainWindow", "150", 0)
<< QApplication::translate("MainWindow", "300", 0)
<< QApplication::translate("MainWindow", "600", 0)
<< QApplication::translate("MainWindow", "1200", 0)
<< QApplication::translate("MainWindow", "1800", 0)
<< QApplication::translate("MainWindow", "2000", 0)
<< QApplication::translate("MainWindow", "2400", 0)
<< QApplication::translate("MainWindow", "3600", 0)
<< QApplication::translate("MainWindow", "4800", 0)
<< QApplication::translate("MainWindow", "7200", 0)
<< QApplication::translate("MainWindow", "9600", 0)
<< QApplication::translate("MainWindow", "14400", 0)
<< QApplication::translate("MainWindow", "19200", 0)
<< QApplication::translate("MainWindow", "28800", 0)
<< QApplication::translate("MainWindow", "38400", 0)
<< QApplication::translate("MainWindow", "57600", 0)
<< QApplication::translate("MainWindow", "115200", 0)
);
parity_label->setText(QApplication::translate("MainWindow", "Parity:", 0));
parity_combo_box->clear();
parity_combo_box->insertItems(0, QStringList()
<< QApplication::translate("MainWindow", "N - for none", 0)
<< QApplication::translate("MainWindow", "E - for even", 0)
<< QApplication::translate("MainWindow", "O - for odd", 0)
);
data_bits_label->setText(QApplication::translate("MainWindow", "Data_bits:", 0));
data_bits_combo_box->clear();
data_bits_combo_box->insertItems(0, QStringList()
<< QApplication::translate("MainWindow", "5", 0)
<< QApplication::translate("MainWindow", "6", 0)
<< QApplication::translate("MainWindow", "7", 0)
<< QApplication::translate("MainWindow", "8", 0)
);
stop_bit_label->setText(QApplication::translate("MainWindow", "Stop_bits:", 0));
stop_bits_combo_box->clear();
stop_bits_combo_box->insertItems(0, QStringList()
<< QApplication::translate("MainWindow", "1", 0)
<< QApplication::translate("MainWindow", "2", 0)
);
rd_reg_label->setText(QApplication::translate("MainWindow", "Reg:", 0));
rd_reg_line_edit->setText(QApplication::translate("MainWindow", "0", 0));
rd_count_label->setText(QApplication::translate("MainWindow", "Count", 0));
rd_count_line_edit->setText(QApplication::translate("MainWindow", "1", 0));
rd_button->setText(QApplication::translate("MainWindow", "Read", 0));
wr_reg_label->setText(QApplication::translate("MainWindow", "Reg:", 0));
wr_reg_line_edit->setText(QApplication::translate("MainWindow", "0", 0));
wr_val_label->setText(QApplication::translate("MainWindow", "Value", 0));
wr_val_line_edit->setText(QApplication::translate("MainWindow", "0", 0));
wr_button->setText(QApplication::translate("MainWindow", "Write", 0));
connect_button->setText(QApplication::translate("MainWindow", "Connect", 0));
LightBTN->setText(QApplication::translate("MainWindow", "Light:OFF", 0));
} // retranslateUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
| d8b8668db99615a8dd9cb2c17cd4662106290a8f | [
"Markdown",
"C++"
]
| 8 | C++ | KomKGT/ModBus_SmartHome | 43e519376038fa32225a5222ac6835b346de03e2 | 1a45b3b0de26ee3feebdb2e89548dda9ade9b19b |
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 org.Object;
/**
*
* @author Suanny
*/
public class Usuario {
Integer idUsuario;
String nickName;
String password;
String nombre;
String apellido;
String cedula;
String fechaNacimiento;
String correo;
String direccion;
Integer nivelAcademico;
Integer idCiudad;
Integer idInstitucion;
Integer idProfesion;
Rol idRol;
public Usuario() {
}
public Usuario(Integer idUsuario) {
this.idUsuario = idUsuario;
}
public Integer getIdInstitucion() {
return idInstitucion;
}
public void setIdInstitucion(Integer idInstitucion) {
this.idInstitucion = idInstitucion;
}
public Integer getIdProfesion() {
return idProfesion;
}
public void setIdProfesion(Integer idProfesion) {
this.idProfesion = idProfesion;
}
public Integer getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(Integer idUsuario) {
this.idUsuario = idUsuario;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public String getCedula() {
return cedula;
}
public void setCedula(String cedula) {
this.cedula = cedula;
}
public String getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(String fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public String getCorreo() {
return correo;
}
public void setCorreo(String correo) {
this.correo = correo;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public Integer getNivelAcademico() {
return nivelAcademico;
}
public void setNivelAcademico(Integer nivelAcademico) {
this.nivelAcademico = nivelAcademico;
}
public Integer getIdCiudad() {
return idCiudad;
}
public void setIdCiudad(Integer idCiudad) {
this.idCiudad = idCiudad;
}
public Rol getIdRol() {
return idRol;
}
public void setIdRol(Rol idRol) {
this.idRol = idRol;
}
}
<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 org.Object;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author F
*/
public class Proyecto {
Integer id;
String titulo;
String semestre;
String fecha;
String objetivo;
String carrera;
String periodo;
String anio;
String url;
String resumen;
Usuario coordinador;
ArrayList<Autor> autores;
ArrayList<Variable> variables;
public Proyecto(Integer id) {
this.id = id;
}
public Proyecto(Integer id, String titulo) {
this.id = id;
this.titulo = titulo;
}
public Proyecto() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getSemestre() {
return semestre;
}
public void setSemestre(String semestre) {
this.semestre = semestre;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public String getObjetivo() {
return objetivo;
}
public void setObjetivo(String objetivo) {
this.objetivo = objetivo;
}
public String getCarrera() {
return carrera;
}
public void setCarrera(String carrera) {
this.carrera = carrera;
}
public String getPeriodo() {
return periodo;
}
public void setPeriodo(String periodo) {
this.periodo = periodo;
}
public String getAnio() {
return anio;
}
public void setAnio(String anio) {
this.anio = anio;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getResumen() {
return resumen;
}
public void setResumen(String resumen) {
this.resumen = resumen;
}
public Usuario getCoordinador() {
return coordinador;
}
public void setCoordinador(Usuario coordinador) {
this.coordinador = coordinador;
}
public ArrayList<Autor> getAutores() {
return autores;
}
public void setAutores(ArrayList<Autor> autores) {
this.autores = autores;
}
public ArrayList<Variable> getVariables() {
return variables;
}
public void setVariables(ArrayList<Variable> variables) {
this.variables = variables;
}
@Override
public String toString() {
return "Proyecto{" + "id=" + id + ", titulo=" + titulo + ", semestre=" + semestre + ", fecha=" + fecha + ", objetivo=" + objetivo + ", carrera=" + carrera + ", periodo=" + periodo + ", url=" + url + '}';
}
}
<file_sep>deploy.ant.properties.file=C:\\Users\\DANIELA\\AppData\\Roaming\\NetBeans\\8.2\\config\\GlassFishEE6\\Properties\\gfv3-1161610441.properties
file.reference.mysql-connector-java-5.1.48.jar=C:\\Users\\DANIELA\\Desktop\\Dani\\7mo Semestre\\PI\\repositorioproyectos\\librerias\\mysql-connector-java-5.1.48.jar
file.reference.rengine.jar=C:\\Users\\DANIELA\\Desktop\\Dani\\7mo Semestre\\PI\\repositorioproyectos\\librerias\\rengine.jar
file.reference.RserveEngine.jar=C:\\Users\\DANIELA\\Desktop\\Dani\\7mo Semestre\\PI\\repositorioproyectos\\librerias\\RserveEngine.jar
j2ee.platform.is.jsr109=true
j2ee.server.domain=C:/Users/DANIELA/AppData/Roaming/NetBeans/8.2/config/GF_4.1.1/domain1
j2ee.server.home=C:/Program Files/glassfish-4.1.1/glassfish
j2ee.server.instance=[C:\\Program Files\\glassfish-4.1.1\\glassfish;C:\\Program Files\\glassfish-4.1.1\\glassfish\\domains\\domain1]deployer:gfv3ee6wc:localhost:4848
j2ee.server.middleware=C:/Program Files/glassfish-4.1.1
selected.browser=Chrome
user.properties.file=C:\\Users\\DANIELA\\AppData\\Roaming\\NetBeans\\8.2\\build.properties
<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 org.Object;
import java.io.Serializable;
/**
*
* @author F
*/
public class Variable implements Serializable {
Integer id;
Integer idProyecto;
String tipo;
String variable;
public Variable() {
}
public Variable(Integer id, Integer idProyecto, String tipo, String variable) {
this.id = id;
this.idProyecto = idProyecto;
this.tipo = tipo;
this.variable = variable;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getIdProyecto() {
return idProyecto;
}
public void setIdProyecto(Integer idProyecto) {
this.idProyecto = idProyecto;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getVariable() {
return variable;
}
public void setVariable(String variable) {
this.variable = variable;
}
@Override
public String toString() {
return "Variable{" + "id=" + id + ", idProyecto=" + idProyecto + ", tipo=" + tipo + ", variable=" + variable + '}';
}
}
<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 org.Controladores;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.Object.Usuario;
import org.DAO.ConexionMySQL;
/**
*
* @author F
*/
public class CoordinadorController extends ConexionMySQL {
public ArrayList<Usuario> getCoordinadores(String nombre) {
ArrayList<Usuario> coordinadores = new ArrayList<>();
PreparedStatement pst = null;
ResultSet rs = null;
String sql;
nombre = nombre.trim();
try {
sql = "SELECT * FROM(SELECT idUsuario, nombre, apellido FROM usuario WHERE Rol_idRol=2) AS p \n";
sql = sql.concat("WHERE p.nombre LIKE ? OR p.apellido LIKE ? \n");
sql = sql.concat("OR CONCAT_WS(' ', p.nombre, p.apellido) LIKE ? ;");
pst = getConnection().prepareStatement(sql);
pst.setString(1, "%" + nombre + "%");
pst.setString(2, "%" + nombre + "%");
pst.setString(3, "%" + nombre + "%");
rs = pst.executeQuery();
while (rs.next()) {
Usuario user = new Usuario();
user.setIdUsuario(rs.getInt("idUsuario"));
user.setNombre(rs.getString("nombre") + " " + rs.getString("apellido"));
coordinadores.add(user);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
} finally {
try {
if (isConected()) {
getConnection().close();
}
if (pst != null) {
pst.close();
}
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
System.err.println(e.getMessage());
}
}
return coordinadores;
}
public String insertCoordinadores(String user, String password, String nombre, String apellido, String cedula, String nacimiento, String email,
String direccion, Integer nivelacademico, Integer idciudad, Integer idprofesion, Integer idinstitucion) {
String sms = "";
PreparedStatement pst = null;
try {
if (existsCoordinador(cedula, email) != true) {
Integer estado;
String sql;
sql = "insert into usuario (nickName,password,nombre,apellido,cedula,fechaNacimiento,correo,direccion,nivelAcademico,Ciudad_idCiudad,Rol_idRol,Profesion_idProfesion,Institucion_idInstitucion) values (?,?,?,?,?,?,?,?,?,?,2,?,?);";
pst = getConnection().prepareStatement(sql);
pst.setString(1, user);
pst.setString(2, password);
pst.setString(3, nombre);
pst.setString(4, apellido);
pst.setString(5, cedula);
pst.setString(6, nacimiento);
pst.setString(7, email);
pst.setString(8, direccion);
pst.setInt(9, nivelacademico);
pst.setInt(10, idciudad);
pst.setInt(11, idprofesion);
pst.setInt(12, idinstitucion);
estado = pst.executeUpdate();
if (estado > 0) {
sms = "Datos del coordinador ingresados exitosamente";
} else {
sms = "No se ingresaron los datos, intente nuevamente";
}
} else {
sms = "Ya existe un Coordinador registrado con ese No. de Identificacion y/o Email";
}
} catch (SQLException e) {
sms = "A ocurrido un error al guardar la informacion";
} finally {
try {
if (isConected()) {
getConnection().close();
}
if (pst != null) {
pst.close();
}
} catch (SQLException e) {
System.err.println(e.getMessage());
}
}
return sms;
}
private boolean existsCoordinador(String identificacion, String email) throws SQLException {
PreparedStatement pst = null;
ResultSet rs = null;
String sql;
int cont = 0;
sql = "select count(*) from usuario where cedula = ? or correo = ?;";
pst = getConnection().prepareStatement(sql);
pst.setString(1, identificacion);
pst.setString(2, email);
rs = pst.executeQuery();
if (rs.next()) {
cont = rs.getInt(1);
}
pst.close();
rs.close();
return cont > 0;
}
public Usuario getCoordinadorProyecto(String idProyecto) {
Usuario coordinador = new Usuario();
PreparedStatement pst = null;
ResultSet rs = null;
String sql = "";
try {
sql = sql.concat("SELECT u.idUsuario, u.nombre, u.apellido ");
sql = sql.concat("FROM proyecto_integrador p INNER JOIN usuario u ");
sql = sql.concat("ON u.idUsuario=p.id_usuario WHERE p.id_proyecto = ?");
pst = getConnection().prepareStatement(sql);
pst.setString(1, idProyecto);
rs = pst.executeQuery();
if (rs.next()) {
coordinador.setIdUsuario(rs.getInt("idUsuario"));
coordinador.setNombre(rs.getString("nombre"));
coordinador.setApellido(rs.getString("apellido"));
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
} finally {
try {
if (isConected()) {
getConnection().close();
}
if (pst != null) {
pst.close();
}
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
System.err.println(e.getMessage());
}
}
return coordinador;
}
}
<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 org.Object;
/**
*
* @author crist
*/
public class Facultad {
Integer id;
Integer id_facultad;
String nombre;
public Facultad() {
}
public Facultad(Integer id_facultad, String nombre) {
this.id_facultad = id_facultad;
this.nombre = nombre;
}
public Facultad(Integer id, Integer id_facultad, String nombre) {
this.id = id;
this.id_facultad = id_facultad;
this.nombre = nombre;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId_facultad() {
return id_facultad;
}
public void setId_facultad(Integer id_facultad) {
this.id_facultad = id_facultad;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
<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 org.servlet;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.Controladores.AutorController;
import org.Controladores.CarreraController;
import org.Controladores.CiudadController;
import org.Controladores.CoordinadorController;
import org.Controladores.FacultadController;
import org.Controladores.InstitucionController;
import org.Controladores.ProfesionController;
import org.Controladores.ProvinciaController;
import org.Object.Usuario;
import org.Object.Autor;
import org.Object.Provincia;
import org.Object.Ciudad;
import org.Object.Profesion;
import org.Object.Institucion;
import org.Object.Carrera;
import org.Object.Facultad;
/**
*
* @author F
*/
public class Autocomplete 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 {
String nombre = request.getParameter("nombre");
String tipo = request.getParameter("tipo");
String json = "[]";
if(tipo.equals("coordinador")){
ArrayList<Usuario> coordinadores = new CoordinadorController().getCoordinadores(nombre);
json = new Gson().toJson(coordinadores);
}
if(tipo.equals("autor")){
ArrayList<Autor> autor = new AutorController().getAutores(nombre);
json = new Gson().toJson(autor);
}
if(tipo.equals("provincia")){
ArrayList<Provincia> provincia = new ProvinciaController().getProvincias(nombre);
json = new Gson().toJson(provincia);
}
if(tipo.equals("ciudad")){
Integer idp = Integer.parseInt(request.getParameter("idProvincia"));
ArrayList<Ciudad> ciudad = new CiudadController().getCiudades(nombre, idp);
json = new Gson().toJson(ciudad);
}
if(tipo.equals("profesion")){
ArrayList<Profesion> profesion = new ProfesionController().getProfesiones(nombre);
json = new Gson().toJson(profesion);
}
if(tipo.equals("institucion")){
ArrayList<Institucion> institucion = new InstitucionController().getInstituciones(nombre);
json = new Gson().toJson(institucion);
}
if(tipo.equals("carrera")){
ArrayList<Carrera> carrera = new CarreraController().getCarreras(nombre);
json = new Gson().toJson(carrera);
}
if(tipo.equals("facultad")){
ArrayList<Facultad> facultad = new FacultadController().getFacultades(nombre);
json = new Gson().toJson(facultad);
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
// <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 {
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 {
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>
}
<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 org.Object;
/**
*
* @author Suanny
*/
public class Profesion {
Integer profesionID;
String nombre;
public Profesion()
{
}
public Profesion(Integer profesionID, String nombre) {
this.profesionID = profesionID;
this.nombre = nombre;
}
public Integer getProfesionID() {
return profesionID;
}
public void setProfesionID(Integer profesionID) {
this.profesionID = profesionID;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
<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 org.servlet;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import model.ConexionR;
/**
*
* @author cris_
*/
@MultipartConfig
@WebServlet(name = "SubirArchGener", urlPatterns = {"/SubirArchGener"})
public class SubirArchGener 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 {
}
// <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 {
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 variblesClase = request.getParameter("txtVariables");
String numRequer = request.getParameter("txtestimar");
try {
//file1 es el nombre de subir archivos
Part filePart = request.getPart("file1"); // Retrieves <input type="file" name="file">
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
InputStream fileContent = filePart.getInputStream();
File fichero = new File("C:\\Users\\cris_\\Desktop\\pivi\\Nueva carpeta\\PII\\web\\GenerarDatos", fileName);
String rut = "C:/Users/cris_/Desktop/pivi/Nueva carpeta/PII/web/GenerarDatos/" + fileName;
//Llama a la conexion a R recordar que se necesita tener iniciado RServer en R investigar sobre R server
ConexionR con = new ConexionR();
con.conectar(rut, variblesClase, numRequer);
try (InputStream input = filePart.getInputStream()) {
Files.copy(input, fichero.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
//out.print("data in inserted");
} catch (IOException | ServletException e) {
// out.print(e.getMessage());
}
request.getRequestDispatcher("descargarDG.html").forward(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<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 org.Controladores;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.Object.Usuario;
import org.DAO.ConexionMySQL;
import org.Object.Encript;
/**
*
* @author Suanny
*/
@WebServlet(name = "InsertUsuario", urlPatterns = {"/InsertUsuario"})
public class InsertUsuario 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, ParseException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Usuario usuario = new Usuario();
usuario.setIdUsuario(Integer.parseInt(request.getParameter("ID")));
usuario.setNickName(request.getParameter("usuario"));
usuario.setPassword(request.getParameter("<PASSWORD>"));
usuario.setNombre(request.getParameter("nombre"));
usuario.setApellido(request.getParameter("apellido"));
usuario.setFechaNacimiento(request.getParameter("fechaNacimiento"));
usuario.setCorreo(request.getParameter("correo"));
usuario.setNivelAcademico(Integer.parseInt(request.getParameter("nivelAcademico")));
usuario.setDireccion(request.getParameter("direccion"));
usuario.setIdCiudad(Integer.parseInt(request.getParameter("ciudad_id")));
usuario.setIdProfesion(Integer.parseInt(request.getParameter("provinciaid")));
usuario.setIdProfesion(Integer.parseInt(request.getParameter("idProfesion")));
usuario.setIdInstitucion(Integer.parseInt(request.getParameter("idInstitucion")));
ConexionMySQL conex = new ConexionMySQL();
String date = usuario.getFechaNacimiento() + " 00:00:00";
boolean band = false;
String contraseña = <PASSWORD>(usuario.getPassword());
String clave1 = request.getParameter("clave");
String clave2 = request.getParameter("clave2");
if ("0".equals(request.getParameter("ID"))) {
String userR = ConexionMySQL.seleccion("select count(*) as resultado from usuario where nickName='" + usuario.getNickName() + "'");
if ("0".equals(userR)) {
String cadena = "insert into usuario(nickName, password ,nombre, apellido, Profesion_idProfesion,Institucion_idInstitucion,fechaNacimiento, correo, direccion, nivelAcademico, Ciudad_idCiudad, Rol_idRol) "
+ "values ('" + usuario.getNickName() + "','" + contraseña + "','" + usuario.getNombre() + "','" + usuario.getApellido() + "'," + usuario.getIdProfesion() + "," + usuario.getIdInstitucion() + ",'" + date + "','" + usuario.getCorreo() + "','" + usuario.getDireccion() + "','" + usuario.getNivelAcademico() + "'," + usuario.getIdCiudad() + ",1);";
if (clave1 == null ? clave2 == null : clave1.equals(clave2)) {
band = conex.accion(cadena);
if (band == true) {
out.println("<script>alert(\"Datos Registrados Exitosamente\"); </script>");
out.println("<script>location.href = \"http://\" + window.location.host + \"/PII/RegistroUsuario.jsp\"</script>");
// response.sendRedirect("http://localhost:8082/PII/RegistroUsuario.jsp");
}
} else {
// response.sendRedirect("http://localhost:8082/PII/RegistroUsuario.jsp");
// out.println("<script>alert(\"Las contraseñas no coinciden. Vuelva a intentarlo\"); </script>");
}
} else {
out.println("<script>alert(\"Advertencia al insertar: El nombre de usuario ya existe\"); </script>");
}
} else {
String userR = ConexionMySQL.seleccion("select count(*) as resultado from usuario where nickName='" + usuario.getNickName() + "' and idUsuario !='" + usuario.getIdUsuario() + "'");
if ("0".equals(userR)) {
if ("".equals(clave1) && "".equals(clave2)) {
String cadena = "update usuario set nickName='" + usuario.getNickName() + "',nombre='" + usuario.getNombre() + "',\n"
+ "apellido='" + usuario.getApellido() + "', cedula='" + usuario.getCedula() + "',fechaNacimiento='" + usuario.getFechaNacimiento() + "',\n"
+ "correo='" + usuario.getCorreo() + "', direccion='" + usuario.getDireccion() + "',nivelAcademico='" + usuario.getNivelAcademico() + "', \n"
+ "Ciudad_idCiudad='" + usuario.getIdCiudad() + "',Profesion_idProfesion='" + usuario.getIdProfesion() + "',Institucion_idInstitucion='" + usuario.getIdInstitucion() + "'\n"
+ "where idUsuario=" + usuario.getIdUsuario() + ";";
band = conex.accion(cadena);
if (band == true) {
out.println("<script>alert(\"Datos Modificados Exitosamente\"); </script>");
response.sendRedirect("http://localhost:8082/PII/RegistroUsuario.jsp");
}
} else {
String cadena = "update usuario set nickName='" + usuario.getNickName() + "',password='" + <PASSWORD> + "' ,nombre='" + usuario.getNombre() + "',\n"
+ "apellido='" + usuario.getApellido() + "', cedula='" + usuario.getCedula() + "',fechaNacimiento='" + usuario.getFechaNacimiento() + "',\n"
+ "correo='" + usuario.getCorreo() + "', direccion='" + usuario.getDireccion() + "',nivelAcademico='" + usuario.getNivelAcademico() + "', \n"
+ "Ciudad_idCiudad='" + usuario.getIdCiudad() + "',Profesion_idProfesion='" + usuario.getIdProfesion() + "',Institucion_idInstitucion='" + usuario.getIdInstitucion() + "'\n"
+ "where idUsuario=" + usuario.getIdUsuario() + ";";
band = conex.accion(cadena);
if (band == true) {
out.println("<script>alert(\"Datos Modificados Exitosamente\"); </script>");
response.sendRedirect("http://localhost:8082/PII/RegistroUsuario.jsp");
}
}
} else {
out.println("<script>alert(\"El nombre de usuario ya existe\"); </script>");
}
}
}
}
// <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 {
try {
processRequest(request, response);
} catch (ParseException ex) {
Logger.getLogger(InsertUsuario.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* 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 {
try {
processRequest(request, response);
} catch (ParseException ex) {
Logger.getLogger(InsertUsuario.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<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 model;
/**
*
* @author cris_
*/
public class RepositorioD {
private int idDonaciones;
private String nombreConjuntoDatos;
private String tipoDatos;
private String tarea;
private String tipoAtributo;
private String numeroInstancia;
private String numeroAtributos;
private String anio;
private String observacion;
private String validacion;
public String getValidacion() {
return validacion;
}
public void setValidacion(String validacion) {
this.validacion = validacion;
}
public String getObservacion() {
return observacion;
}
public void setObservacion(String observacion) {
this.observacion = observacion;
}
public int getIdDonaciones() {
return idDonaciones;
}
public void setIdDonaciones(int idDonaciones) {
this.idDonaciones = idDonaciones;
}
public String getNombreConjuntoDatos() {
return nombreConjuntoDatos;
}
public void setNombreConjuntoDatos(String nombreConjuntoDatos) {
this.nombreConjuntoDatos = nombreConjuntoDatos;
}
public String getTipoDatos() {
return tipoDatos;
}
public void setTipoDatos(String tipoDatos) {
this.tipoDatos = tipoDatos;
}
public String getTarea() {
return tarea;
}
public void setTarea(String tarea) {
this.tarea = tarea;
}
public String getTipoAtributo() {
return tipoAtributo;
}
public void setTipoAtributo(String tipoAtributo) {
this.tipoAtributo = tipoAtributo;
}
public String getNumeroInstancia() {
return numeroInstancia;
}
public void setNumeroInstancia(String numeroInstancia) {
this.numeroInstancia = numeroInstancia;
}
public String getNumeroAtributos() {
return numeroAtributos;
}
public void setNumeroAtributos(String numeroAtributos) {
this.numeroAtributos = numeroAtributos;
}
public String getAnio() {
return anio;
}
public void setAnio(String anio) {
this.anio = anio;
}
void setObservacion(int i) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
<file_sep>
function saluda(){
var nomBArt= 'El libro';
var nomBAut= 'El autor';
var fCreacion= '11 abr 2018';
var fMod= '14 may 2019';
var textC='Informacin InformacinInformacin Informacin Informacin Informacin Informacin InformacinInformacin Informacin Informacin Informacin Informacin InformacinInformacin Informacin Informacin Informacin';
var sec1= '<div class="IniCards"><div><img src="iconos/icons8_Database_104px.png" class="IniCardsImg" alt=""></div><div class="iniConCardsSec"><a href="#" class="IniCardsTitulo">';
var sec2='</a><div><div class="iniConCardsSec"><p class="IniCardInfoRel">Conjunto de datos por</p><a href="#" class="IniCardInfoRel">';
var sec3='</a> |<p class="IniCardInfoRel"> Fecha de creación ';
var sec4='</p> |<p class="IniCardInfoRel"> Ultima modificación ';
var sec5='</p></div><p class="IniCardsInformacion">';
var sec6= '</p> </div></div></div>';
var cadenaF=sec1+nomBArt+sec2+nomBAut+sec3+fCreacion+sec4+fMod+sec5+textC+sec6;
$("#contenedores").append(cadenaF);
}
<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 org.Controladores;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.DAO.ConexionMySQL;
import org.Object.Variable;
/**
*
* @author F
*/
public class VariableController extends ConexionMySQL {
ArrayList<Variable> getVariablesProyecto(String idProyecto) {
ArrayList<Variable> variables = new ArrayList<>();
PreparedStatement pst = null;
ResultSet rs = null;
String sql = "";
try {
sql = sql.concat("SELECT v.id_variable,v.id_proyecto, v.tipo, v.variable \n");
sql = sql.concat("FROM variable v INNER JOIN proyecto_integrador p \n");
sql = sql.concat("ON v.id_proyecto=p.id_proyecto WHERE p.id_proyecto = ?");
pst = getConnection().prepareStatement(sql);
pst.setString(1, idProyecto);
rs = pst.executeQuery();
while (rs.next()) {
Variable variable = new Variable();
variable.setId(rs.getInt("id_variable"));
variable.setIdProyecto(rs.getInt("id_proyecto"));
variable.setTipo(rs.getString("tipo"));
variable.setVariable(rs.getString("variable"));
variables.add(variable);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
} finally {
try {
if (isConected()) {
getConnection().close();
}
if (pst != null) {
pst.close();
}
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
System.err.println(e.getMessage());
}
}
return variables;
}
public void insertVariableProyecto(ArrayList<Variable> variable, Integer idproyecto) throws SQLException {
PreparedStatement pst = null;
String sql = "insert into variable (id_proyecto,tipo,variable) values (?, ?, ?);";
for (Variable i : variable) {
pst = getConnection().prepareStatement(sql);
pst.setInt(1, idproyecto);
pst.setString(2, i.getTipo());
pst.setString(3, i.getVariable());
pst.executeUpdate();
}
if (pst != null) {
pst.close();
}
}
public void updateVariableProyecto(ArrayList<Variable> variables, Integer idproyecto) throws SQLException {
PreparedStatement pst;
String sql = "DELETE FROM variable WHERE id_proyecto = ?;";
pst = getConnection().prepareStatement(sql);
pst.setInt(1, idproyecto);
pst.executeUpdate();
this.insertVariableProyecto(variables, idproyecto);
pst.close();
}
}
| 1734e453125ade38f4349036af9d55932d7f0d8b | [
"JavaScript",
"Java",
"INI"
]
| 13 | Java | josegerar/repositorioproyectos | 3adc7de896738a911b01bba2b17d0a5b82529792 | 6d3dad3c8b4aaab17aa2562376013f9663f494e5 |
refs/heads/master | <repo_name>jomal123a/fir_filter<file_sep>/main.c
/*
* main.c
*/
#include "fir.h"
#define BUFFER_LEN 1024
#define COEFF_NUM 242
int out_tab[BUFFER_LEN];
int kronecker_delta[BUFFER_LEN];
int x[COEFF_NUM];
const int w[COEFF_NUM] = {0, 0, 0, 0, 0, 1, 1,-1,-1,-1, 0, 1, 2, 2, 1, 0,-2,-3,-3, 0,
3, 5, 5, 2,-2,-6,-8,-5, 1, 7,11, 9, 2,-7,-14,-14,-7, 5,16,20,
14,-1,-17,-26,-23,-7,15,31,33,18,-9,-34,-44,-32,-2,33,54,49,18,-27,
-62,-68,-40,13,64,87,67, 9,-59,-103,-97,-41,43,112,130,81,-14,-112,-161,-130,
-29,97,185,185,88,-65,-198,-241,-163, 9,193,296,254,75,-163,-342,-361,-192,98,372,
483,353,18,-374,-625,-579,-214,331,799,924,567,-196,-1060,-1587,-1374,-226,1730,4057,6129,7348,
7348,6129,4057,1730,-226,-1374,-1587,-1060,-196,567,924,799,331,-214,-579,-625,-374,18,353,483,
372,98,-192,-361,-342,-163,75,254,296,193, 9,-163,-241,-198,-65,88,185,185,97,-29,
-130,-161,-112,-14,81,130,112,43,-41,-97,-103,-59, 9,67,87,64,13,-40,-68,-62,
-27,18,49,54,33,-2,-32,-44,-34,-9,18,33,31,15,-7,-23,-26,-17,-1,14,
20,16, 5,-7,-14,-14,-7, 2, 9,11, 7, 1,-5,-8,-6,-2, 2, 5, 5, 3,
0,-3,-3,-2, 0, 1, 2, 2, 1, 0,-1,-1,-1, 0, 1, 1, 0, 0, 0, 0, 0};
void create_buffer(int x[], int N);
void create_kronecker(int tab[], int N);
int main(void) {
// Create buffer filled with zeros
create_buffer(x, COEFF_NUM);
// Create Kronecker delta
create_kronecker(kronecker_delta, BUFFER_LEN);
// Loop that simulates sample acquisition and filtering
int samp_in;
int samp_out;
int i;
for(i = 0; i < BUFFER_LEN; ++i) {
samp_in = kronecker_delta[i];
samp_out = fir(samp_in, w, COEFF_NUM, x);
out_tab[i] = samp_out;
}
return 0;
}
void create_kronecker(int tab[], int N) {
create_buffer(tab, N);
tab[0] = 32767;
}
void create_buffer(int x[], int N) {
int i;
for (i = 0; i < N; ++i) {
x[i] = 0;
}
}
<file_sep>/fir.h
/*
* fir.h
*
* Created on: 23 may 2020
* Author: <NAME>
*
*/
#ifndef FIR_H_
#define FIR_H_
/* fir filter
*
* INPUT:
* xin - input sample
* w - filter coefficients array
* N - number of filter coefficients
* x - sample buffer array
*
* OUTPUT:
* y - current output value of a filter
*/
int fir(int xin, const int w[], int N, int x[]);
#endif /* FIR_H_ */
<file_sep>/fir.c
/*
* fir.c
*
* Created on: 23 may 2020
* Author: <NAME>
*
*/
#include "fir.h"
int* buffr_ptr;
int fir(int xin, const int w[], int N, int x[]) {
// If buffer is empty or not loaded return 0
static int loaded = 0;
static int n = 0;
long y = 0;
int i;
int j;
if (!loaded) {
x[n] = xin;
buffr_ptr = &x[n];
++n;
if (n >= N) loaded = 1;
j = N - n;
}
else {
// Else return filtered output value
if (n >= N) {
buffr_ptr = &x[0];
n = 0;
} else {
++buffr_ptr;
++n;
}
*buffr_ptr = xin;
j = N - n - 1 ;
}
// Initialize counter with start value n
for (i = 0; i < N; ++i, ++j) {
y += w[i] * (long) x[(N - 1) - (j % N)];
}
return (y >> 15);
}
| d9536706f5b9337f9638b2a91ca62c6e2d895e5c | [
"C"
]
| 3 | C | jomal123a/fir_filter | 79fe3e136fab412ce568b52eeb15b5b7700927e7 | f90a2236272cb2541ce170453303311e3551851e |
refs/heads/master | <repo_name>M-a-c/Vis1<file_sep>/EmailTimeChart.js
var d;
let findHourTime = (time) => {
time = String(time);
var matches = time.match(/(\d+):(\d+)/);
var hourTime = 0;
hourTime += parseInt(matches[0],10);
var timeMinuite = parseInt(matches[1],10);
hourTime += timeMinuite/60;
if(time.toLowerCase().includes("pm")){
hourTime += 12;
}
return hourTime;
};
let findTimeAsZone = (time) => {
var roundedTime = round(time,0);
if(roundedTime>12){
roundedTime=roundedTime%12;
return String(roundedTime) + "PM";
}
else{
return String(roundedTime) + "AM";
}
}
//Credit to <NAME> - Sep 8 '11 at 4:06
//His code was quicker than what I could come up with so this function is verbatim not mine
//http://stackoverflow.com/questions/7342957/how-do-you-round-to-1-decimal-place-in-javascript
let round = (value, precision) => {
var multiplier = Math.pow(10, precision || 0);
return Math.round(value * multiplier) / multiplier;
}
let EmailTimeChart = () => {
var formatTime = d3.timeFormat("%B %d");
var uniqueDates = [];
var allRows =[];
var data = []
d3.text("emailData.csv", (emailData) => {
//All Data cleaning and parsing.
allRows = d3.csvParseRows(emailData)
.slice(1, d3.csvParseRows(emailData).lenght);
let dates = allRows.map((emailData) => {return formatTime(new Date(emailData[0]));});
uniqueDates = Array.from(new Set(dates));
let times = allRows.map((emailData) => {return findHourTime(emailData[1]);});
d = uniqueDates.map((uniqueDate) => {
var count = 0;
var totalTime = 0;
var color = [0,0,0];
var typeOfEmail = [0,0,0,0];
allRows.map((emailData) => {
if (formatTime(new Date(emailData[0])) == uniqueDate) {
count++;
}
});
allRows.map((emailData) => {
if (formatTime(new Date(emailData[0])) == uniqueDate) {
totalTime += findHourTime(emailData[1]);
}
});
allRows.map((emailData) => {
if (formatTime(new Date(emailData[0])) == uniqueDate) {
if(emailData[5]==="answer"){
color[0]+=0;
color[1]+=255;//green
color[2]+=0;
typeOfEmail[0]+=1;
}
else if(emailData[5]==="statement"){
color[0]+=0;
color[1]+=0;
color[2]+=255;//blue
typeOfEmail[1]+=1;
}
else if(emailData[5]==="question"){
color[0]+=255;//red
color[1]+=0;
color[2]+=0;
typeOfEmail[2]+=1;
}
else{
color[0]+=0;
color[1]+=0;
color[2]+=0;
typeOfEmail[3]+=1;
}
}
});
color[0]/=count;
color[1]/=count;
color[2]/=count;
totalTime = totalTime/count;
var returnVariable = [uniqueDate,totalTime,count,color,typeOfEmail];
return returnVariable;
});
data = d;
d = data;
var tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("background-color","white")
.style("padding","10px")
.style("border-radius", "25px")
.style("visibility", "hidden")
.text("a simple tooltip");
uniqueDates.push(" ");
uniqueDates.unshift(0);
let margin = {top: 50, right: 50, bottom: 150, left: 50};
let width = 960 - margin.left - margin.right;
let height = 500 - margin.top - margin.bottom;
let x = d3.scalePoint()
.domain(uniqueDates)
.range([ 0, width ]);
let y = d3.scaleLinear()
.domain([0, d3.max(data, (d) => {
return 24;
})])
.range([height, 0]);
let chart = d3.select('#EmailTimeChart')
.append('svg')
.attr('preserveAspectRatio',"xMidYMid meet")
.attr('viewBox',`${0} ${0} ${width + margin.right + margin.left} ${height + margin.top + margin.bottom}`)
.attr('class', 'chart')
let EmailGraph = chart.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr('width', width)
.attr('height', height)
.attr('class', 'EmailGraph')
// all x axis code
let xAxis = d3.axisBottom()
.scale(x);
EmailGraph.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'EmailGraph axis date')
.call(xAxis)
.selectAll("text")
.attr("y", 0)
.attr("x", 9)
.attr("dy", ".35em")
.attr("transform", "rotate(90)")
.style("text-anchor", "start");
EmailGraph.append("text")
.attr("class", "x label")
.attr("text-anchor", "end")
.attr("x", width)
.attr("y", height + 30)
.text("Date");
// all y axis code
let yAxis = d3.axisLeft()
.scale(y)
.ticks(12);
EmailGraph.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'EmailGraph axis date')
.call(yAxis);
EmailGraph.append("text")
.attr("class", "y label")
.attr("text-anchor", "end")
.attr("transform", "rotate(-90)")
.attr("x", 0)
.attr("y", -30)
.text("Time of Day");
//All displayed data code
let g = EmailGraph.append("g");
g.selectAll("scatter-dots")
.data(data)
.enter().append("circle")
.attr("cx", (d,i) => { return x(d[0]); } )
.attr("cy", (d) => { return y(d[1]); } )
.attr("r", (d) => { return d[2]; } )
.attr('fill', (d) => {return d3.rgb(d[3][0], d[3][1], d[3][2]);})
.on("mouseover", (d) => {return tooltip.style("visibility", "visible")
.html(`<p>Number of Emails: ${d[2]}</p>
<p>Average time of email: ${findTimeAsZone(d[1])}</p>
<p style="color:green;">answers: ${d[4][0]} (${round((d[4][0]/d[2])*100,1)}%)</p>
<p style="color:blue;">statements: ${d[4][1]} (${round((d[4][1]/d[2])*100,1)}%)</p>
<p style="color:red;">questions: ${d[4][2]} (${round((d[4][2]/d[2])*100,1)}%)</p>
<p style="color:black;">other: ${d[4][3]} (${round((d[4][3]/d[2])*100,1)}%)</p>`);
})
.on("mousemove", (d) => {return tooltip.style("top", (d3.event.pageY-10)+"px")
.style("left",(d3.event.pageX+10)+"px");
})
.on("mouseout", () => {return tooltip.style("visibility", "hidden");});
});
};
<file_sep>/README.txt
Info:
-----------------------------------------------------------------------------------------------------------------------
Copyright <NAME> 9/13/2016
I used D3 v4 for this, python server to host everything locally,
All libs are downloaded.
index.html is the primary file.
* I only tested this in Chrome *
Sketches are in the sketch folder. Along with text that was submitted in the first write up.
Aside:
-----------------------------------------------------------------------------------------------------------------------
Additionally, v3 stuff is different enough from v4, that I did not get the hang of a lot of this till 3 nights of
working with it.
PS, thanks for having a first assignment that wasn't group work, this has been an eye opener for what kind of work we
will be doing. Some of this is a lot harder than I thought it would be (mostly versions and drawing your own shapes
to the screen is annoying).
| 2d22f168bf2cf2548f6ef0b067e20f2832794d97 | [
"JavaScript",
"Text"
]
| 2 | JavaScript | M-a-c/Vis1 | 264a1b72aa97df6fef1d2dbd42c29f9205fe76b8 | 805cdbbc06be2791134ec983fd0f50937324abbc |
refs/heads/master | <repo_name>thesunauto/sunweb<file_sep>/src/main/java/vn/automation/sunweb/commons/CategoryResponse.java
package vn.automation.sunweb.commons;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class CategoryResponse {
private String id;
private String title;
private String image;
private String detail;
private String parentTitle;
private String idParent;
private Boolean hasParent;
private String isShowIndex;
private Boolean isMax;
}
<file_sep>/src/main/java/vn/automation/sunweb/validator/PostValidator.java
package vn.automation.sunweb.validator;
import org.thymeleaf.util.StringUtils;
import vn.automation.sunweb.entity.Post;
import java.util.Optional;
public class PostValidator {
public boolean isValid(Post post){
return Optional.ofNullable(post).filter(post1 -> !StringUtils.isEmpty(post.getTitle())).filter(post1 -> !StringUtils.isEmpty(post1.getContext())).isPresent();
}
}
<file_sep>/src/main/java/vn/automation/sunweb/controller/MainRestController.java
package vn.automation.sunweb.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import vn.automation.sunweb.commons.CategoryResponse;
import vn.automation.sunweb.commons.PostResponse;
import vn.automation.sunweb.entity.Category;
import vn.automation.sunweb.entity.Post;
import vn.automation.sunweb.service.CategoryService;
import vn.automation.sunweb.service.PostService;
import vn.automation.sunweb.service.UserService;
import vn.automation.sunweb.storage.StorageService;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.nio.file.Path;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@RequestMapping("/api")
@RestController
public class MainRestController {
@Autowired
private UserService userService;
@Autowired
private CategoryService categoryService;
@Autowired
private PostService postService;
@Autowired
private StorageService storageService;
@PostMapping("/getlistpostbycategory-{page}-{limit}")
public ResponseEntity getlistPost(@PathVariable(value = "page") Integer page, @PathVariable(value = "limit") Integer limit, @RequestParam(value = "idcategory") String idcategory) {
List<PostResponse> postResponses = new ArrayList<>();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
postService.findAll(page, limit, idcategory).forEach(post -> {
Path html = storageService.load(post.getContext());
BufferedReader bufferedReader = null;
String context = "";
try {
bufferedReader = new BufferedReader(new FileReader(html.toFile()));
context = bufferedReader.lines().collect(Collectors.joining());
} catch (Exception e) {
context = "";
}
if(post.getIspulic()){
postResponses.add(PostResponse.builder()
.idCategory(post.getCategory().getId())
.id(post.getId())
.title(post.getTitle())
.metatitle(post.getMetatitle())
.isshowindex(post.getIsshowindex())
.ispublic(post.getIspulic())
.dateCreated(post.getDatecreated().format(dateTimeFormatter))
.dateUpdated(post.getDateupdated().format(dateTimeFormatter))
.datepuliced(post.getDatepuliced().format(dateTimeFormatter))
.image(post.getImage())
.content(context)
.user(post.getUser().getName())
.build());}
});
return ResponseEntity.ok().body(postResponses);
}
@PostMapping("/getpagenumbycategory")
public ResponseEntity getPageNum(@RequestParam(value = "idcategory") String idcategory) {
return ResponseEntity.ok().body(postService.findAll(idcategory).size() / 10 + 1);
}
@PostMapping("/getTop3PostNew")
public ResponseEntity getTop3PostNew() {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
List<PostResponse> postResponses = new ArrayList<>();
postService.getTop3new().forEach(post -> {
postResponses.add(PostResponse.builder()
.id(post.getId())
.idCategory(post.getCategory().getId())
.title(post.getTitle())
.metatitle(post.getMetatitle())
.isshowindex(post.getIsshowindex())
.ispublic(post.getIsshowindex())
.dateCreated(post.getDatecreated().format(dateTimeFormatter))
.dateUpdated(post.getDateupdated().format(dateTimeFormatter))
.datepuliced(post.getDatepuliced().format(dateTimeFormatter))
.image(post.getImage())
.user(post.getUser().getName())
.build());
});
return ResponseEntity.ok().body(postResponses);
}
@PostMapping("/getTreeCategory")
public ResponseEntity getTreeCategory(@RequestParam(value = "idcategory") String idcategory) {
List<String> caTr = new ArrayList<>();
Category category = categoryService.getOne(idcategory);
caTr.add(category.getTitle());
if (category.getCategory() == null) {
Collections.reverse(caTr);
return ResponseEntity.ok().body(caTr);
}else{
caTr.add(category.getCategory().getTitle());
if(category.getCategory().getCategory()==null){ Collections.reverse(caTr);
return ResponseEntity.ok().body(caTr);
}else{
caTr.add(category.getCategory().getCategory().getTitle());
if(category.getCategory().getCategory().getCategory()==null){ Collections.reverse(caTr);
return ResponseEntity.ok().body(caTr);
}else{
caTr.add(category.getCategory().getCategory().getCategory().getTitle());
if(category.getCategory().getCategory().getCategory().getCategory()==null){ Collections.reverse(caTr);
return ResponseEntity.ok().body(caTr);
}else{
caTr.add(category.getCategory().getCategory().getCategory().getCategory().getTitle());
if(category.getCategory().getCategory().getCategory().getCategory().getCategory()==null){ Collections.reverse(caTr);
return ResponseEntity.ok().body(caTr);
}else{
return ResponseEntity.ok().body(null);
}
}
}
}
}
}
@PostMapping("/getPost/{id}")
public ResponseEntity getPost(@PathVariable Integer id){
Post post = postService.findById(id);
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
Path html = storageService.load(post.getContext());
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(html.toFile()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String context = bufferedReader.lines().collect(Collectors.joining());
return ResponseEntity.ok().body(PostResponse.builder()
.user(post.getUser().getName())
.image(post.getImage())
.datepuliced(post.getDatepuliced().format(dateTimeFormatter))
.dateUpdated(post.getDateupdated().format(dateTimeFormatter))
.dateCreated(post.getDatecreated().format(dateTimeFormatter))
.content(context)
.ispublic(post.getIspulic())
.isshowindex(post.getIsshowindex())
.metatitle(post.getMetatitle())
.title(post.getTitle())
.idCategory(post.getCategory().getTitle())
.id(post.getId())
.build());
}
@PostMapping("/getCategoryShowingIndex")
public ResponseEntity getCategoryShowingIndex(){
List<CategoryResponse> responseList = new ArrayList<>();
categoryService.getCategoryIndex().forEach(category -> {
responseList.add(CategoryResponse.builder()
.isShowIndex(category.getIsshowindex()?"on":"off")
.id(category.getId())
.detail(category.getDetail())
.image(category.getImage())
.title(category.getTitle())
.hasParent(category.getCategory()!=null)
.idParent(category.getCategory().getId())
.parentTitle(category.getCategory().getTitle())
.build());
});
return ResponseEntity.ok().body(responseList);
}
@PostMapping("/getPostShowingIndex")
public ResponseEntity getPostShowingIndex(){
List<PostResponse> postResponses = new ArrayList<>();
postService.getPostShowIndex().forEach(post -> {
postResponses.add(PostResponse.builder()
.id(post.getId())
.idCategory(post.getCategory().getId())
.title(post.getTitle())
.metatitle(post.getMetatitle())
.isshowindex(post.getIsshowindex())
.ispublic(post.getIsshowindex())
.dateCreated(post.getDatecreated().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")))
.image(post.getImage())
.user(post.getUser().getName())
.titleCategory(post.getCategory().getTitle())
.build());
});
return ResponseEntity.ok().body(postResponses);
}
}
<file_sep>/src/main/java/vn/automation/sunweb/service/PostService.java
package vn.automation.sunweb.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import vn.automation.sunweb.entity.Category;
import vn.automation.sunweb.entity.Post;
import vn.automation.sunweb.repository.CategoryRepository;
import vn.automation.sunweb.repository.PostRepository;
import vn.automation.sunweb.validator.PostValidator;
import java.util.List;
import java.util.Optional;
@Service
public class PostService {
@Autowired private PostRepository postRepository;
@Autowired private PostValidator postValidator;
@Autowired private CategoryRepository categoryRepository;
public List<Post> findAll(Integer limit){
return Optional.ofNullable(limit).map(value->postRepository.findAll(PageRequest.of(0,limit)).getContent()).orElseGet(()->postRepository.findAll());
}
public List<Post> findAll(){
return postRepository.findAllByIsdeleted(false);
}
public List<Post> findAll(String idcategory){
return postRepository.findAllByCategoryAndIsdeleted(categoryRepository.getOne(idcategory),false);
}
public List<Post> findAll(Integer page, Integer limit){
return postRepository.findAllByIsdeleted(PageRequest.of(page,limit),false).getContent();
}
public List<Post> findAll(Integer page, Integer limit, String idCategory){
return postRepository.findAllByIsdeletedAndCategory(PageRequest.of(page,limit),false,categoryRepository.getOne(idCategory)).getContent();
}
public Post findById(Integer id){
return Optional.ofNullable(id).map(value -> postRepository.findById(id).get()).orElseGet(()->postRepository.findById(1).get());
}
public Post addPost(Post post){
if(postValidator.isValid(post)){
return postRepository.save(post);
}
return null;
}
public Post saveFileContextPost(Integer idPost){
Post post = postRepository.findById(idPost).get();
post.setContext(idPost+".html");
return postRepository.save(post);
}
public Post deletePost(Integer id){
Post post = findById(id);
post.setIsdeleted(true);
return postRepository.save(post);
}
public List<Post> getTop3new(){
return postRepository.findTop3ByOrderByDatecreatedDesc();
}
public List<Post> getTop3newIndex(){
return postRepository.findTop3ByIsshowindexAndIspulicAndIsdeletedOrderByDatecreatedDesc(true,true,false);
}
public List<Post> getPostShowIndex(){
return postRepository.findAllByIsshowindexAndIspulicAndIsdeletedOrderByDatecreatedDesc(true,true,false);
}
}
<file_sep>/src/test/java/vn/automation/sunweb/SunwebApplicationTests.java
package vn.automation.sunweb;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import vn.automation.sunweb.entity.Category;
import vn.automation.sunweb.entity.Post;
import vn.automation.sunweb.entity.User;
import vn.automation.sunweb.repository.CategoryRepository;
import vn.automation.sunweb.repository.PostRepository;
import vn.automation.sunweb.repository.UserRepository;
import vn.automation.sunweb.service.CategoryService;
import vn.automation.sunweb.service.PostService;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@SpringBootTest
class SunwebApplicationTests {
@Autowired private PostRepository postRepository;
@Autowired private CategoryRepository categoryRepository;
@Autowired private UserRepository userRepository;
@Autowired private CategoryService categoryService;
@Autowired private PostService postService;
@Test
void contextLoads() {
postService.getTop3new().forEach(post -> {
System.out.println(post);
});
}
}
<file_sep>/src/main/java/vn/automation/sunweb/entity/User.java
package vn.automation.sunweb.entity;
import lombok.*;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;
@Entity
@Table(name = "user")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
@Id
@Column(name = "username", nullable = false)
private String username;
@Column(name = "datecreated", nullable = false)
private LocalDateTime datecreated;
@Column(name = "email")
private String email;
@Column(name = "isdelete", nullable = false)
private Integer isdelete;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "password", nullable = false)
private String password;
@Column(name = "phone")
private String phone;
@Column(name = "role", nullable = false)
private String role;
@OneToMany(mappedBy = "user",cascade = CascadeType.ALL)
@EqualsAndHashCode.Exclude
@ToString.Exclude
private Collection<Post> posts;
@OneToMany(mappedBy = "user",cascade = CascadeType.ALL)
@EqualsAndHashCode.Exclude
@ToString.Exclude
private Collection<Category> categories;
}
<file_sep>/src/main/java/vn/automation/sunweb/commons/PostResponse.java
package vn.automation.sunweb.commons;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class PostResponse {
private String idCategory;
private String titleCategory;
private Integer id;
private String title;
private String metatitle;
private Boolean isshowindex;
private Boolean ispublic;
private String dateCreated;
private String dateUpdated;
private String datepuliced;
private String image;
private String content;
private String user;
}
<file_sep>/src/main/java/vn/automation/sunweb/service/CategoryService.java
package vn.automation.sunweb.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import vn.automation.sunweb.commons.CategoryResponse;
import vn.automation.sunweb.commons.UserResponse;
import vn.automation.sunweb.entity.Category;
import vn.automation.sunweb.entity.User;
import vn.automation.sunweb.repository.CategoryRepository;
import vn.automation.sunweb.repository.UserRepository;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
@Service
public class CategoryService {
@Autowired private CategoryRepository categoryRepository;
@Autowired private UserRepository userRepository;
public List<Category> findAll(Integer limit){
return Optional.ofNullable(limit).map(value -> categoryRepository.findAll(PageRequest.of(0,limit)).getContent()).orElseGet(()->categoryRepository.findAll());
}
public List<Category> findByIdparent(Category category){
return Optional.ofNullable(category).map(value->categoryRepository.findByCategoryAndIsdeleted(value,false)).orElseGet(()->categoryRepository.findByCategoryAndIsdeleted(null,false));
}
public Collection<Category> findByIdparent(String category){
return Optional.ofNullable(category).map(value->categoryRepository.findByCategoryAndIsdeleted(categoryRepository.getOne(value),false)).orElseGet(()->categoryRepository.findByCategoryAndIsdeleted(null,false));
}
public Category getOne(String id){
return categoryRepository.findById(id).orElse(new Category());
}
public boolean save(CategoryResponse categoryResponse){
try{
Category category = new Category();
category.setId(categoryResponse.getId());
category.setTitle(categoryResponse.getTitle());
category.setImage(categoryResponse.getImage());
category.setDetail(categoryResponse.getDetail());
category.setDatecreated(LocalDateTime.now());
category.setCategory(categoryRepository.getOne(categoryResponse.getIdParent()));
category.setIsdeleted(false);
category.setUser(userRepository.findById("admin").get());
category.setIsshowindex(categoryResponse.getIsShowIndex()!=null);
System.out.println(category);
categoryRepository.save(category);
return true;
}catch (Exception e){}
return false;
}
public boolean delete(String id){
Category category = getOne(id);
category.setIsdeleted(true);
try{categoryRepository.save(category); return true;}catch (Exception e){e.printStackTrace();}
return false;
}
public boolean edit(CategoryResponse categoryResponse) {
try {
Category category = getOne(categoryResponse.getId());
category.setTitle(categoryResponse.getTitle());
category.setImage(categoryResponse.getImage());
category.setDetail(categoryResponse.getDetail());
category.setIsshowindex(categoryResponse.getIsShowIndex()!=null);
categoryRepository.save(category);
return true;
}catch (Exception e){
System.out.println("edit category");
e.printStackTrace();
}
return false;
}
public List<Category> getCategoryIndex(){
return categoryRepository.findAllByIsshowindexAndIsdeleted(true,false);
}
}
| 1bbc6f10b9a21f1ffbb5e8a33262e51a209aecc3 | [
"Java"
]
| 8 | Java | thesunauto/sunweb | 2b542f931f20005656d99d8b3be92f85bfa40bbf | bf3860eeae410935cd9e9197c5c5e3bfe5093e28 |
refs/heads/master | <repo_name>SudharchithSonty/OperatingSystems<file_sep>/Debug/kern/compile/ASST2/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../kern/compile/ASST2/.depend.__printf.c \
../kern/compile/ASST2/.depend.adddi3.c \
../kern/compile/ASST2/.depend.anddi3.c \
../kern/compile/ASST2/.depend.array.c \
../kern/compile/ASST2/.depend.arraytest.c \
../kern/compile/ASST2/.depend.ashldi3.c \
../kern/compile/ASST2/.depend.ashrdi3.c \
../kern/compile/ASST2/.depend.atoi.c \
../kern/compile/ASST2/.depend.autoconf.c \
../kern/compile/ASST2/.depend.beep.c \
../kern/compile/ASST2/.depend.beep_ltimer.c \
../kern/compile/ASST2/.depend.bitmap.c \
../kern/compile/ASST2/.depend.bitmaptest.c \
../kern/compile/ASST2/.depend.bswap.c \
../kern/compile/ASST2/.depend.bzero.c \
../kern/compile/ASST2/.depend.clock.c \
../kern/compile/ASST2/.depend.cmpdi2.c \
../kern/compile/ASST2/.depend.con_lser.c \
../kern/compile/ASST2/.depend.console.c \
../kern/compile/ASST2/.depend.copyinout.c \
../kern/compile/ASST2/.depend.cpu.c \
../kern/compile/ASST2/.depend.device.c \
../kern/compile/ASST2/.depend.devnull.c \
../kern/compile/ASST2/.depend.divdi3.c \
../kern/compile/ASST2/.depend.dumbvm.c \
../kern/compile/ASST2/.depend.emu.c \
../kern/compile/ASST2/.depend.emu_att.c \
../kern/compile/ASST2/.depend.file_syscalls.c \
../kern/compile/ASST2/.depend.fstest.c \
../kern/compile/ASST2/.depend.hmacunit.c \
../kern/compile/ASST2/.depend.iordi3.c \
../kern/compile/ASST2/.depend.kgets.c \
../kern/compile/ASST2/.depend.kmalloc.c \
../kern/compile/ASST2/.depend.kmalloctest.c \
../kern/compile/ASST2/.depend.kprintf.c \
../kern/compile/ASST2/.depend.lamebus.c \
../kern/compile/ASST2/.depend.lamebus_machdep.c \
../kern/compile/ASST2/.depend.lhd.c \
../kern/compile/ASST2/.depend.lhd_att.c \
../kern/compile/ASST2/.depend.lib.c \
../kern/compile/ASST2/.depend.loadelf.c \
../kern/compile/ASST2/.depend.lrandom.c \
../kern/compile/ASST2/.depend.lrandom_att.c \
../kern/compile/ASST2/.depend.lser.c \
../kern/compile/ASST2/.depend.lser_att.c \
../kern/compile/ASST2/.depend.lshldi3.c \
../kern/compile/ASST2/.depend.lshrdi3.c \
../kern/compile/ASST2/.depend.ltimer.c \
../kern/compile/ASST2/.depend.ltimer_att.c \
../kern/compile/ASST2/.depend.ltrace.c \
../kern/compile/ASST2/.depend.ltrace_att.c \
../kern/compile/ASST2/.depend.main.c \
../kern/compile/ASST2/.depend.memcpy.c \
../kern/compile/ASST2/.depend.memmove.c \
../kern/compile/ASST2/.depend.memset.c \
../kern/compile/ASST2/.depend.menu.c \
../kern/compile/ASST2/.depend.misc.c \
../kern/compile/ASST2/.depend.moddi3.c \
../kern/compile/ASST2/.depend.muldi3.c \
../kern/compile/ASST2/.depend.negdi2.c \
../kern/compile/ASST2/.depend.notdi2.c \
../kern/compile/ASST2/.depend.proc.c \
../kern/compile/ASST2/.depend.proc_syscalls.c \
../kern/compile/ASST2/.depend.qdivrem.c \
../kern/compile/ASST2/.depend.ram.c \
../kern/compile/ASST2/.depend.random.c \
../kern/compile/ASST2/.depend.random_lrandom.c \
../kern/compile/ASST2/.depend.rtclock.c \
../kern/compile/ASST2/.depend.rtclock_ltimer.c \
../kern/compile/ASST2/.depend.runprogram.c \
../kern/compile/ASST2/.depend.rwtest.c \
../kern/compile/ASST2/.depend.secure.c \
../kern/compile/ASST2/.depend.semfs_fsops.c \
../kern/compile/ASST2/.depend.semfs_obj.c \
../kern/compile/ASST2/.depend.semfs_vnops.c \
../kern/compile/ASST2/.depend.semunit.c \
../kern/compile/ASST2/.depend.sfs_balloc.c \
../kern/compile/ASST2/.depend.sfs_bmap.c \
../kern/compile/ASST2/.depend.sfs_dir.c \
../kern/compile/ASST2/.depend.sfs_fsops.c \
../kern/compile/ASST2/.depend.sfs_inode.c \
../kern/compile/ASST2/.depend.sfs_io.c \
../kern/compile/ASST2/.depend.sfs_vnops.c \
../kern/compile/ASST2/.depend.sha256.c \
../kern/compile/ASST2/.depend.snprintf.c \
../kern/compile/ASST2/.depend.spinlock.c \
../kern/compile/ASST2/.depend.spl.c \
../kern/compile/ASST2/.depend.strcat.c \
../kern/compile/ASST2/.depend.strchr.c \
../kern/compile/ASST2/.depend.strcmp.c \
../kern/compile/ASST2/.depend.strcpy.c \
../kern/compile/ASST2/.depend.strlen.c \
../kern/compile/ASST2/.depend.strrchr.c \
../kern/compile/ASST2/.depend.strtok_r.c \
../kern/compile/ASST2/.depend.subdi3.c \
../kern/compile/ASST2/.depend.switchframe.c \
../kern/compile/ASST2/.depend.synch.c \
../kern/compile/ASST2/.depend.synchtest.c \
../kern/compile/ASST2/.depend.syscall.c \
../kern/compile/ASST2/.depend.test161.c \
../kern/compile/ASST2/.depend.thread.c \
../kern/compile/ASST2/.depend.thread_machdep.c \
../kern/compile/ASST2/.depend.threadlist.c \
../kern/compile/ASST2/.depend.threadlisttest.c \
../kern/compile/ASST2/.depend.threadtest.c \
../kern/compile/ASST2/.depend.time.c \
../kern/compile/ASST2/.depend.time_syscalls.c \
../kern/compile/ASST2/.depend.trap.c \
../kern/compile/ASST2/.depend.tt3.c \
../kern/compile/ASST2/.depend.ucmpdi2.c \
../kern/compile/ASST2/.depend.udivdi3.c \
../kern/compile/ASST2/.depend.uio.c \
../kern/compile/ASST2/.depend.umoddi3.c \
../kern/compile/ASST2/.depend.vfscwd.c \
../kern/compile/ASST2/.depend.vfsfail.c \
../kern/compile/ASST2/.depend.vfslist.c \
../kern/compile/ASST2/.depend.vfslookup.c \
../kern/compile/ASST2/.depend.vfspath.c \
../kern/compile/ASST2/.depend.vnode.c \
../kern/compile/ASST2/.depend.xordi3.c \
../kern/compile/ASST2/autoconf.c \
../kern/compile/ASST2/vers.c
O_SRCS += \
../kern/compile/ASST2/__printf.o \
../kern/compile/ASST2/adddi3.o \
../kern/compile/ASST2/anddi3.o \
../kern/compile/ASST2/array.o \
../kern/compile/ASST2/arraytest.o \
../kern/compile/ASST2/ashldi3.o \
../kern/compile/ASST2/ashrdi3.o \
../kern/compile/ASST2/atoi.o \
../kern/compile/ASST2/autoconf.o \
../kern/compile/ASST2/beep.o \
../kern/compile/ASST2/beep_ltimer.o \
../kern/compile/ASST2/bitmap.o \
../kern/compile/ASST2/bitmaptest.o \
../kern/compile/ASST2/bswap.o \
../kern/compile/ASST2/bzero.o \
../kern/compile/ASST2/cache-mips161.o \
../kern/compile/ASST2/clock.o \
../kern/compile/ASST2/cmpdi2.o \
../kern/compile/ASST2/con_lser.o \
../kern/compile/ASST2/console.o \
../kern/compile/ASST2/copyinout.o \
../kern/compile/ASST2/cpu.o \
../kern/compile/ASST2/device.o \
../kern/compile/ASST2/devnull.o \
../kern/compile/ASST2/divdi3.o \
../kern/compile/ASST2/dumbvm.o \
../kern/compile/ASST2/emu.o \
../kern/compile/ASST2/emu_att.o \
../kern/compile/ASST2/exception-mips1.o \
../kern/compile/ASST2/file_syscalls.o \
../kern/compile/ASST2/fstest.o \
../kern/compile/ASST2/hmacunit.o \
../kern/compile/ASST2/iordi3.o \
../kern/compile/ASST2/kgets.o \
../kern/compile/ASST2/kmalloc.o \
../kern/compile/ASST2/kmalloctest.o \
../kern/compile/ASST2/kprintf.o \
../kern/compile/ASST2/lamebus.o \
../kern/compile/ASST2/lamebus_machdep.o \
../kern/compile/ASST2/lhd.o \
../kern/compile/ASST2/lhd_att.o \
../kern/compile/ASST2/lib.o \
../kern/compile/ASST2/loadelf.o \
../kern/compile/ASST2/lrandom.o \
../kern/compile/ASST2/lrandom_att.o \
../kern/compile/ASST2/lser.o \
../kern/compile/ASST2/lser_att.o \
../kern/compile/ASST2/lshldi3.o \
../kern/compile/ASST2/lshrdi3.o \
../kern/compile/ASST2/ltimer.o \
../kern/compile/ASST2/ltimer_att.o \
../kern/compile/ASST2/ltrace.o \
../kern/compile/ASST2/ltrace_att.o \
../kern/compile/ASST2/main.o \
../kern/compile/ASST2/memcpy.o \
../kern/compile/ASST2/memmove.o \
../kern/compile/ASST2/memset.o \
../kern/compile/ASST2/menu.o \
../kern/compile/ASST2/misc.o \
../kern/compile/ASST2/moddi3.o \
../kern/compile/ASST2/muldi3.o \
../kern/compile/ASST2/negdi2.o \
../kern/compile/ASST2/notdi2.o \
../kern/compile/ASST2/proc.o \
../kern/compile/ASST2/proc_syscalls.o \
../kern/compile/ASST2/qdivrem.o \
../kern/compile/ASST2/ram.o \
../kern/compile/ASST2/random.o \
../kern/compile/ASST2/random_lrandom.o \
../kern/compile/ASST2/rtclock.o \
../kern/compile/ASST2/rtclock_ltimer.o \
../kern/compile/ASST2/runprogram.o \
../kern/compile/ASST2/rwtest.o \
../kern/compile/ASST2/secure.o \
../kern/compile/ASST2/semfs_fsops.o \
../kern/compile/ASST2/semfs_obj.o \
../kern/compile/ASST2/semfs_vnops.o \
../kern/compile/ASST2/semunit.o \
../kern/compile/ASST2/setjmp.o \
../kern/compile/ASST2/sfs_balloc.o \
../kern/compile/ASST2/sfs_bmap.o \
../kern/compile/ASST2/sfs_dir.o \
../kern/compile/ASST2/sfs_fsops.o \
../kern/compile/ASST2/sfs_inode.o \
../kern/compile/ASST2/sfs_io.o \
../kern/compile/ASST2/sfs_vnops.o \
../kern/compile/ASST2/sha256.o \
../kern/compile/ASST2/snprintf.o \
../kern/compile/ASST2/spinlock.o \
../kern/compile/ASST2/spl.o \
../kern/compile/ASST2/start.o \
../kern/compile/ASST2/strcat.o \
../kern/compile/ASST2/strchr.o \
../kern/compile/ASST2/strcmp.o \
../kern/compile/ASST2/strcpy.o \
../kern/compile/ASST2/strlen.o \
../kern/compile/ASST2/strrchr.o \
../kern/compile/ASST2/strtok_r.o \
../kern/compile/ASST2/subdi3.o \
../kern/compile/ASST2/switch.o \
../kern/compile/ASST2/switchframe.o \
../kern/compile/ASST2/synch.o \
../kern/compile/ASST2/synchtest.o \
../kern/compile/ASST2/syscall.o \
../kern/compile/ASST2/test161.o \
../kern/compile/ASST2/thread.o \
../kern/compile/ASST2/thread_machdep.o \
../kern/compile/ASST2/threadlist.o \
../kern/compile/ASST2/threadlisttest.o \
../kern/compile/ASST2/threadstart.o \
../kern/compile/ASST2/threadtest.o \
../kern/compile/ASST2/time.o \
../kern/compile/ASST2/time_syscalls.o \
../kern/compile/ASST2/tlb-mips161.o \
../kern/compile/ASST2/trap.o \
../kern/compile/ASST2/tt3.o \
../kern/compile/ASST2/ucmpdi2.o \
../kern/compile/ASST2/udivdi3.o \
../kern/compile/ASST2/uio.o \
../kern/compile/ASST2/umoddi3.o \
../kern/compile/ASST2/vers.o \
../kern/compile/ASST2/vfscwd.o \
../kern/compile/ASST2/vfsfail.o \
../kern/compile/ASST2/vfslist.o \
../kern/compile/ASST2/vfslookup.o \
../kern/compile/ASST2/vfspath.o \
../kern/compile/ASST2/vnode.o \
../kern/compile/ASST2/xordi3.o
S_UPPER_SRCS += \
../kern/compile/ASST2/.depend.cache-mips161.S \
../kern/compile/ASST2/.depend.exception-mips1.S \
../kern/compile/ASST2/.depend.setjmp.S \
../kern/compile/ASST2/.depend.start.S \
../kern/compile/ASST2/.depend.switch.S \
../kern/compile/ASST2/.depend.threadstart.S \
../kern/compile/ASST2/.depend.tlb-mips161.S
OBJS += \
./kern/compile/ASST2/.depend.__printf.o \
./kern/compile/ASST2/.depend.adddi3.o \
./kern/compile/ASST2/.depend.anddi3.o \
./kern/compile/ASST2/.depend.array.o \
./kern/compile/ASST2/.depend.arraytest.o \
./kern/compile/ASST2/.depend.ashldi3.o \
./kern/compile/ASST2/.depend.ashrdi3.o \
./kern/compile/ASST2/.depend.atoi.o \
./kern/compile/ASST2/.depend.autoconf.o \
./kern/compile/ASST2/.depend.beep.o \
./kern/compile/ASST2/.depend.beep_ltimer.o \
./kern/compile/ASST2/.depend.bitmap.o \
./kern/compile/ASST2/.depend.bitmaptest.o \
./kern/compile/ASST2/.depend.bswap.o \
./kern/compile/ASST2/.depend.bzero.o \
./kern/compile/ASST2/.depend.cache-mips161.o \
./kern/compile/ASST2/.depend.clock.o \
./kern/compile/ASST2/.depend.cmpdi2.o \
./kern/compile/ASST2/.depend.con_lser.o \
./kern/compile/ASST2/.depend.console.o \
./kern/compile/ASST2/.depend.copyinout.o \
./kern/compile/ASST2/.depend.cpu.o \
./kern/compile/ASST2/.depend.device.o \
./kern/compile/ASST2/.depend.devnull.o \
./kern/compile/ASST2/.depend.divdi3.o \
./kern/compile/ASST2/.depend.dumbvm.o \
./kern/compile/ASST2/.depend.emu.o \
./kern/compile/ASST2/.depend.emu_att.o \
./kern/compile/ASST2/.depend.exception-mips1.o \
./kern/compile/ASST2/.depend.file_syscalls.o \
./kern/compile/ASST2/.depend.fstest.o \
./kern/compile/ASST2/.depend.hmacunit.o \
./kern/compile/ASST2/.depend.iordi3.o \
./kern/compile/ASST2/.depend.kgets.o \
./kern/compile/ASST2/.depend.kmalloc.o \
./kern/compile/ASST2/.depend.kmalloctest.o \
./kern/compile/ASST2/.depend.kprintf.o \
./kern/compile/ASST2/.depend.lamebus.o \
./kern/compile/ASST2/.depend.lamebus_machdep.o \
./kern/compile/ASST2/.depend.lhd.o \
./kern/compile/ASST2/.depend.lhd_att.o \
./kern/compile/ASST2/.depend.lib.o \
./kern/compile/ASST2/.depend.loadelf.o \
./kern/compile/ASST2/.depend.lrandom.o \
./kern/compile/ASST2/.depend.lrandom_att.o \
./kern/compile/ASST2/.depend.lser.o \
./kern/compile/ASST2/.depend.lser_att.o \
./kern/compile/ASST2/.depend.lshldi3.o \
./kern/compile/ASST2/.depend.lshrdi3.o \
./kern/compile/ASST2/.depend.ltimer.o \
./kern/compile/ASST2/.depend.ltimer_att.o \
./kern/compile/ASST2/.depend.ltrace.o \
./kern/compile/ASST2/.depend.ltrace_att.o \
./kern/compile/ASST2/.depend.main.o \
./kern/compile/ASST2/.depend.memcpy.o \
./kern/compile/ASST2/.depend.memmove.o \
./kern/compile/ASST2/.depend.memset.o \
./kern/compile/ASST2/.depend.menu.o \
./kern/compile/ASST2/.depend.misc.o \
./kern/compile/ASST2/.depend.moddi3.o \
./kern/compile/ASST2/.depend.muldi3.o \
./kern/compile/ASST2/.depend.negdi2.o \
./kern/compile/ASST2/.depend.notdi2.o \
./kern/compile/ASST2/.depend.proc.o \
./kern/compile/ASST2/.depend.proc_syscalls.o \
./kern/compile/ASST2/.depend.qdivrem.o \
./kern/compile/ASST2/.depend.ram.o \
./kern/compile/ASST2/.depend.random.o \
./kern/compile/ASST2/.depend.random_lrandom.o \
./kern/compile/ASST2/.depend.rtclock.o \
./kern/compile/ASST2/.depend.rtclock_ltimer.o \
./kern/compile/ASST2/.depend.runprogram.o \
./kern/compile/ASST2/.depend.rwtest.o \
./kern/compile/ASST2/.depend.secure.o \
./kern/compile/ASST2/.depend.semfs_fsops.o \
./kern/compile/ASST2/.depend.semfs_obj.o \
./kern/compile/ASST2/.depend.semfs_vnops.o \
./kern/compile/ASST2/.depend.semunit.o \
./kern/compile/ASST2/.depend.setjmp.o \
./kern/compile/ASST2/.depend.sfs_balloc.o \
./kern/compile/ASST2/.depend.sfs_bmap.o \
./kern/compile/ASST2/.depend.sfs_dir.o \
./kern/compile/ASST2/.depend.sfs_fsops.o \
./kern/compile/ASST2/.depend.sfs_inode.o \
./kern/compile/ASST2/.depend.sfs_io.o \
./kern/compile/ASST2/.depend.sfs_vnops.o \
./kern/compile/ASST2/.depend.sha256.o \
./kern/compile/ASST2/.depend.snprintf.o \
./kern/compile/ASST2/.depend.spinlock.o \
./kern/compile/ASST2/.depend.spl.o \
./kern/compile/ASST2/.depend.start.o \
./kern/compile/ASST2/.depend.strcat.o \
./kern/compile/ASST2/.depend.strchr.o \
./kern/compile/ASST2/.depend.strcmp.o \
./kern/compile/ASST2/.depend.strcpy.o \
./kern/compile/ASST2/.depend.strlen.o \
./kern/compile/ASST2/.depend.strrchr.o \
./kern/compile/ASST2/.depend.strtok_r.o \
./kern/compile/ASST2/.depend.subdi3.o \
./kern/compile/ASST2/.depend.switch.o \
./kern/compile/ASST2/.depend.switchframe.o \
./kern/compile/ASST2/.depend.synch.o \
./kern/compile/ASST2/.depend.synchtest.o \
./kern/compile/ASST2/.depend.syscall.o \
./kern/compile/ASST2/.depend.test161.o \
./kern/compile/ASST2/.depend.thread.o \
./kern/compile/ASST2/.depend.thread_machdep.o \
./kern/compile/ASST2/.depend.threadlist.o \
./kern/compile/ASST2/.depend.threadlisttest.o \
./kern/compile/ASST2/.depend.threadstart.o \
./kern/compile/ASST2/.depend.threadtest.o \
./kern/compile/ASST2/.depend.time.o \
./kern/compile/ASST2/.depend.time_syscalls.o \
./kern/compile/ASST2/.depend.tlb-mips161.o \
./kern/compile/ASST2/.depend.trap.o \
./kern/compile/ASST2/.depend.tt3.o \
./kern/compile/ASST2/.depend.ucmpdi2.o \
./kern/compile/ASST2/.depend.udivdi3.o \
./kern/compile/ASST2/.depend.uio.o \
./kern/compile/ASST2/.depend.umoddi3.o \
./kern/compile/ASST2/.depend.vfscwd.o \
./kern/compile/ASST2/.depend.vfsfail.o \
./kern/compile/ASST2/.depend.vfslist.o \
./kern/compile/ASST2/.depend.vfslookup.o \
./kern/compile/ASST2/.depend.vfspath.o \
./kern/compile/ASST2/.depend.vnode.o \
./kern/compile/ASST2/.depend.xordi3.o \
./kern/compile/ASST2/autoconf.o \
./kern/compile/ASST2/vers.o
C_DEPS += \
./kern/compile/ASST2/.depend.__printf.d \
./kern/compile/ASST2/.depend.adddi3.d \
./kern/compile/ASST2/.depend.anddi3.d \
./kern/compile/ASST2/.depend.array.d \
./kern/compile/ASST2/.depend.arraytest.d \
./kern/compile/ASST2/.depend.ashldi3.d \
./kern/compile/ASST2/.depend.ashrdi3.d \
./kern/compile/ASST2/.depend.atoi.d \
./kern/compile/ASST2/.depend.autoconf.d \
./kern/compile/ASST2/.depend.beep.d \
./kern/compile/ASST2/.depend.beep_ltimer.d \
./kern/compile/ASST2/.depend.bitmap.d \
./kern/compile/ASST2/.depend.bitmaptest.d \
./kern/compile/ASST2/.depend.bswap.d \
./kern/compile/ASST2/.depend.bzero.d \
./kern/compile/ASST2/.depend.clock.d \
./kern/compile/ASST2/.depend.cmpdi2.d \
./kern/compile/ASST2/.depend.con_lser.d \
./kern/compile/ASST2/.depend.console.d \
./kern/compile/ASST2/.depend.copyinout.d \
./kern/compile/ASST2/.depend.cpu.d \
./kern/compile/ASST2/.depend.device.d \
./kern/compile/ASST2/.depend.devnull.d \
./kern/compile/ASST2/.depend.divdi3.d \
./kern/compile/ASST2/.depend.dumbvm.d \
./kern/compile/ASST2/.depend.emu.d \
./kern/compile/ASST2/.depend.emu_att.d \
./kern/compile/ASST2/.depend.file_syscalls.d \
./kern/compile/ASST2/.depend.fstest.d \
./kern/compile/ASST2/.depend.hmacunit.d \
./kern/compile/ASST2/.depend.iordi3.d \
./kern/compile/ASST2/.depend.kgets.d \
./kern/compile/ASST2/.depend.kmalloc.d \
./kern/compile/ASST2/.depend.kmalloctest.d \
./kern/compile/ASST2/.depend.kprintf.d \
./kern/compile/ASST2/.depend.lamebus.d \
./kern/compile/ASST2/.depend.lamebus_machdep.d \
./kern/compile/ASST2/.depend.lhd.d \
./kern/compile/ASST2/.depend.lhd_att.d \
./kern/compile/ASST2/.depend.lib.d \
./kern/compile/ASST2/.depend.loadelf.d \
./kern/compile/ASST2/.depend.lrandom.d \
./kern/compile/ASST2/.depend.lrandom_att.d \
./kern/compile/ASST2/.depend.lser.d \
./kern/compile/ASST2/.depend.lser_att.d \
./kern/compile/ASST2/.depend.lshldi3.d \
./kern/compile/ASST2/.depend.lshrdi3.d \
./kern/compile/ASST2/.depend.ltimer.d \
./kern/compile/ASST2/.depend.ltimer_att.d \
./kern/compile/ASST2/.depend.ltrace.d \
./kern/compile/ASST2/.depend.ltrace_att.d \
./kern/compile/ASST2/.depend.main.d \
./kern/compile/ASST2/.depend.memcpy.d \
./kern/compile/ASST2/.depend.memmove.d \
./kern/compile/ASST2/.depend.memset.d \
./kern/compile/ASST2/.depend.menu.d \
./kern/compile/ASST2/.depend.misc.d \
./kern/compile/ASST2/.depend.moddi3.d \
./kern/compile/ASST2/.depend.muldi3.d \
./kern/compile/ASST2/.depend.negdi2.d \
./kern/compile/ASST2/.depend.notdi2.d \
./kern/compile/ASST2/.depend.proc.d \
./kern/compile/ASST2/.depend.proc_syscalls.d \
./kern/compile/ASST2/.depend.qdivrem.d \
./kern/compile/ASST2/.depend.ram.d \
./kern/compile/ASST2/.depend.random.d \
./kern/compile/ASST2/.depend.random_lrandom.d \
./kern/compile/ASST2/.depend.rtclock.d \
./kern/compile/ASST2/.depend.rtclock_ltimer.d \
./kern/compile/ASST2/.depend.runprogram.d \
./kern/compile/ASST2/.depend.rwtest.d \
./kern/compile/ASST2/.depend.secure.d \
./kern/compile/ASST2/.depend.semfs_fsops.d \
./kern/compile/ASST2/.depend.semfs_obj.d \
./kern/compile/ASST2/.depend.semfs_vnops.d \
./kern/compile/ASST2/.depend.semunit.d \
./kern/compile/ASST2/.depend.sfs_balloc.d \
./kern/compile/ASST2/.depend.sfs_bmap.d \
./kern/compile/ASST2/.depend.sfs_dir.d \
./kern/compile/ASST2/.depend.sfs_fsops.d \
./kern/compile/ASST2/.depend.sfs_inode.d \
./kern/compile/ASST2/.depend.sfs_io.d \
./kern/compile/ASST2/.depend.sfs_vnops.d \
./kern/compile/ASST2/.depend.sha256.d \
./kern/compile/ASST2/.depend.snprintf.d \
./kern/compile/ASST2/.depend.spinlock.d \
./kern/compile/ASST2/.depend.spl.d \
./kern/compile/ASST2/.depend.strcat.d \
./kern/compile/ASST2/.depend.strchr.d \
./kern/compile/ASST2/.depend.strcmp.d \
./kern/compile/ASST2/.depend.strcpy.d \
./kern/compile/ASST2/.depend.strlen.d \
./kern/compile/ASST2/.depend.strrchr.d \
./kern/compile/ASST2/.depend.strtok_r.d \
./kern/compile/ASST2/.depend.subdi3.d \
./kern/compile/ASST2/.depend.switchframe.d \
./kern/compile/ASST2/.depend.synch.d \
./kern/compile/ASST2/.depend.synchtest.d \
./kern/compile/ASST2/.depend.syscall.d \
./kern/compile/ASST2/.depend.test161.d \
./kern/compile/ASST2/.depend.thread.d \
./kern/compile/ASST2/.depend.thread_machdep.d \
./kern/compile/ASST2/.depend.threadlist.d \
./kern/compile/ASST2/.depend.threadlisttest.d \
./kern/compile/ASST2/.depend.threadtest.d \
./kern/compile/ASST2/.depend.time.d \
./kern/compile/ASST2/.depend.time_syscalls.d \
./kern/compile/ASST2/.depend.trap.d \
./kern/compile/ASST2/.depend.tt3.d \
./kern/compile/ASST2/.depend.ucmpdi2.d \
./kern/compile/ASST2/.depend.udivdi3.d \
./kern/compile/ASST2/.depend.uio.d \
./kern/compile/ASST2/.depend.umoddi3.d \
./kern/compile/ASST2/.depend.vfscwd.d \
./kern/compile/ASST2/.depend.vfsfail.d \
./kern/compile/ASST2/.depend.vfslist.d \
./kern/compile/ASST2/.depend.vfslookup.d \
./kern/compile/ASST2/.depend.vfspath.d \
./kern/compile/ASST2/.depend.vnode.d \
./kern/compile/ASST2/.depend.xordi3.d \
./kern/compile/ASST2/autoconf.d \
./kern/compile/ASST2/vers.d
# Each subdirectory must supply rules for building sources it contributes
kern/compile/ASST2/%.o: ../kern/compile/ASST2/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
kern/compile/ASST2/%.o: ../kern/compile/ASST2/%.S
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Assembler'
as -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/kern/include/vm.h
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004, 2005, 2008, 2009
* The President and Fellows of Harvard College.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the 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 UNIVERSITY 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 UNIVERSITY 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.
*/
#ifndef _VM_H_
#define _VM_H_
/*
* VM system-related definitions.
*
* You'll probably want to add stuff here.
*/
#include <machine/vm.h>
#include <spinlock.h>
/* Fault-type arguments to vm_fault() */
#define VM_FAULT_READ 0 /* A read was attempted */
#define VM_FAULT_WRITE 1 /* A write was attempted */
#define VM_FAULT_READONLY 2 /* A write to a readonly page was attempted*/
#define MYVM_STACKPAGES 1024
#define SWAPDISK_SIZE 8192
#define FREE 1
#define DIRTY 2
#define CLEAN 3
#define FIXED 4
struct coremap_entry* coremap;
struct spinlock coremap_spinlock;
struct spinlock tlb_spinlock;
paddr_t first;
paddr_t last;
unsigned first_free_addr;
unsigned num_pages;
unsigned usedBytes;
bool swapping;
unsigned swapdisk_index; //to store current index of swapdisk ptr
struct vnode *swapdisk_vnode;
struct lock *paging_lock;
struct bitmap *swapdisk_bitmap;
unsigned clock_pte_ptr;
//char *helper1[1000];
//char *helper2[2000];
//int h1index;
//int h2index;
int coremap_size;
int no_of_coremap_entries;
size_t num_swappages;
//added by sammokka
struct coremap_entry {
size_t size;
int state; //0 for clean, 1 for dirty, 2 for free
bool busy;
struct PTE *pte_ptr;
bool clock;
int cpu_num;
};
/* Initialization function */
void vm_bootstrap(void);
/* Fault handling function called by trap code */
int vm_fault(int faulttype, vaddr_t faultaddress);
/* Allocate/free kernel heap pages (called by kmalloc/kfree) */
vaddr_t alloc_kpages(unsigned npages);
void free_kpages(vaddr_t addr);
paddr_t page_alloc(struct PTE *pte);
void page_free(paddr_t paddr);
/*
* Return amount of memory (in bytes) used by allocated coremap pages. If
* there are ongoing allocations, this value could change after it is returned
* to the caller. But it should have been correct at some point in time.
*/
unsigned int coremap_used_bytes(void);
/* TLB shootdown handling called from interprocessor_interrupt */
void vm_tlbshootdown_all(void);
void vm_tlbshootdown(const struct tlbshootdown *);
void vm_tlbshootdownvaddr(vaddr_t vaddr);
void swapdisk_init(void);
int evict(void);
void swapout(vaddr_t swapaddr, paddr_t paddr);
void swapin(vaddr_t swapaddr, paddr_t paddr);
#endif /* _VM_H_ */
<file_sep>/kern/synchprobs/stoplight.c
/*
* Copyright (c) 2001, 2002, 2009
* The President and Fellows of Harvard College.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the 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 UNIVERSITY 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 UNIVERSITY 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.
*/
/*
* Driver code is in kern/tests/synchprobs.c We will replace that file. This
* file is yours to modify as you see fit.
*
* You should implement your solution to the stoplight problem below. The
* quadrant and direction mappings for reference: (although the problem is, of
* course, stable under rotation)
*
* |0 |
* - --
* 01 1
* 3 32
* -- --
* | 2|
*
* As way to think about it, assuming cars drive on the right: a car entering
* the intersection from direction X will enter intersection quadrant X first.
* The semantics of the problem are that once a car enters any quadrant it has
* to be somewhere in the intersection until it call leaveIntersection(),
* which it should call while in the final quadrant.
*
* As an example, let's say a car approaches the intersection and needs to
* pass through quadrants 0, 3 and 2. Once you call inQuadrant(0), the car is
* considered in quadrant 0 until you call inQuadrant(3). After you call
* inQuadrant(2), the car is considered in quadrant 2 until you call
* leaveIntersection().
*
* You will probably want to write some helper functions to assist with the
* mappings. Modular arithmetic can help, e.g. a car passing straight through
* the intersection entering from direction X will leave to direction (X + 2)
* % 4 and pass through quadrants X and (X + 3) % 4. Boo-yah.
*
* Your solutions below should call the inQuadrant() and leaveIntersection()
* functions in synchprobs.c to record their progress.
*/
#include <types.h>
#include <lib.h>
#include <thread.h>
#include <test.h>
#include <synch.h>
/*
* Called by the driver during initialization.
*/
struct lock *locks[4];
void
stoplight_init() {
//added by sammokka
locks[0] = lock_create("lock0");
locks[1] = lock_create("lock1");
locks[2] = lock_create("lock2");
locks[3] = lock_create("lock3");
return;
}
/*
* Called by the driver during teardown.
*/
void stoplight_cleanup() {
//added by sammmokka
lock_destroy(locks[0]);
lock_destroy(locks[1]);
lock_destroy(locks[2]);
lock_destroy(locks[3]);
return;
}
void
turnright(uint32_t direction, uint32_t index)
{
// kprintf_n("printing ordering of direction (go right).. %d,\n",direction);
//added by sammokka
lock_acquire(locks[direction]);
inQuadrant(direction, index);
leaveIntersection(index);
lock_release(locks[direction]);
return;
}
void
gostraight(uint32_t direction, uint32_t index)
{
//added by sammokka
int a[2];
if( direction>(direction + 3) % 4) {
a[0]=(direction + 3) % 4;
a[1] = direction;
} else {
a[1]=(direction + 3) % 4;
a[0] = direction;
}
// kprintf_n("printing ordering of direction (go straight).. %d,%d\n",a[0],a[1]);
lock_acquire(locks[a[0]]);
lock_acquire(locks[a[1]]);
inQuadrant(direction, index);
inQuadrant((direction + 3) % 4, index);
leaveIntersection(index);
lock_release(locks[a[1]]);
lock_release(locks[a[0]]);
return;
}
void
turnleft(uint32_t direction, uint32_t index) {
//added by sammmokka
int a[3];
a[0] = direction;
a[1] = (direction + 3) % 4;
a[2] = (direction + 2) % 4;
int swap = 0;
//order a in increasing order
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (a[i] < a[j]) {
//swap a[i] and a[j]
swap = a[i];
a[i] = a[j];
a[j] = swap;
}
}
}
// kprintf_n("printing ordering of direction(go left).. %d,%d,%d\n",a[0],a[1],a[2]);
//added by sammokka
lock_acquire(locks[a[0]]);
lock_acquire(locks[a[1]]);
lock_acquire(locks[a[2]]);
// kprintf_n("Direction is.. %d\n",direction);
inQuadrant(direction, index);
inQuadrant((direction + 3) % 4, index);
inQuadrant((direction + 2) % 4, index);
leaveIntersection(index);
lock_release(locks[a[2]]);
lock_release(locks[a[1]]);
lock_release(locks[a[0]]);
return;
}
<file_sep>/Debug/userland/testbin/frack/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../userland/testbin/frack/check.c \
../userland/testbin/frack/data.c \
../userland/testbin/frack/do.c \
../userland/testbin/frack/main.c \
../userland/testbin/frack/name.c \
../userland/testbin/frack/ops.c \
../userland/testbin/frack/pool.c \
../userland/testbin/frack/workloads.c
OBJS += \
./userland/testbin/frack/check.o \
./userland/testbin/frack/data.o \
./userland/testbin/frack/do.o \
./userland/testbin/frack/main.o \
./userland/testbin/frack/name.o \
./userland/testbin/frack/ops.o \
./userland/testbin/frack/pool.o \
./userland/testbin/frack/workloads.o
C_DEPS += \
./userland/testbin/frack/check.d \
./userland/testbin/frack/data.d \
./userland/testbin/frack/do.d \
./userland/testbin/frack/main.d \
./userland/testbin/frack/name.d \
./userland/testbin/frack/ops.d \
./userland/testbin/frack/pool.d \
./userland/testbin/frack/workloads.d
# Each subdirectory must supply rules for building sources it contributes
userland/testbin/frack/%.o: ../userland/testbin/frack/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/Debug/userland/sbin/sfsck/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../userland/sbin/sfsck/freemap.c \
../userland/sbin/sfsck/inode.c \
../userland/sbin/sfsck/main.c \
../userland/sbin/sfsck/pass1.c \
../userland/sbin/sfsck/pass2.c \
../userland/sbin/sfsck/sb.c \
../userland/sbin/sfsck/sfs.c \
../userland/sbin/sfsck/utils.c
OBJS += \
./userland/sbin/sfsck/freemap.o \
./userland/sbin/sfsck/inode.o \
./userland/sbin/sfsck/main.o \
./userland/sbin/sfsck/pass1.o \
./userland/sbin/sfsck/pass2.o \
./userland/sbin/sfsck/sb.o \
./userland/sbin/sfsck/sfs.o \
./userland/sbin/sfsck/utils.o
C_DEPS += \
./userland/sbin/sfsck/freemap.d \
./userland/sbin/sfsck/inode.d \
./userland/sbin/sfsck/main.d \
./userland/sbin/sfsck/pass1.d \
./userland/sbin/sfsck/pass2.d \
./userland/sbin/sfsck/sb.d \
./userland/sbin/sfsck/sfs.d \
./userland/sbin/sfsck/utils.d
# Each subdirectory must supply rules for building sources it contributes
userland/sbin/sfsck/%.o: ../userland/sbin/sfsck/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/Debug/common/libc/string/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../common/libc/string/bzero.c \
../common/libc/string/memcpy.c \
../common/libc/string/memmove.c \
../common/libc/string/memset.c \
../common/libc/string/strcat.c \
../common/libc/string/strchr.c \
../common/libc/string/strcmp.c \
../common/libc/string/strcpy.c \
../common/libc/string/strlen.c \
../common/libc/string/strrchr.c \
../common/libc/string/strtok_r.c
OBJS += \
./common/libc/string/bzero.o \
./common/libc/string/memcpy.o \
./common/libc/string/memmove.o \
./common/libc/string/memset.o \
./common/libc/string/strcat.o \
./common/libc/string/strchr.o \
./common/libc/string/strcmp.o \
./common/libc/string/strcpy.o \
./common/libc/string/strlen.o \
./common/libc/string/strrchr.o \
./common/libc/string/strtok_r.o
C_DEPS += \
./common/libc/string/bzero.d \
./common/libc/string/memcpy.d \
./common/libc/string/memmove.d \
./common/libc/string/memset.d \
./common/libc/string/strcat.d \
./common/libc/string/strchr.d \
./common/libc/string/strcmp.d \
./common/libc/string/strcpy.d \
./common/libc/string/strlen.d \
./common/libc/string/strrchr.d \
./common/libc/string/strtok_r.d
# Each subdirectory must supply rules for building sources it contributes
common/libc/string/%.o: ../common/libc/string/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/kern/syscall/file_syscalls.c
#include <types.h>
#include <clock.h>
#include <copyinout.h>
#include <current.h>
#include <vfs.h>
#include <vnode.h>
#include <synch.h>
#include <proc.h>
#include <limits.h>
#include <kern/errno.h>
#include <kern/stat.h>
#include <kern/iovec.h>
#include <uio.h>
#include <syscall.h>
#include <lib.h>
#include <stdarg.h>
#include <types.h>
#include <kern/fcntl.h>
#include <kern/seek.h>
/**
* Added by sammokka
* input:
* flags -> is a OR of flags
*
* output: file descriptor
*
* eg: O_WRONLY|O_CREAT|O_TRUNC
*/
int sys_open(char *filename, int flags, int32_t *retval) {
mode_t mode = 0664; // Dunno what this means but whatever.
char name[100];
int result;
if (filename == NULL || filename == (void *) 0x40000000) {
*retval = -1;
return EFAULT;
}
if (flags > 66) {
*retval = -1;
return EINVAL;
}
size_t length;
result = copycheck1((const_userptr_t) filename, PATH_MAX, &length);
if (result) {
*retval = -1;
return result;
}
result = copyinstr((const_userptr_t) filename, name, sizeof(name), NULL);
if (result) { //memory problem
*retval = -1;
return result;
}
struct vnode *ret; //empty nvnode
int returner = vfs_open(name, flags, mode, &ret);
if ((returner == 0)) { // && (name != fd_name)) {
int inserted_flag = 0;
for (int i = 3; i < OPEN_MAX; i++) {
if (curproc->proc_filedesc[i] != NULL) {
if (curproc->proc_filedesc[i]->isempty == 1) {
//it is empty, you can use this
} else {
//its being used elsewhere, check the next element for empty
continue;
}
} else {
//nothing, you can use this
}
// if it gets to here, then it's found an index where pointer is not used up
//now create a filedesc structure
struct filedesc *filedesc_ptr;
filedesc_ptr = kmalloc(sizeof(*filedesc_ptr));
if (filedesc_ptr == NULL) {
*retval = -1;
return ENOMEM;
}
filedesc_ptr->fd_lock = lock_create(name); //not sure when i should use this lock
if (filedesc_ptr->fd_lock == NULL) {
kfree(filedesc_ptr);
*retval = -1;
return ENOMEM;
}
filedesc_ptr->isempty = 0; //not empty
filedesc_ptr->fd_vnode = ret; //pointer to vnode object to be stored in filedesc->vnode
filedesc_ptr->flags = flags;
filedesc_ptr->read_count = 1;
filedesc_ptr->name = kstrdup(name);
filedesc_ptr->fd_refcount = 1;
if ((flags & O_APPEND) == O_APPEND) {
struct stat *stat_obj;
stat_obj = kmalloc(sizeof(struct stat));
if (stat_obj == NULL) {
kfree(filedesc_ptr);
*retval = -1;
return ENOMEM;
}
int vopstat_returner = VOP_STAT(ret, stat_obj);
if (vopstat_returner != 0) {
}
filedesc_ptr->offset = stat_obj->st_size;
kfree(stat_obj);
} else {
filedesc_ptr->offset = 0;
}
//make the thread->filedesc point to the filedesc
lock_acquire(filedesc_ptr->fd_lock);
curproc->proc_filedesc[i] = filedesc_ptr;
lock_release(curproc->proc_filedesc[i]->fd_lock);
*retval = i; //store the value returned by vfs_open to retval
inserted_flag = 1;
break;
}
if (inserted_flag == 0) {
return EMFILE;
}
}
return 0; //returns 0 if no error.
}
int sys_write(int fd, const void *buf, size_t size, ssize_t *retval) {
if (fd < 0 || fd >= OPEN_MAX) {
*retval = -1;
return EBADF;
}
if (curproc->proc_filedesc[fd] == NULL
|| (curproc->proc_filedesc[fd]->flags & O_ACCMODE) == O_RDONLY) {
*retval = -1;
return EBADF;
}
size_t length;
int err1;
err1 = copycheck1((const_userptr_t) buf, size, &length);
if (err1) {
*retval = -1;
return EFAULT;
}
if (buf == (void *) 0x40000000) {
*retval = -1;
return EFAULT;
}
lock_acquire(curproc->proc_filedesc[fd]->fd_lock);
struct iovec iov;
struct uio uio_obj;
int err;
off_t pos = curproc->proc_filedesc[fd]->offset;
//copying code from load_elf.c
iov.iov_ubase = (userptr_t) buf;
iov.iov_len = size;
uio_obj.uio_iov = &iov;
uio_obj.uio_iovcnt = 1;
uio_obj.uio_offset = pos;
uio_obj.uio_resid = size;
uio_obj.uio_segflg = UIO_USERSPACE;
uio_obj.uio_rw = UIO_WRITE;
uio_obj.uio_space = curproc->p_addrspace;
err = VOP_WRITE(curproc->proc_filedesc[fd]->fd_vnode, &uio_obj);
if (err) {
lock_release(curproc->proc_filedesc[fd]->fd_lock);
*retval = -1;
return err;
}
curproc->proc_filedesc[fd]->offset = uio_obj.uio_offset;
*retval = size - uio_obj.uio_resid;
lock_release(curproc->proc_filedesc[fd]->fd_lock);
return 0; //done: handle returns. only specific returns possible
}
int sys_close(int fd, ssize_t *retval) {
if (fd < 0 || fd > OPEN_MAX) {
*retval = -1;
return EBADF;
} else if (curproc->proc_filedesc[fd] == NULL) {
return EBADF;
} else {
if ((curproc->proc_filedesc[fd] != NULL) && (fd > 2)) {
int refcount;
lock_acquire(curproc->proc_filedesc[fd]->fd_lock);
curproc->proc_filedesc[fd]->fd_refcount--;
lock_release(curproc->proc_filedesc[fd]->fd_lock);
refcount = curproc->proc_filedesc[fd]->fd_refcount;
if (refcount == 0) {
vfs_close(curproc->proc_filedesc[fd]->fd_vnode);
lock_destroy(curproc->proc_filedesc[fd]->fd_lock);
kfree(curproc->proc_filedesc[fd]->name);
kfree(curproc->proc_filedesc[fd]);
curproc->proc_filedesc[fd] = NULL;
}
}
*retval = 0;
return 0;
}
}
int sys_read(int fd, void *buf, size_t buflen, ssize_t *retval) {
if (fd >= OPEN_MAX || fd < 0 ||
curproc->proc_filedesc[fd] == NULL
|| curproc->proc_filedesc[fd]->isempty == 1
|| ((curproc->proc_filedesc[fd]->flags & O_ACCMODE) == O_WRONLY)) {
*retval = -1;
return EBADF;
}
size_t length;
int result;
result = copycheck1((const_userptr_t) buf, buflen, &length);
if (result) {
*retval = -1;
return result;
}
if (buf == (void *) 0x40000000) {
*retval = -1;
return EFAULT;
}
struct iovec iov;
struct uio uio_obj;
lock_acquire(curproc->proc_filedesc[fd]->fd_lock);
iov.iov_ubase = (userptr_t) buf;
iov.iov_len = buflen;
uio_obj.uio_iov = &iov;
uio_obj.uio_iovcnt = 1;
off_t pos = curproc->proc_filedesc[fd]->offset;
uio_obj.uio_offset = pos;
uio_obj.uio_resid = buflen;
uio_obj.uio_segflg = UIO_USERSPACE;
uio_obj.uio_rw = UIO_READ;
uio_obj.uio_space = curproc->p_addrspace;
int err = VOP_READ(curproc->proc_filedesc[fd]->fd_vnode, &uio_obj);
if (err) {
lock_release(curproc->proc_filedesc[fd]->fd_lock);
return EINVAL;
}
curproc->proc_filedesc[fd]->offset = uio_obj.uio_offset;
*retval = buflen - uio_obj.uio_resid;
lock_release(curproc->proc_filedesc[fd]->fd_lock);
return 0;
}
int sys_dup2(int oldfd, int newfd, ssize_t *retval) {
int result = 0;
if (oldfd > OPEN_MAX || oldfd < 0 || newfd < 0 || newfd >= OPEN_MAX) {
*retval = -1;
return EBADF;
}
if (newfd >= OPEN_MAX) {
*retval = -1;
return EMFILE;
}
if (curproc->proc_filedesc[oldfd] == NULL) {
*retval = -1;
return EBADF;
}
lock_acquire(curproc->proc_filedesc[oldfd]->fd_lock);
if (curproc->proc_filedesc[newfd] != NULL) {
result = sys_close(newfd, retval);
if (result) {
lock_release(curproc->proc_filedesc[oldfd]->fd_lock);
return EBADF;
}
}
curproc->proc_filedesc[oldfd]->fd_refcount++;
curproc->proc_filedesc[newfd] = curproc->proc_filedesc[oldfd];
lock_release(curproc->proc_filedesc[oldfd]->fd_lock);
*retval = newfd;
return 0;
}
off_t sys_lseek(int filehandle, off_t pos, int code, ssize_t *retval,
ssize_t *retval2) {
if (filehandle > OPEN_MAX
|| filehandle < 0|| curproc->proc_filedesc[filehandle] == NULL) {
*retval = -1;
return EBADF;
}
int result;
off_t offset;
off_t filesize;
struct stat file_stat;
lock_acquire(curproc->proc_filedesc[filehandle]->fd_lock);
result = VOP_ISSEEKABLE(curproc->proc_filedesc[filehandle]->fd_vnode);
if (!result) { //file not seekable
lock_release(curproc->proc_filedesc[filehandle]->fd_lock);
return ESPIPE;
}
result = VOP_STAT(curproc->proc_filedesc[filehandle]->fd_vnode, &file_stat);
if (result) { //VOP_STAT failed
lock_release(curproc->proc_filedesc[filehandle]->fd_lock);
return result;
}
filesize = file_stat.st_size;
if (code == SEEK_SET) { //the new position is pos
offset = pos;
} else if (code == SEEK_CUR) { // the new position is the current position plus pos
offset = pos + curproc->proc_filedesc[filehandle]->offset;
} else if (code == SEEK_END) { //the new position is the position of end-of-file plus pos
offset = pos + filesize;
} else {
lock_release(curproc->proc_filedesc[filehandle]->fd_lock);
return EINVAL;
}
if (offset < (off_t) 0) {
lock_release(curproc->proc_filedesc[filehandle]->fd_lock);
return EINVAL;
}
curproc->proc_filedesc[filehandle]->offset = offset;
*retval = (offset & 0xFFFFFFFF00000000) >> 32;
*retval2 = offset & 0xFFFFFFFF;
lock_release(curproc->proc_filedesc[filehandle]->fd_lock);
return 0;
}
int sys_chdir(const char *path) {
int result;
char *path2;
size_t size;
path2 = (char *) kmalloc(sizeof(char) * PATH_MAX);
if (path2 == NULL) {
return ENOMEM;
}
result = copyinstr((const_userptr_t) path, path2, PATH_MAX, &size);
if (result) {
kfree(path2);
return EFAULT;
}
result = vfs_chdir(path2);
if (result) {
kfree(path2);
return result;
}
kfree(path2);
return 0;
}
int sys___getcwd(char *buf, size_t buflen, int *retval) {
if (buf == (void *) 0x40000000) {
*retval = -1;
return EFAULT;
}
char *cwdbuf;
cwdbuf = kmalloc(sizeof(*buf) * buflen);
if (cwdbuf == NULL) {
*retval = -1;
return ENOMEM;
}
int result;
size_t size;
result = copyinstr((const_userptr_t) buf, cwdbuf, PATH_MAX, &size);
if (result) {
kfree(cwdbuf);
return EFAULT;
}
struct iovec iov;
struct uio uio;
iov.iov_ubase = (userptr_t) buf;
iov.iov_len = buflen;
uio.uio_iov = &iov;
uio.uio_iovcnt = 1;
uio.uio_offset = (off_t) 0;
uio.uio_resid = buflen;
uio.uio_segflg = UIO_USERSPACE;
uio.uio_rw = UIO_READ;
uio.uio_space = curproc->p_addrspace;
result = vfs_getcwd(&uio);
if (result) {
kfree(cwdbuf);
return result;
}
*retval = strlen(buf);
kfree(cwdbuf);
return 0;
}
<file_sep>/Debug/kern/syscall/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../kern/syscall/file_syscalls.c \
../kern/syscall/loadelf.c \
../kern/syscall/proc_syscalls.c \
../kern/syscall/runprogram.c \
../kern/syscall/time_syscalls.c
OBJS += \
./kern/syscall/file_syscalls.o \
./kern/syscall/loadelf.o \
./kern/syscall/proc_syscalls.o \
./kern/syscall/runprogram.o \
./kern/syscall/time_syscalls.o
C_DEPS += \
./kern/syscall/file_syscalls.d \
./kern/syscall/loadelf.d \
./kern/syscall/proc_syscalls.d \
./kern/syscall/runprogram.d \
./kern/syscall/time_syscalls.d
# Each subdirectory must supply rules for building sources it contributes
kern/syscall/%.o: ../kern/syscall/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/Debug/kern/fs/sfs/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../kern/fs/sfs/sfs_balloc.c \
../kern/fs/sfs/sfs_bmap.c \
../kern/fs/sfs/sfs_dir.c \
../kern/fs/sfs/sfs_fsops.c \
../kern/fs/sfs/sfs_inode.c \
../kern/fs/sfs/sfs_io.c \
../kern/fs/sfs/sfs_vnops.c
OBJS += \
./kern/fs/sfs/sfs_balloc.o \
./kern/fs/sfs/sfs_bmap.o \
./kern/fs/sfs/sfs_dir.o \
./kern/fs/sfs/sfs_fsops.o \
./kern/fs/sfs/sfs_inode.o \
./kern/fs/sfs/sfs_io.o \
./kern/fs/sfs/sfs_vnops.o
C_DEPS += \
./kern/fs/sfs/sfs_balloc.d \
./kern/fs/sfs/sfs_bmap.d \
./kern/fs/sfs/sfs_dir.d \
./kern/fs/sfs/sfs_fsops.d \
./kern/fs/sfs/sfs_inode.d \
./kern/fs/sfs/sfs_io.d \
./kern/fs/sfs/sfs_vnops.d
# Each subdirectory must supply rules for building sources it contributes
kern/fs/sfs/%.o: ../kern/fs/sfs/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/Debug/kern/test/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../kern/test/arraytest.c \
../kern/test/automationtest.c \
../kern/test/bitmaptest.c \
../kern/test/fstest.c \
../kern/test/hmacunit.c \
../kern/test/kmalloctest.c \
../kern/test/lib.c \
../kern/test/nettest.c \
../kern/test/rwtest.c \
../kern/test/semunit.c \
../kern/test/synchprobs.c \
../kern/test/synchtest.c \
../kern/test/threadlisttest.c \
../kern/test/threadtest.c \
../kern/test/tt3.c
OBJS += \
./kern/test/arraytest.o \
./kern/test/automationtest.o \
./kern/test/bitmaptest.o \
./kern/test/fstest.o \
./kern/test/hmacunit.o \
./kern/test/kmalloctest.o \
./kern/test/lib.o \
./kern/test/nettest.o \
./kern/test/rwtest.o \
./kern/test/semunit.o \
./kern/test/synchprobs.o \
./kern/test/synchtest.o \
./kern/test/threadlisttest.o \
./kern/test/threadtest.o \
./kern/test/tt3.o
C_DEPS += \
./kern/test/arraytest.d \
./kern/test/automationtest.d \
./kern/test/bitmaptest.d \
./kern/test/fstest.d \
./kern/test/hmacunit.d \
./kern/test/kmalloctest.d \
./kern/test/lib.d \
./kern/test/nettest.d \
./kern/test/rwtest.d \
./kern/test/semunit.d \
./kern/test/synchprobs.d \
./kern/test/synchtest.d \
./kern/test/threadlisttest.d \
./kern/test/threadtest.d \
./kern/test/tt3.d
# Each subdirectory must supply rules for building sources it contributes
kern/test/%.o: ../kern/test/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/Debug/common/gcc-millicode/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../common/gcc-millicode/adddi3.c \
../common/gcc-millicode/anddi3.c \
../common/gcc-millicode/ashldi3.c \
../common/gcc-millicode/ashrdi3.c \
../common/gcc-millicode/cmpdi2.c \
../common/gcc-millicode/divdi3.c \
../common/gcc-millicode/iordi3.c \
../common/gcc-millicode/lshldi3.c \
../common/gcc-millicode/lshrdi3.c \
../common/gcc-millicode/moddi3.c \
../common/gcc-millicode/muldi3.c \
../common/gcc-millicode/negdi2.c \
../common/gcc-millicode/notdi2.c \
../common/gcc-millicode/qdivrem.c \
../common/gcc-millicode/subdi3.c \
../common/gcc-millicode/ucmpdi2.c \
../common/gcc-millicode/udivdi3.c \
../common/gcc-millicode/umoddi3.c \
../common/gcc-millicode/xordi3.c
OBJS += \
./common/gcc-millicode/adddi3.o \
./common/gcc-millicode/anddi3.o \
./common/gcc-millicode/ashldi3.o \
./common/gcc-millicode/ashrdi3.o \
./common/gcc-millicode/cmpdi2.o \
./common/gcc-millicode/divdi3.o \
./common/gcc-millicode/iordi3.o \
./common/gcc-millicode/lshldi3.o \
./common/gcc-millicode/lshrdi3.o \
./common/gcc-millicode/moddi3.o \
./common/gcc-millicode/muldi3.o \
./common/gcc-millicode/negdi2.o \
./common/gcc-millicode/notdi2.o \
./common/gcc-millicode/qdivrem.o \
./common/gcc-millicode/subdi3.o \
./common/gcc-millicode/ucmpdi2.o \
./common/gcc-millicode/udivdi3.o \
./common/gcc-millicode/umoddi3.o \
./common/gcc-millicode/xordi3.o
C_DEPS += \
./common/gcc-millicode/adddi3.d \
./common/gcc-millicode/anddi3.d \
./common/gcc-millicode/ashldi3.d \
./common/gcc-millicode/ashrdi3.d \
./common/gcc-millicode/cmpdi2.d \
./common/gcc-millicode/divdi3.d \
./common/gcc-millicode/iordi3.d \
./common/gcc-millicode/lshldi3.d \
./common/gcc-millicode/lshrdi3.d \
./common/gcc-millicode/moddi3.d \
./common/gcc-millicode/muldi3.d \
./common/gcc-millicode/negdi2.d \
./common/gcc-millicode/notdi2.d \
./common/gcc-millicode/qdivrem.d \
./common/gcc-millicode/subdi3.d \
./common/gcc-millicode/ucmpdi2.d \
./common/gcc-millicode/udivdi3.d \
./common/gcc-millicode/umoddi3.d \
./common/gcc-millicode/xordi3.d
# Each subdirectory must supply rules for building sources it contributes
common/gcc-millicode/%.o: ../common/gcc-millicode/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/Debug/kern/vfs/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../kern/vfs/device.c \
../kern/vfs/devnull.c \
../kern/vfs/vfscwd.c \
../kern/vfs/vfsfail.c \
../kern/vfs/vfslist.c \
../kern/vfs/vfslookup.c \
../kern/vfs/vfspath.c \
../kern/vfs/vnode.c
OBJS += \
./kern/vfs/device.o \
./kern/vfs/devnull.o \
./kern/vfs/vfscwd.o \
./kern/vfs/vfsfail.o \
./kern/vfs/vfslist.o \
./kern/vfs/vfslookup.o \
./kern/vfs/vfspath.o \
./kern/vfs/vnode.o
C_DEPS += \
./kern/vfs/device.d \
./kern/vfs/devnull.d \
./kern/vfs/vfscwd.d \
./kern/vfs/vfsfail.d \
./kern/vfs/vfslist.d \
./kern/vfs/vfslookup.d \
./kern/vfs/vfspath.d \
./kern/vfs/vnode.d
# Each subdirectory must supply rules for building sources it contributes
kern/vfs/%.o: ../kern/vfs/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/kern/include/file_syscalls.h
#include <kern/fcntl.h>
struct filedesc {
struct vnode *fd_vnode;
int fd_refcount;
//int fd_count;
struct lock *fd_lock;
char *name;
int offset;
int isempty;
int flags;
int read_count;
};
/** added by sammokka
O_RDONLY Open for reading only.
O_WRONLY Open for writing only.
O_RDWR Open for reading and writing.
*/
int sys_open(char *filename, int flags, int32_t *retval);
int sys_close(int fd, ssize_t *retval);
ssize_t read(int fd, void *buf, size_t buflen);
int sys_write(int fd, const void *buf, size_t size, ssize_t *retval);
int sys_read(int fd,void *buf, size_t buflen, ssize_t *retval);
int sys_dup2(int filehandle, int newhandle, ssize_t *retval);
off_t sys_lseek(int filehandle, off_t pos, int code, ssize_t *retval, ssize_t *retval2);
int sys_chdir(const char *path);
ssize_t sys___getcwd(char *buf, size_t buflen, ssize_t *retval);
<file_sep>/Debug/userland/lib/libc/stdio/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../userland/lib/libc/stdio/__puts.c \
../userland/lib/libc/stdio/getchar.c \
../userland/lib/libc/stdio/printf.c \
../userland/lib/libc/stdio/putchar.c \
../userland/lib/libc/stdio/puts.c
OBJS += \
./userland/lib/libc/stdio/__puts.o \
./userland/lib/libc/stdio/getchar.o \
./userland/lib/libc/stdio/printf.o \
./userland/lib/libc/stdio/putchar.o \
./userland/lib/libc/stdio/puts.o
C_DEPS += \
./userland/lib/libc/stdio/__puts.d \
./userland/lib/libc/stdio/getchar.d \
./userland/lib/libc/stdio/printf.d \
./userland/lib/libc/stdio/putchar.d \
./userland/lib/libc/stdio/puts.d
# Each subdirectory must supply rules for building sources it contributes
userland/lib/libc/stdio/%.o: ../userland/lib/libc/stdio/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/kern/syscall/proc_syscalls.c
#include <types.h>
#include <clock.h>
#include <copyinout.h>
#include <current.h>
#include <vfs.h>
#include <vnode.h>
#include <synch.h>
#include <proc.h>
#include <limits.h>
#include <kern/errno.h>
#include <kern/stat.h>
#include <kern/iovec.h>
#include <uio.h>
#include <proc.h>
#include <addrspace.h>
#include <mips/trapframe.h>
#include <kern/proc_syscalls.h>
#include <kern/wait.h>
#include <syscall.h>
struct lock *p_lock;
struct proc *pt_proc[256];
//char *helper[4000];
//initializes file table
void pt_init() {
for (int i = 0; i < 256; i++) {
pt_proc[i] = NULL;
}
p_lock = lock_create("ptable lock");
}
// inserts process into file table, returns PID
pid_t insert_process_into_process_table(struct proc *newproc) {
lock_acquire(p_lock);
pid_t i = 2;
for (i = 2; i < 256; i++) {
if (pt_proc[i] == NULL) {
newproc->pid = i;
newproc->parent_pid = curproc->pid;
pt_proc[i] = newproc;
break;
}
}
lock_release(p_lock);
if (i == 256) {
//kprintf("out of proc table slots!!\n");
return -1;
} else {
return i;
}
}
static void entrypoint(void* data1, unsigned long data2) {
struct trapframe tf;
data2 = data2 + 100;
tf = *(struct trapframe *) data1;
tf.tf_a3 = 0;
tf.tf_v0 = 0;
tf.tf_epc += 4;
kfree(data1);
as_activate();
mips_usermode(&tf);
}
int sys_fork(struct trapframe *tf, int *retval) {
//create new thread
// kprintf(".");
*retval = -1;
struct proc *newproc;
newproc = proc_create_runprogram("name");
if (newproc == NULL) {
return ENOMEM;
}
//Copy parents address space
if (as_copy(curproc->p_addrspace, &newproc->p_addrspace)) {
return ENOMEM;
}
//Copy parents trapframe
struct trapframe *tf_child = kmalloc(sizeof(struct trapframe));
if (tf_child == NULL) {
return ENOMEM;
}
*tf_child = *tf;
//kprintf("tf_child mem -> %p\n", tf_child);
//kprintf("tf mem -> %p\n", tf);
//copy parents filetable entries
for (int k = 0; k < OPEN_MAX; k++) {
if (curproc->proc_filedesc[k] != NULL) {
lock_acquire(curproc->proc_filedesc[k]->fd_lock);
newproc->proc_filedesc[k] = curproc->proc_filedesc[k];
newproc->proc_filedesc[k]->fd_refcount++;
lock_release(curproc->proc_filedesc[k]->fd_lock);
}
}
newproc->p_cwd = curproc->p_cwd;
VOP_INCREF(curproc->p_cwd);
if (thread_fork("Child Thread", newproc, entrypoint, (void*) tf_child,
(unsigned long) 0)) {
return ENOMEM;
}
//kprintf("forked to pid->%d", newproc->pid);
*retval = newproc->pid;
return 0;
}
int sys_getpid(int *retval) {
*retval = curproc->pid;
return 0;
}
pid_t sys_waitpid(pid_t pid, int *status, int options, int *retval) {
//kprintf("\nwaiting on pid %d", pid);
*retval = -1;
if (pid == curproc->parent_pid || pid == curproc->pid) {
return ECHILD;
}
if (options != 0 && options != 1000) {
return EINVAL;
}
if (status == (void *) 0x40000000 || status == (void *) 0x80000000) {
return EFAULT;
}
if (pid > PID_MAX || pid < PID_MIN) {
return ESRCH;
}
if (pt_proc[pid] == NULL) {
//process does not exist (invalid pid)
return ESRCH;
}
if (options != 1000) {
if (pt_proc[pid]->parent_pid == curproc->parent_pid) {
return ECHILD;
}
}
if (pt_proc[pid]->isexited == false) {
P(pt_proc[pid]->proc_sem);
}
*retval = pid;
if (status != NULL) {
int result = copyout((const void *) &(pt_proc[pid]->exitcode),
(userptr_t) status, sizeof(int));
if (result) {
proc_destroy(pt_proc[pid]);
pt_proc[pid] = NULL;
return result;
}
}
proc_destroy(pt_proc[pid]);
pt_proc[pid] = NULL;
//kprintf("\ndestroyed pid %d", pid);
return 0;
}
int sys_execv(const char *program, char **uargs, int *retval) {
struct vnode *v;
vaddr_t entrypoint, stackptr;
int result, argmax;
size_t length;
char *name;
int i = 0;
*retval = -1;
if (uargs == NULL || program == NULL) {
return EFAULT;
}
size_t length1;
result = copycheck1((const_userptr_t) program, PATH_MAX, &length1);
if (result) {
return result;
}
result = copycheck1((const_userptr_t) uargs, PATH_MAX, &length1);
if (result) {
return result;
}
name = (char *) kmalloc(sizeof(char) * PATH_MAX);
if (name == NULL) {
return ENOMEM;
}
result = copyinstr((const_userptr_t) program, name, PATH_MAX, &length);
if (result) {
kfree(name);
return EFAULT;
}
if ((void *) program == (void *) 0x40000000
|| (void *) uargs == (void *) 0x40000000) {
kfree(name);
return EFAULT;
}
if ((char *) program == NULL || (char *) program == '\0') {
kfree(name);
return EINVAL;
}
if (length < 2 || length > PATH_MAX) {
kfree(name);
return EINVAL;
}
if ((void *) uargs[1] == (void *) 0x40000000) {
kfree(name);
return EFAULT;
}
int len = 0;
int act = 0;
int x = 0;
int totallen = 0;
while (uargs[x] != NULL) {
len = strlen(uargs[x]) + 1;
if ((len % 4) != 0) {
len = len - (len % 4) + 4;
}
totallen = totallen + len;
x++;
}
char *buf = (char *) kmalloc(sizeof(char) * (totallen + 1));
if (buf == NULL) {
kfree(name);
return ENOMEM;
}
char **ptrbuf = (char **) kmalloc(sizeof(char **) * x);
if (ptrbuf == NULL) {
kfree(name);
kfree(buf);
return ENOMEM;
}
char *temp = buf;
while (uargs[i] != NULL) {
length = 0;
len = strlen(uargs[i]) + 1;
act = len;
if ((len % 4) != 0) {
len = len - (len % 4) + 4;
}
result = copyinstr((const_userptr_t) uargs[i], temp,
(sizeof(char) * (strlen(uargs[i]) + 1)), &length);
if (result) {
kfree(name);
kfree(ptrbuf);
kfree(buf);
return EFAULT;
}
temp = temp + (strlen(uargs[i]) + 1);
while (act < len) {
*temp = '\0';
temp++;
act++;
}
i++;
}
argmax = i;
//Now proceeding as in runprogram
/* Open the file. */
result = vfs_open(name, O_RDONLY, 0, &v);
if (result) {
kfree(name);
kfree(ptrbuf);
kfree(buf);
return result;
}
/* We should be a new process. */
as_destroy(curproc->p_addrspace);
curproc->p_addrspace = NULL;
KASSERT(proc_getas() == NULL);
/* Create a new address space. */
curproc->p_addrspace = as_create();
if (curproc->p_addrspace == NULL) {
vfs_close(v);
kfree(name);
kfree(ptrbuf);
kfree(buf);
return ENOMEM;
}
/* Switch to it and activate it. */
proc_setas(curproc->p_addrspace);
as_activate();
/* Load the executable. */
result = load_elf(v, &entrypoint);
if (result) {
/* p_addrspace will go away when curproc is destroyed */
vfs_close(v);
kfree(name);
kfree(ptrbuf);
kfree(buf);
return result;
}
/* Done with the file now. */
vfs_close(v);
/* Define the user stack in the address space */
result = as_define_stack(curproc->p_addrspace, &stackptr);
if (result) {
/* p_addrspace will go away when curproc is destroyed */
kfree(name);
kfree(ptrbuf);
kfree(buf);
return result;
}
//Copying arguments to user space
i = 0;
temp = buf;
char *temp1 = buf;
while (i < argmax) {
length = 0;
len = 0;
while (*temp != '\0') {
temp++;
len++;
}
temp++;
len++;
if ((len % 4) != 0) {
temp = temp + 4 - (len % 4);
len = len - (len % 4) + 4;
}
stackptr = stackptr - len;
act = len;
result = copyout((const void *) (temp1), (userptr_t) stackptr, len);
if (result) {
kfree(name);
kfree(ptrbuf);
kfree(buf);
return EFAULT; //not sure whether to return this or result
}
temp1 = temp1 + (act);
ptrbuf[i] = (char *) stackptr;
i++;
}
stackptr = stackptr - 4 * sizeof(char);
//Copying the pointers
for (i = argmax - 1; i >= 0; i--) {
stackptr = stackptr - sizeof(char *);
result = copyout((const void *) (ptrbuf + i), (userptr_t) stackptr,
sizeof(char *));
if (result) {
kfree(name);
kfree(ptrbuf);
kfree(buf);
return EFAULT; //again, result or this?
}
}
kfree(name);
kfree(ptrbuf);
kfree(buf);
/* Warp to user mode. */
enter_new_process(argmax /*argc*/,
(userptr_t) stackptr /*userspace addr of argv*/,
NULL /*userspace addr of environment*/, stackptr, entrypoint);
/* enter_new_process does not return. */
panic("panic - execv, After enter_new_process\n");
return EINVAL;
}
int sys_exit(int code) {
//kprintf("exiting pid %d", curproc->pid);
struct proc * proc = curproc;
(void) proc;
curproc->isexited = true;
if (code == 0) {
curproc->exitcode = _MKWAIT_EXIT(code);
} else {
curproc->exitcode = _MKWAIT_SIG(code);
}
V(curproc->proc_sem);
thread_exit();
return 0;
}
int sys_sbrk(int amt, int *retval) {
struct addrspace * as = curproc->p_addrspace;
vaddr_t heap_top = curproc->p_addrspace->heap_top;
vaddr_t heap_bottom = curproc->p_addrspace->heap_bottom;
*retval = -1;
if (amt == 0) {
*retval = heap_top;
return 0;
}
if ((amt % 4) != 0) { //check if it's aligned by 4
return EINVAL;
}
if (amt < 0) { //heap size decreased
if ((long) heap_top + (long) amt < (long) heap_bottom) {
return EINVAL;
}
amt *= -1;
// vm_tlbshootdown_all();
if (amt >= PAGE_SIZE) {
for (unsigned i = ((int) (heap_top & PAGE_FRAME) - amt);
i < (heap_top & PAGE_FRAME); i = i + PAGE_SIZE) {
struct PTE *prev, *curr;
if (as->pte->vpn == i) {
curr = as->pte;
as->pte = as->pte->next;
if (swapping) {
if (curr->state == MEM) {
page_free(curr->ppn);
}
} else {
page_free(curr->ppn);
}
vm_tlbshootdownvaddr(curr->vpn);
if (swapping) {
lock_destroy(curr->pte_lock);
}
kfree(curr);
} else {
prev = as->pte;
for (curr = as->pte->next; curr != NULL; curr =
curr->next) {
if (curr->vpn == i) {
if (swapping) {
if (curr->state == MEM) {
page_free(curr->ppn);
}
} else {
page_free(curr->ppn);
}
vm_tlbshootdownvaddr(curr->vpn);
prev->next = curr->next;
if (swapping) {
lock_destroy(curr->pte_lock);
}
kfree(curr);
break;
}
prev = prev->next;
}
}
}
*retval = heap_top;
heap_top -= (amt & PAGE_FRAME);
} else {
*retval = heap_top;
heap_top -= (amt & PAGE_FRAME);
vm_tlbshootdownvaddr(heap_top);
}
} else {
if ((heap_top + amt) > (USERSTACK - MYVM_STACKPAGES * PAGE_SIZE)) {
return ENOMEM;
}
if ((long) amt >= (long) PAGE_SIZE) {
if ((long) amt > (long) (as->stack_ptr - as->heap_top)) {
return ENOMEM;
}
}
*retval = heap_top;
heap_top += amt;
}
curproc->p_addrspace->heap_top = heap_top;
return 0;
}
<file_sep>/Debug/userland/testbin/schedpong/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../userland/testbin/schedpong/grind.c \
../userland/testbin/schedpong/main.c \
../userland/testbin/schedpong/pong.c \
../userland/testbin/schedpong/results.c \
../userland/testbin/schedpong/think.c \
../userland/testbin/schedpong/usem.c
OBJS += \
./userland/testbin/schedpong/grind.o \
./userland/testbin/schedpong/main.o \
./userland/testbin/schedpong/pong.o \
./userland/testbin/schedpong/results.o \
./userland/testbin/schedpong/think.o \
./userland/testbin/schedpong/usem.o
C_DEPS += \
./userland/testbin/schedpong/grind.d \
./userland/testbin/schedpong/main.d \
./userland/testbin/schedpong/pong.d \
./userland/testbin/schedpong/results.d \
./userland/testbin/schedpong/think.d \
./userland/testbin/schedpong/usem.d
# Each subdirectory must supply rules for building sources it contributes
userland/testbin/schedpong/%.o: ../userland/testbin/schedpong/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/kern/include/kern/proc_syscalls.h
#include <kern/fcntl.h>
#include <limits.h>
#include <mips/trapframe.h>
extern struct proc *pt_proc[256];
extern struct lock *p_lock;
void pt_init(void);
pid_t insert_process_into_process_table(struct proc *newproc);
void sys__exit(int exitcode);
int sys_fork(struct trapframe *tf, int *retval);
int sys_execv(const char *program, char **uargs, int *retval);
int sys_getpid(int *retval);
pid_t
sys_waitpid(pid_t pid, int *status, int options, int *retval);
int sys_exit(pid_t pid);
int sys_sbrk(int amt, int *retval);
<file_sep>/Debug/kern/compile/DUMBVM/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../kern/compile/DUMBVM/.depend.__printf.c \
../kern/compile/DUMBVM/.depend.adddi3.c \
../kern/compile/DUMBVM/.depend.anddi3.c \
../kern/compile/DUMBVM/.depend.array.c \
../kern/compile/DUMBVM/.depend.arraytest.c \
../kern/compile/DUMBVM/.depend.ashldi3.c \
../kern/compile/DUMBVM/.depend.ashrdi3.c \
../kern/compile/DUMBVM/.depend.atoi.c \
../kern/compile/DUMBVM/.depend.autoconf.c \
../kern/compile/DUMBVM/.depend.beep.c \
../kern/compile/DUMBVM/.depend.beep_ltimer.c \
../kern/compile/DUMBVM/.depend.bitmap.c \
../kern/compile/DUMBVM/.depend.bitmaptest.c \
../kern/compile/DUMBVM/.depend.bswap.c \
../kern/compile/DUMBVM/.depend.bzero.c \
../kern/compile/DUMBVM/.depend.clock.c \
../kern/compile/DUMBVM/.depend.cmpdi2.c \
../kern/compile/DUMBVM/.depend.con_lser.c \
../kern/compile/DUMBVM/.depend.console.c \
../kern/compile/DUMBVM/.depend.copyinout.c \
../kern/compile/DUMBVM/.depend.cpu.c \
../kern/compile/DUMBVM/.depend.device.c \
../kern/compile/DUMBVM/.depend.devnull.c \
../kern/compile/DUMBVM/.depend.divdi3.c \
../kern/compile/DUMBVM/.depend.dumbvm.c \
../kern/compile/DUMBVM/.depend.emu.c \
../kern/compile/DUMBVM/.depend.emu_att.c \
../kern/compile/DUMBVM/.depend.fstest.c \
../kern/compile/DUMBVM/.depend.hmacunit.c \
../kern/compile/DUMBVM/.depend.iordi3.c \
../kern/compile/DUMBVM/.depend.kgets.c \
../kern/compile/DUMBVM/.depend.kmalloc.c \
../kern/compile/DUMBVM/.depend.kmalloctest.c \
../kern/compile/DUMBVM/.depend.kprintf.c \
../kern/compile/DUMBVM/.depend.lamebus.c \
../kern/compile/DUMBVM/.depend.lamebus_machdep.c \
../kern/compile/DUMBVM/.depend.lhd.c \
../kern/compile/DUMBVM/.depend.lhd_att.c \
../kern/compile/DUMBVM/.depend.lib.c \
../kern/compile/DUMBVM/.depend.loadelf.c \
../kern/compile/DUMBVM/.depend.lrandom.c \
../kern/compile/DUMBVM/.depend.lrandom_att.c \
../kern/compile/DUMBVM/.depend.lser.c \
../kern/compile/DUMBVM/.depend.lser_att.c \
../kern/compile/DUMBVM/.depend.lshldi3.c \
../kern/compile/DUMBVM/.depend.lshrdi3.c \
../kern/compile/DUMBVM/.depend.ltimer.c \
../kern/compile/DUMBVM/.depend.ltimer_att.c \
../kern/compile/DUMBVM/.depend.ltrace.c \
../kern/compile/DUMBVM/.depend.ltrace_att.c \
../kern/compile/DUMBVM/.depend.main.c \
../kern/compile/DUMBVM/.depend.memcpy.c \
../kern/compile/DUMBVM/.depend.memmove.c \
../kern/compile/DUMBVM/.depend.memset.c \
../kern/compile/DUMBVM/.depend.menu.c \
../kern/compile/DUMBVM/.depend.misc.c \
../kern/compile/DUMBVM/.depend.moddi3.c \
../kern/compile/DUMBVM/.depend.muldi3.c \
../kern/compile/DUMBVM/.depend.negdi2.c \
../kern/compile/DUMBVM/.depend.notdi2.c \
../kern/compile/DUMBVM/.depend.proc.c \
../kern/compile/DUMBVM/.depend.qdivrem.c \
../kern/compile/DUMBVM/.depend.ram.c \
../kern/compile/DUMBVM/.depend.random.c \
../kern/compile/DUMBVM/.depend.random_lrandom.c \
../kern/compile/DUMBVM/.depend.rtclock.c \
../kern/compile/DUMBVM/.depend.rtclock_ltimer.c \
../kern/compile/DUMBVM/.depend.runprogram.c \
../kern/compile/DUMBVM/.depend.rwtest.c \
../kern/compile/DUMBVM/.depend.secure.c \
../kern/compile/DUMBVM/.depend.semfs_fsops.c \
../kern/compile/DUMBVM/.depend.semfs_obj.c \
../kern/compile/DUMBVM/.depend.semfs_vnops.c \
../kern/compile/DUMBVM/.depend.semunit.c \
../kern/compile/DUMBVM/.depend.sfs_balloc.c \
../kern/compile/DUMBVM/.depend.sfs_bmap.c \
../kern/compile/DUMBVM/.depend.sfs_dir.c \
../kern/compile/DUMBVM/.depend.sfs_fsops.c \
../kern/compile/DUMBVM/.depend.sfs_inode.c \
../kern/compile/DUMBVM/.depend.sfs_io.c \
../kern/compile/DUMBVM/.depend.sfs_vnops.c \
../kern/compile/DUMBVM/.depend.sha256.c \
../kern/compile/DUMBVM/.depend.snprintf.c \
../kern/compile/DUMBVM/.depend.spinlock.c \
../kern/compile/DUMBVM/.depend.spl.c \
../kern/compile/DUMBVM/.depend.strcat.c \
../kern/compile/DUMBVM/.depend.strchr.c \
../kern/compile/DUMBVM/.depend.strcmp.c \
../kern/compile/DUMBVM/.depend.strcpy.c \
../kern/compile/DUMBVM/.depend.strlen.c \
../kern/compile/DUMBVM/.depend.strrchr.c \
../kern/compile/DUMBVM/.depend.strtok_r.c \
../kern/compile/DUMBVM/.depend.subdi3.c \
../kern/compile/DUMBVM/.depend.switchframe.c \
../kern/compile/DUMBVM/.depend.synch.c \
../kern/compile/DUMBVM/.depend.synchtest.c \
../kern/compile/DUMBVM/.depend.syscall.c \
../kern/compile/DUMBVM/.depend.test161.c \
../kern/compile/DUMBVM/.depend.thread.c \
../kern/compile/DUMBVM/.depend.thread_machdep.c \
../kern/compile/DUMBVM/.depend.threadlist.c \
../kern/compile/DUMBVM/.depend.threadlisttest.c \
../kern/compile/DUMBVM/.depend.threadtest.c \
../kern/compile/DUMBVM/.depend.time.c \
../kern/compile/DUMBVM/.depend.time_syscalls.c \
../kern/compile/DUMBVM/.depend.trap.c \
../kern/compile/DUMBVM/.depend.tt3.c \
../kern/compile/DUMBVM/.depend.ucmpdi2.c \
../kern/compile/DUMBVM/.depend.udivdi3.c \
../kern/compile/DUMBVM/.depend.uio.c \
../kern/compile/DUMBVM/.depend.umoddi3.c \
../kern/compile/DUMBVM/.depend.vfscwd.c \
../kern/compile/DUMBVM/.depend.vfsfail.c \
../kern/compile/DUMBVM/.depend.vfslist.c \
../kern/compile/DUMBVM/.depend.vfslookup.c \
../kern/compile/DUMBVM/.depend.vfspath.c \
../kern/compile/DUMBVM/.depend.vnode.c \
../kern/compile/DUMBVM/.depend.xordi3.c \
../kern/compile/DUMBVM/autoconf.c \
../kern/compile/DUMBVM/vers.c
O_SRCS += \
../kern/compile/DUMBVM/__printf.o \
../kern/compile/DUMBVM/adddi3.o \
../kern/compile/DUMBVM/anddi3.o \
../kern/compile/DUMBVM/array.o \
../kern/compile/DUMBVM/arraytest.o \
../kern/compile/DUMBVM/ashldi3.o \
../kern/compile/DUMBVM/ashrdi3.o \
../kern/compile/DUMBVM/atoi.o \
../kern/compile/DUMBVM/autoconf.o \
../kern/compile/DUMBVM/beep.o \
../kern/compile/DUMBVM/beep_ltimer.o \
../kern/compile/DUMBVM/bitmap.o \
../kern/compile/DUMBVM/bitmaptest.o \
../kern/compile/DUMBVM/bswap.o \
../kern/compile/DUMBVM/bzero.o \
../kern/compile/DUMBVM/cache-mips161.o \
../kern/compile/DUMBVM/clock.o \
../kern/compile/DUMBVM/cmpdi2.o \
../kern/compile/DUMBVM/con_lser.o \
../kern/compile/DUMBVM/console.o \
../kern/compile/DUMBVM/copyinout.o \
../kern/compile/DUMBVM/cpu.o \
../kern/compile/DUMBVM/device.o \
../kern/compile/DUMBVM/devnull.o \
../kern/compile/DUMBVM/divdi3.o \
../kern/compile/DUMBVM/dumbvm.o \
../kern/compile/DUMBVM/emu.o \
../kern/compile/DUMBVM/emu_att.o \
../kern/compile/DUMBVM/exception-mips1.o \
../kern/compile/DUMBVM/fstest.o \
../kern/compile/DUMBVM/hmacunit.o \
../kern/compile/DUMBVM/iordi3.o \
../kern/compile/DUMBVM/kgets.o \
../kern/compile/DUMBVM/kmalloc.o \
../kern/compile/DUMBVM/kmalloctest.o \
../kern/compile/DUMBVM/kprintf.o \
../kern/compile/DUMBVM/lamebus.o \
../kern/compile/DUMBVM/lamebus_machdep.o \
../kern/compile/DUMBVM/lhd.o \
../kern/compile/DUMBVM/lhd_att.o \
../kern/compile/DUMBVM/lib.o \
../kern/compile/DUMBVM/loadelf.o \
../kern/compile/DUMBVM/lrandom.o \
../kern/compile/DUMBVM/lrandom_att.o \
../kern/compile/DUMBVM/lser.o \
../kern/compile/DUMBVM/lser_att.o \
../kern/compile/DUMBVM/lshldi3.o \
../kern/compile/DUMBVM/lshrdi3.o \
../kern/compile/DUMBVM/ltimer.o \
../kern/compile/DUMBVM/ltimer_att.o \
../kern/compile/DUMBVM/ltrace.o \
../kern/compile/DUMBVM/ltrace_att.o \
../kern/compile/DUMBVM/main.o \
../kern/compile/DUMBVM/memcpy.o \
../kern/compile/DUMBVM/memmove.o \
../kern/compile/DUMBVM/memset.o \
../kern/compile/DUMBVM/menu.o \
../kern/compile/DUMBVM/misc.o \
../kern/compile/DUMBVM/moddi3.o \
../kern/compile/DUMBVM/muldi3.o \
../kern/compile/DUMBVM/negdi2.o \
../kern/compile/DUMBVM/notdi2.o \
../kern/compile/DUMBVM/proc.o \
../kern/compile/DUMBVM/qdivrem.o \
../kern/compile/DUMBVM/ram.o \
../kern/compile/DUMBVM/random.o \
../kern/compile/DUMBVM/random_lrandom.o \
../kern/compile/DUMBVM/rtclock.o \
../kern/compile/DUMBVM/rtclock_ltimer.o \
../kern/compile/DUMBVM/runprogram.o \
../kern/compile/DUMBVM/rwtest.o \
../kern/compile/DUMBVM/secure.o \
../kern/compile/DUMBVM/semfs_fsops.o \
../kern/compile/DUMBVM/semfs_obj.o \
../kern/compile/DUMBVM/semfs_vnops.o \
../kern/compile/DUMBVM/semunit.o \
../kern/compile/DUMBVM/setjmp.o \
../kern/compile/DUMBVM/sfs_balloc.o \
../kern/compile/DUMBVM/sfs_bmap.o \
../kern/compile/DUMBVM/sfs_dir.o \
../kern/compile/DUMBVM/sfs_fsops.o \
../kern/compile/DUMBVM/sfs_inode.o \
../kern/compile/DUMBVM/sfs_io.o \
../kern/compile/DUMBVM/sfs_vnops.o \
../kern/compile/DUMBVM/sha256.o \
../kern/compile/DUMBVM/snprintf.o \
../kern/compile/DUMBVM/spinlock.o \
../kern/compile/DUMBVM/spl.o \
../kern/compile/DUMBVM/start.o \
../kern/compile/DUMBVM/strcat.o \
../kern/compile/DUMBVM/strchr.o \
../kern/compile/DUMBVM/strcmp.o \
../kern/compile/DUMBVM/strcpy.o \
../kern/compile/DUMBVM/strlen.o \
../kern/compile/DUMBVM/strrchr.o \
../kern/compile/DUMBVM/strtok_r.o \
../kern/compile/DUMBVM/subdi3.o \
../kern/compile/DUMBVM/switch.o \
../kern/compile/DUMBVM/switchframe.o \
../kern/compile/DUMBVM/synch.o \
../kern/compile/DUMBVM/synchtest.o \
../kern/compile/DUMBVM/syscall.o \
../kern/compile/DUMBVM/test161.o \
../kern/compile/DUMBVM/thread.o \
../kern/compile/DUMBVM/thread_machdep.o \
../kern/compile/DUMBVM/threadlist.o \
../kern/compile/DUMBVM/threadlisttest.o \
../kern/compile/DUMBVM/threadstart.o \
../kern/compile/DUMBVM/threadtest.o \
../kern/compile/DUMBVM/time.o \
../kern/compile/DUMBVM/time_syscalls.o \
../kern/compile/DUMBVM/tlb-mips161.o \
../kern/compile/DUMBVM/trap.o \
../kern/compile/DUMBVM/tt3.o \
../kern/compile/DUMBVM/ucmpdi2.o \
../kern/compile/DUMBVM/udivdi3.o \
../kern/compile/DUMBVM/uio.o \
../kern/compile/DUMBVM/umoddi3.o \
../kern/compile/DUMBVM/vers.o \
../kern/compile/DUMBVM/vfscwd.o \
../kern/compile/DUMBVM/vfsfail.o \
../kern/compile/DUMBVM/vfslist.o \
../kern/compile/DUMBVM/vfslookup.o \
../kern/compile/DUMBVM/vfspath.o \
../kern/compile/DUMBVM/vnode.o \
../kern/compile/DUMBVM/xordi3.o
S_UPPER_SRCS += \
../kern/compile/DUMBVM/.depend.cache-mips161.S \
../kern/compile/DUMBVM/.depend.exception-mips1.S \
../kern/compile/DUMBVM/.depend.setjmp.S \
../kern/compile/DUMBVM/.depend.start.S \
../kern/compile/DUMBVM/.depend.switch.S \
../kern/compile/DUMBVM/.depend.threadstart.S \
../kern/compile/DUMBVM/.depend.tlb-mips161.S
OBJS += \
./kern/compile/DUMBVM/.depend.__printf.o \
./kern/compile/DUMBVM/.depend.adddi3.o \
./kern/compile/DUMBVM/.depend.anddi3.o \
./kern/compile/DUMBVM/.depend.array.o \
./kern/compile/DUMBVM/.depend.arraytest.o \
./kern/compile/DUMBVM/.depend.ashldi3.o \
./kern/compile/DUMBVM/.depend.ashrdi3.o \
./kern/compile/DUMBVM/.depend.atoi.o \
./kern/compile/DUMBVM/.depend.autoconf.o \
./kern/compile/DUMBVM/.depend.beep.o \
./kern/compile/DUMBVM/.depend.beep_ltimer.o \
./kern/compile/DUMBVM/.depend.bitmap.o \
./kern/compile/DUMBVM/.depend.bitmaptest.o \
./kern/compile/DUMBVM/.depend.bswap.o \
./kern/compile/DUMBVM/.depend.bzero.o \
./kern/compile/DUMBVM/.depend.cache-mips161.o \
./kern/compile/DUMBVM/.depend.clock.o \
./kern/compile/DUMBVM/.depend.cmpdi2.o \
./kern/compile/DUMBVM/.depend.con_lser.o \
./kern/compile/DUMBVM/.depend.console.o \
./kern/compile/DUMBVM/.depend.copyinout.o \
./kern/compile/DUMBVM/.depend.cpu.o \
./kern/compile/DUMBVM/.depend.device.o \
./kern/compile/DUMBVM/.depend.devnull.o \
./kern/compile/DUMBVM/.depend.divdi3.o \
./kern/compile/DUMBVM/.depend.dumbvm.o \
./kern/compile/DUMBVM/.depend.emu.o \
./kern/compile/DUMBVM/.depend.emu_att.o \
./kern/compile/DUMBVM/.depend.exception-mips1.o \
./kern/compile/DUMBVM/.depend.fstest.o \
./kern/compile/DUMBVM/.depend.hmacunit.o \
./kern/compile/DUMBVM/.depend.iordi3.o \
./kern/compile/DUMBVM/.depend.kgets.o \
./kern/compile/DUMBVM/.depend.kmalloc.o \
./kern/compile/DUMBVM/.depend.kmalloctest.o \
./kern/compile/DUMBVM/.depend.kprintf.o \
./kern/compile/DUMBVM/.depend.lamebus.o \
./kern/compile/DUMBVM/.depend.lamebus_machdep.o \
./kern/compile/DUMBVM/.depend.lhd.o \
./kern/compile/DUMBVM/.depend.lhd_att.o \
./kern/compile/DUMBVM/.depend.lib.o \
./kern/compile/DUMBVM/.depend.loadelf.o \
./kern/compile/DUMBVM/.depend.lrandom.o \
./kern/compile/DUMBVM/.depend.lrandom_att.o \
./kern/compile/DUMBVM/.depend.lser.o \
./kern/compile/DUMBVM/.depend.lser_att.o \
./kern/compile/DUMBVM/.depend.lshldi3.o \
./kern/compile/DUMBVM/.depend.lshrdi3.o \
./kern/compile/DUMBVM/.depend.ltimer.o \
./kern/compile/DUMBVM/.depend.ltimer_att.o \
./kern/compile/DUMBVM/.depend.ltrace.o \
./kern/compile/DUMBVM/.depend.ltrace_att.o \
./kern/compile/DUMBVM/.depend.main.o \
./kern/compile/DUMBVM/.depend.memcpy.o \
./kern/compile/DUMBVM/.depend.memmove.o \
./kern/compile/DUMBVM/.depend.memset.o \
./kern/compile/DUMBVM/.depend.menu.o \
./kern/compile/DUMBVM/.depend.misc.o \
./kern/compile/DUMBVM/.depend.moddi3.o \
./kern/compile/DUMBVM/.depend.muldi3.o \
./kern/compile/DUMBVM/.depend.negdi2.o \
./kern/compile/DUMBVM/.depend.notdi2.o \
./kern/compile/DUMBVM/.depend.proc.o \
./kern/compile/DUMBVM/.depend.qdivrem.o \
./kern/compile/DUMBVM/.depend.ram.o \
./kern/compile/DUMBVM/.depend.random.o \
./kern/compile/DUMBVM/.depend.random_lrandom.o \
./kern/compile/DUMBVM/.depend.rtclock.o \
./kern/compile/DUMBVM/.depend.rtclock_ltimer.o \
./kern/compile/DUMBVM/.depend.runprogram.o \
./kern/compile/DUMBVM/.depend.rwtest.o \
./kern/compile/DUMBVM/.depend.secure.o \
./kern/compile/DUMBVM/.depend.semfs_fsops.o \
./kern/compile/DUMBVM/.depend.semfs_obj.o \
./kern/compile/DUMBVM/.depend.semfs_vnops.o \
./kern/compile/DUMBVM/.depend.semunit.o \
./kern/compile/DUMBVM/.depend.setjmp.o \
./kern/compile/DUMBVM/.depend.sfs_balloc.o \
./kern/compile/DUMBVM/.depend.sfs_bmap.o \
./kern/compile/DUMBVM/.depend.sfs_dir.o \
./kern/compile/DUMBVM/.depend.sfs_fsops.o \
./kern/compile/DUMBVM/.depend.sfs_inode.o \
./kern/compile/DUMBVM/.depend.sfs_io.o \
./kern/compile/DUMBVM/.depend.sfs_vnops.o \
./kern/compile/DUMBVM/.depend.sha256.o \
./kern/compile/DUMBVM/.depend.snprintf.o \
./kern/compile/DUMBVM/.depend.spinlock.o \
./kern/compile/DUMBVM/.depend.spl.o \
./kern/compile/DUMBVM/.depend.start.o \
./kern/compile/DUMBVM/.depend.strcat.o \
./kern/compile/DUMBVM/.depend.strchr.o \
./kern/compile/DUMBVM/.depend.strcmp.o \
./kern/compile/DUMBVM/.depend.strcpy.o \
./kern/compile/DUMBVM/.depend.strlen.o \
./kern/compile/DUMBVM/.depend.strrchr.o \
./kern/compile/DUMBVM/.depend.strtok_r.o \
./kern/compile/DUMBVM/.depend.subdi3.o \
./kern/compile/DUMBVM/.depend.switch.o \
./kern/compile/DUMBVM/.depend.switchframe.o \
./kern/compile/DUMBVM/.depend.synch.o \
./kern/compile/DUMBVM/.depend.synchtest.o \
./kern/compile/DUMBVM/.depend.syscall.o \
./kern/compile/DUMBVM/.depend.test161.o \
./kern/compile/DUMBVM/.depend.thread.o \
./kern/compile/DUMBVM/.depend.thread_machdep.o \
./kern/compile/DUMBVM/.depend.threadlist.o \
./kern/compile/DUMBVM/.depend.threadlisttest.o \
./kern/compile/DUMBVM/.depend.threadstart.o \
./kern/compile/DUMBVM/.depend.threadtest.o \
./kern/compile/DUMBVM/.depend.time.o \
./kern/compile/DUMBVM/.depend.time_syscalls.o \
./kern/compile/DUMBVM/.depend.tlb-mips161.o \
./kern/compile/DUMBVM/.depend.trap.o \
./kern/compile/DUMBVM/.depend.tt3.o \
./kern/compile/DUMBVM/.depend.ucmpdi2.o \
./kern/compile/DUMBVM/.depend.udivdi3.o \
./kern/compile/DUMBVM/.depend.uio.o \
./kern/compile/DUMBVM/.depend.umoddi3.o \
./kern/compile/DUMBVM/.depend.vfscwd.o \
./kern/compile/DUMBVM/.depend.vfsfail.o \
./kern/compile/DUMBVM/.depend.vfslist.o \
./kern/compile/DUMBVM/.depend.vfslookup.o \
./kern/compile/DUMBVM/.depend.vfspath.o \
./kern/compile/DUMBVM/.depend.vnode.o \
./kern/compile/DUMBVM/.depend.xordi3.o \
./kern/compile/DUMBVM/autoconf.o \
./kern/compile/DUMBVM/vers.o
C_DEPS += \
./kern/compile/DUMBVM/.depend.__printf.d \
./kern/compile/DUMBVM/.depend.adddi3.d \
./kern/compile/DUMBVM/.depend.anddi3.d \
./kern/compile/DUMBVM/.depend.array.d \
./kern/compile/DUMBVM/.depend.arraytest.d \
./kern/compile/DUMBVM/.depend.ashldi3.d \
./kern/compile/DUMBVM/.depend.ashrdi3.d \
./kern/compile/DUMBVM/.depend.atoi.d \
./kern/compile/DUMBVM/.depend.autoconf.d \
./kern/compile/DUMBVM/.depend.beep.d \
./kern/compile/DUMBVM/.depend.beep_ltimer.d \
./kern/compile/DUMBVM/.depend.bitmap.d \
./kern/compile/DUMBVM/.depend.bitmaptest.d \
./kern/compile/DUMBVM/.depend.bswap.d \
./kern/compile/DUMBVM/.depend.bzero.d \
./kern/compile/DUMBVM/.depend.clock.d \
./kern/compile/DUMBVM/.depend.cmpdi2.d \
./kern/compile/DUMBVM/.depend.con_lser.d \
./kern/compile/DUMBVM/.depend.console.d \
./kern/compile/DUMBVM/.depend.copyinout.d \
./kern/compile/DUMBVM/.depend.cpu.d \
./kern/compile/DUMBVM/.depend.device.d \
./kern/compile/DUMBVM/.depend.devnull.d \
./kern/compile/DUMBVM/.depend.divdi3.d \
./kern/compile/DUMBVM/.depend.dumbvm.d \
./kern/compile/DUMBVM/.depend.emu.d \
./kern/compile/DUMBVM/.depend.emu_att.d \
./kern/compile/DUMBVM/.depend.fstest.d \
./kern/compile/DUMBVM/.depend.hmacunit.d \
./kern/compile/DUMBVM/.depend.iordi3.d \
./kern/compile/DUMBVM/.depend.kgets.d \
./kern/compile/DUMBVM/.depend.kmalloc.d \
./kern/compile/DUMBVM/.depend.kmalloctest.d \
./kern/compile/DUMBVM/.depend.kprintf.d \
./kern/compile/DUMBVM/.depend.lamebus.d \
./kern/compile/DUMBVM/.depend.lamebus_machdep.d \
./kern/compile/DUMBVM/.depend.lhd.d \
./kern/compile/DUMBVM/.depend.lhd_att.d \
./kern/compile/DUMBVM/.depend.lib.d \
./kern/compile/DUMBVM/.depend.loadelf.d \
./kern/compile/DUMBVM/.depend.lrandom.d \
./kern/compile/DUMBVM/.depend.lrandom_att.d \
./kern/compile/DUMBVM/.depend.lser.d \
./kern/compile/DUMBVM/.depend.lser_att.d \
./kern/compile/DUMBVM/.depend.lshldi3.d \
./kern/compile/DUMBVM/.depend.lshrdi3.d \
./kern/compile/DUMBVM/.depend.ltimer.d \
./kern/compile/DUMBVM/.depend.ltimer_att.d \
./kern/compile/DUMBVM/.depend.ltrace.d \
./kern/compile/DUMBVM/.depend.ltrace_att.d \
./kern/compile/DUMBVM/.depend.main.d \
./kern/compile/DUMBVM/.depend.memcpy.d \
./kern/compile/DUMBVM/.depend.memmove.d \
./kern/compile/DUMBVM/.depend.memset.d \
./kern/compile/DUMBVM/.depend.menu.d \
./kern/compile/DUMBVM/.depend.misc.d \
./kern/compile/DUMBVM/.depend.moddi3.d \
./kern/compile/DUMBVM/.depend.muldi3.d \
./kern/compile/DUMBVM/.depend.negdi2.d \
./kern/compile/DUMBVM/.depend.notdi2.d \
./kern/compile/DUMBVM/.depend.proc.d \
./kern/compile/DUMBVM/.depend.qdivrem.d \
./kern/compile/DUMBVM/.depend.ram.d \
./kern/compile/DUMBVM/.depend.random.d \
./kern/compile/DUMBVM/.depend.random_lrandom.d \
./kern/compile/DUMBVM/.depend.rtclock.d \
./kern/compile/DUMBVM/.depend.rtclock_ltimer.d \
./kern/compile/DUMBVM/.depend.runprogram.d \
./kern/compile/DUMBVM/.depend.rwtest.d \
./kern/compile/DUMBVM/.depend.secure.d \
./kern/compile/DUMBVM/.depend.semfs_fsops.d \
./kern/compile/DUMBVM/.depend.semfs_obj.d \
./kern/compile/DUMBVM/.depend.semfs_vnops.d \
./kern/compile/DUMBVM/.depend.semunit.d \
./kern/compile/DUMBVM/.depend.sfs_balloc.d \
./kern/compile/DUMBVM/.depend.sfs_bmap.d \
./kern/compile/DUMBVM/.depend.sfs_dir.d \
./kern/compile/DUMBVM/.depend.sfs_fsops.d \
./kern/compile/DUMBVM/.depend.sfs_inode.d \
./kern/compile/DUMBVM/.depend.sfs_io.d \
./kern/compile/DUMBVM/.depend.sfs_vnops.d \
./kern/compile/DUMBVM/.depend.sha256.d \
./kern/compile/DUMBVM/.depend.snprintf.d \
./kern/compile/DUMBVM/.depend.spinlock.d \
./kern/compile/DUMBVM/.depend.spl.d \
./kern/compile/DUMBVM/.depend.strcat.d \
./kern/compile/DUMBVM/.depend.strchr.d \
./kern/compile/DUMBVM/.depend.strcmp.d \
./kern/compile/DUMBVM/.depend.strcpy.d \
./kern/compile/DUMBVM/.depend.strlen.d \
./kern/compile/DUMBVM/.depend.strrchr.d \
./kern/compile/DUMBVM/.depend.strtok_r.d \
./kern/compile/DUMBVM/.depend.subdi3.d \
./kern/compile/DUMBVM/.depend.switchframe.d \
./kern/compile/DUMBVM/.depend.synch.d \
./kern/compile/DUMBVM/.depend.synchtest.d \
./kern/compile/DUMBVM/.depend.syscall.d \
./kern/compile/DUMBVM/.depend.test161.d \
./kern/compile/DUMBVM/.depend.thread.d \
./kern/compile/DUMBVM/.depend.thread_machdep.d \
./kern/compile/DUMBVM/.depend.threadlist.d \
./kern/compile/DUMBVM/.depend.threadlisttest.d \
./kern/compile/DUMBVM/.depend.threadtest.d \
./kern/compile/DUMBVM/.depend.time.d \
./kern/compile/DUMBVM/.depend.time_syscalls.d \
./kern/compile/DUMBVM/.depend.trap.d \
./kern/compile/DUMBVM/.depend.tt3.d \
./kern/compile/DUMBVM/.depend.ucmpdi2.d \
./kern/compile/DUMBVM/.depend.udivdi3.d \
./kern/compile/DUMBVM/.depend.uio.d \
./kern/compile/DUMBVM/.depend.umoddi3.d \
./kern/compile/DUMBVM/.depend.vfscwd.d \
./kern/compile/DUMBVM/.depend.vfsfail.d \
./kern/compile/DUMBVM/.depend.vfslist.d \
./kern/compile/DUMBVM/.depend.vfslookup.d \
./kern/compile/DUMBVM/.depend.vfspath.d \
./kern/compile/DUMBVM/.depend.vnode.d \
./kern/compile/DUMBVM/.depend.xordi3.d \
./kern/compile/DUMBVM/autoconf.d \
./kern/compile/DUMBVM/vers.d
# Each subdirectory must supply rules for building sources it contributes
kern/compile/DUMBVM/%.o: ../kern/compile/DUMBVM/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
kern/compile/DUMBVM/%.o: ../kern/compile/DUMBVM/%.S
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Assembler'
as -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/Debug/userland/testbin/badcall/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../userland/testbin/badcall/bad_chdir.c \
../userland/testbin/badcall/bad_close.c \
../userland/testbin/badcall/bad_dup2.c \
../userland/testbin/badcall/bad_execv.c \
../userland/testbin/badcall/bad_fsync.c \
../userland/testbin/badcall/bad_ftruncate.c \
../userland/testbin/badcall/bad_getcwd.c \
../userland/testbin/badcall/bad_getdirentry.c \
../userland/testbin/badcall/bad_ioctl.c \
../userland/testbin/badcall/bad_link.c \
../userland/testbin/badcall/bad_lseek.c \
../userland/testbin/badcall/bad_mkdir.c \
../userland/testbin/badcall/bad_open.c \
../userland/testbin/badcall/bad_pipe.c \
../userland/testbin/badcall/bad_read.c \
../userland/testbin/badcall/bad_readlink.c \
../userland/testbin/badcall/bad_reboot.c \
../userland/testbin/badcall/bad_remove.c \
../userland/testbin/badcall/bad_rename.c \
../userland/testbin/badcall/bad_rmdir.c \
../userland/testbin/badcall/bad_sbrk.c \
../userland/testbin/badcall/bad_stat.c \
../userland/testbin/badcall/bad_symlink.c \
../userland/testbin/badcall/bad_time.c \
../userland/testbin/badcall/bad_waitpid.c \
../userland/testbin/badcall/bad_write.c \
../userland/testbin/badcall/common_buf.c \
../userland/testbin/badcall/common_fds.c \
../userland/testbin/badcall/common_path.c \
../userland/testbin/badcall/driver.c \
../userland/testbin/badcall/report.c
OBJS += \
./userland/testbin/badcall/bad_chdir.o \
./userland/testbin/badcall/bad_close.o \
./userland/testbin/badcall/bad_dup2.o \
./userland/testbin/badcall/bad_execv.o \
./userland/testbin/badcall/bad_fsync.o \
./userland/testbin/badcall/bad_ftruncate.o \
./userland/testbin/badcall/bad_getcwd.o \
./userland/testbin/badcall/bad_getdirentry.o \
./userland/testbin/badcall/bad_ioctl.o \
./userland/testbin/badcall/bad_link.o \
./userland/testbin/badcall/bad_lseek.o \
./userland/testbin/badcall/bad_mkdir.o \
./userland/testbin/badcall/bad_open.o \
./userland/testbin/badcall/bad_pipe.o \
./userland/testbin/badcall/bad_read.o \
./userland/testbin/badcall/bad_readlink.o \
./userland/testbin/badcall/bad_reboot.o \
./userland/testbin/badcall/bad_remove.o \
./userland/testbin/badcall/bad_rename.o \
./userland/testbin/badcall/bad_rmdir.o \
./userland/testbin/badcall/bad_sbrk.o \
./userland/testbin/badcall/bad_stat.o \
./userland/testbin/badcall/bad_symlink.o \
./userland/testbin/badcall/bad_time.o \
./userland/testbin/badcall/bad_waitpid.o \
./userland/testbin/badcall/bad_write.o \
./userland/testbin/badcall/common_buf.o \
./userland/testbin/badcall/common_fds.o \
./userland/testbin/badcall/common_path.o \
./userland/testbin/badcall/driver.o \
./userland/testbin/badcall/report.o
C_DEPS += \
./userland/testbin/badcall/bad_chdir.d \
./userland/testbin/badcall/bad_close.d \
./userland/testbin/badcall/bad_dup2.d \
./userland/testbin/badcall/bad_execv.d \
./userland/testbin/badcall/bad_fsync.d \
./userland/testbin/badcall/bad_ftruncate.d \
./userland/testbin/badcall/bad_getcwd.d \
./userland/testbin/badcall/bad_getdirentry.d \
./userland/testbin/badcall/bad_ioctl.d \
./userland/testbin/badcall/bad_link.d \
./userland/testbin/badcall/bad_lseek.d \
./userland/testbin/badcall/bad_mkdir.d \
./userland/testbin/badcall/bad_open.d \
./userland/testbin/badcall/bad_pipe.d \
./userland/testbin/badcall/bad_read.d \
./userland/testbin/badcall/bad_readlink.d \
./userland/testbin/badcall/bad_reboot.d \
./userland/testbin/badcall/bad_remove.d \
./userland/testbin/badcall/bad_rename.d \
./userland/testbin/badcall/bad_rmdir.d \
./userland/testbin/badcall/bad_sbrk.d \
./userland/testbin/badcall/bad_stat.d \
./userland/testbin/badcall/bad_symlink.d \
./userland/testbin/badcall/bad_time.d \
./userland/testbin/badcall/bad_waitpid.d \
./userland/testbin/badcall/bad_write.d \
./userland/testbin/badcall/common_buf.d \
./userland/testbin/badcall/common_fds.d \
./userland/testbin/badcall/common_path.d \
./userland/testbin/badcall/driver.d \
./userland/testbin/badcall/report.d
# Each subdirectory must supply rules for building sources it contributes
userland/testbin/badcall/%.o: ../userland/testbin/badcall/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/Debug/kern/arch/mips/thread/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../kern/arch/mips/thread/cpu.c \
../kern/arch/mips/thread/switchframe.c \
../kern/arch/mips/thread/thread_machdep.c
S_UPPER_SRCS += \
../kern/arch/mips/thread/switch.S \
../kern/arch/mips/thread/threadstart.S
OBJS += \
./kern/arch/mips/thread/cpu.o \
./kern/arch/mips/thread/switch.o \
./kern/arch/mips/thread/switchframe.o \
./kern/arch/mips/thread/thread_machdep.o \
./kern/arch/mips/thread/threadstart.o
C_DEPS += \
./kern/arch/mips/thread/cpu.d \
./kern/arch/mips/thread/switchframe.d \
./kern/arch/mips/thread/thread_machdep.d
# Each subdirectory must supply rules for building sources it contributes
kern/arch/mips/thread/%.o: ../kern/arch/mips/thread/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
kern/arch/mips/thread/%.o: ../kern/arch/mips/thread/%.S
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Assembler'
as -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/kern/vm/myvm.c
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004, 2005, 2008, 2009
* The President and Fellows of Harvard College.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the 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 UNIVERSITY 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 UNIVERSITY 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.
*/
#include <types.h>
#include <kern/errno.h>
#include <lib.h>
#include <spl.h>
#include <cpu.h>
#include <proc.h>
#include <current.h>
#include <mips/tlb.h>
#include <addrspace.h>
#include <vm.h>
#include <spl.h>
#include <kern/stat.h>
#include <vnode.h>
#include <vfs.h>
#include <bitmap.h>
#include <uio.h>
#include <synch.h>
void vm_bootstrap(void) {
last = ram_getsize();
first = ram_getfirstfree();
num_pages = last/PAGE_SIZE;
coremap_size = num_pages * sizeof(struct coremap_entry);
coremap = (struct coremap_entry *) PADDR_TO_KVADDR(first);
first = first + coremap_size; //change first to the address after the coremap allocation
first = ROUNDUP(first, PAGE_SIZE);
first_free_addr = first / PAGE_SIZE;
usedBytes = 0;
for(unsigned i = 0; i<first_free_addr; i++) {
coremap[i].state = FIXED;
coremap[i].size = 1;
coremap[i].pte_ptr = NULL;
coremap[i].busy = 1;
coremap[i].clock = false;
coremap[i].cpu_num = -1;
}
for (unsigned i = first_free_addr; i < num_pages; i++) {
coremap[i].state = FREE;
coremap[i].size = 1;
coremap[i].pte_ptr = NULL;
coremap[i].busy = 0;
coremap[i].clock = false;
coremap[i].cpu_num = -1;
}
spinlock_init(&coremap_spinlock);
spinlock_init(&tlb_spinlock);
}
/* Allocate/free some kernel-space virtual pages */
vaddr_t alloc_kpages(unsigned npages) {
int page_ind;
vaddr_t returner;
spinlock_acquire(&coremap_spinlock);
//check for a free space
for (unsigned i = first_free_addr; i < num_pages; i++) {
int flag = 1;
if (coremap[i].state == FREE && ((i + npages) < num_pages)) {
//free space found. Check if next nPages are also free
for (unsigned j = 0; j < npages; j++) {
if (coremap[i + j].state == FREE) { ///1 is free
} else {//next nPages are not free. break to start of outer for loop
flag = 0;
break;
}
}
if (flag == 0) {
continue;
}
//npages of free space found.
coremap[i].state = FIXED;
coremap[i].size = npages;
coremap[i].busy = 0;
coremap[i].pte_ptr = NULL;
coremap[i].clock = false;
coremap[i].cpu_num = -1;
for (unsigned j = 1; j < npages; j++) {
coremap[i + j].state = FIXED;
coremap[i + j].busy = 0;
coremap[i + j].size = 1;
coremap[i + j].pte_ptr = NULL;
coremap[i + j].clock = false;
coremap[i + j].cpu_num = -1;
}
bzero((void *) PADDR_TO_KVADDR(i * PAGE_SIZE), PAGE_SIZE * npages);
usedBytes = usedBytes + PAGE_SIZE * npages;
spinlock_release(&coremap_spinlock);
returner = PADDR_TO_KVADDR(PAGE_SIZE * i);
return returner;
}
}
//If FREE pages not found, swapout pages
if (swapping) {
if (npages <= 1) {
page_ind = evict();
coremap[page_ind].state = FIXED;
coremap[page_ind].busy = 0;
coremap[page_ind].size = npages;
coremap[page_ind].pte_ptr = NULL;
coremap[page_ind].clock = false;
coremap[page_ind].cpu_num = -1;
for (unsigned j = 1; j < npages; j++) {
coremap[page_ind + j].state = FIXED;
coremap[page_ind + j].busy = 0;
coremap[page_ind + j].size = 1;
coremap[page_ind + j].pte_ptr = NULL;
coremap[page_ind + j].clock = false;
coremap[page_ind + j].cpu_num = -1;
}
bzero((void *) PADDR_TO_KVADDR(page_ind * PAGE_SIZE),
PAGE_SIZE * npages);
spinlock_release(&coremap_spinlock);
returner = PADDR_TO_KVADDR(PAGE_SIZE * page_ind);
return returner;
} else if (npages > 1) {
for (unsigned i = first_free_addr; i < num_pages; i++) {
int flag = 1;
if (coremap[i].state == DIRTY && ((i + npages) < num_pages)) {
for (unsigned j = 0; j < npages; j++) {
if (coremap[i + j].state == DIRTY) {
} else {
flag = 0;
break;
}
}
if (flag == 0) {
continue;
}
//swapout
for (unsigned j = 0; j < npages; j++) {
paddr_t paddr = PAGE_SIZE * (i + j);
vm_tlbshootdownvaddr(coremap[i + j].pte_ptr->vpn);
spinlock_release(&coremap_spinlock);
// vm_tlbshootdownvaddr_for_all_cpus(
// coremap[i + j].pte_ptr->vpn);
if(coremap[i + j].cpu_num > -1){
vm_tlbshootdownvaddr_for_specific_cpu(coremap[i + j].pte_ptr->vpn, coremap[i + j].cpu_num);
}
lock_acquire(coremap[i + j].pte_ptr->pte_lock);
swapout(coremap[i + j].pte_ptr->swapdisk_pos, paddr);
spinlock_acquire(&coremap_spinlock);
coremap[i + j].pte_ptr->state = DISK;
lock_release(coremap[i + j].pte_ptr->pte_lock);
}
coremap[i].state = FIXED;
coremap[i].busy = 0;
coremap[i].size = npages;
coremap[i].pte_ptr = NULL;
coremap[i].clock = false;
coremap[i].cpu_num = -1;
for (unsigned j = 1; j < npages; j++) {
coremap[i + j].state = FIXED;
coremap[i + j].busy = 0;
coremap[i + j].size = 1;
coremap[i + j].pte_ptr = NULL;
coremap[i + j].clock = false;
coremap[i].cpu_num = -1;
}
bzero((void *) PADDR_TO_KVADDR(i * PAGE_SIZE),
PAGE_SIZE * npages);
spinlock_release(&coremap_spinlock);
returner = PADDR_TO_KVADDR(PAGE_SIZE * i);
return returner;
}
}
panic("\nCouldn't find continuous n pages to swapout in allockpages!");
return 0;
}
return 0;
} else {
spinlock_release(&coremap_spinlock);
return 0;
}
}
void free_kpages(vaddr_t addr) {
paddr_t paddr = KVADDR_TO_PADDR(addr) & PAGE_FRAME;
int i = paddr/PAGE_SIZE;
int index = 0;
int temp = coremap[i].size;
for (int j = i; j < i + temp; j++) {
// vm_tlbshootdownvaddr_for_all_cpus(addr + (index * PAGE_SIZE));
if(coremap[j].cpu_num > -1){
vm_tlbshootdownvaddr_for_specific_cpu(addr + (index * PAGE_SIZE), coremap[j].cpu_num);
}
index++;
}
index = 0;
spinlock_acquire(&coremap_spinlock);
for (int j = i; j < i + temp; j++) {
vm_tlbshootdownvaddr(addr + (index * PAGE_SIZE));
coremap[j].state = FREE;
coremap[j].size = 1;
coremap[j].busy = 0;
coremap[j].pte_ptr = NULL;
coremap[j].clock = false;
coremap[j].cpu_num = -1;
index++;
}
usedBytes = usedBytes - temp * PAGE_SIZE;
spinlock_release(&coremap_spinlock);
return;
}
paddr_t page_alloc(struct PTE *pte) {
int page_ind;
// if(swapping){
// lock_acquire(paging_lock);
// }
spinlock_acquire(&coremap_spinlock);
for (unsigned i = first_free_addr; i < num_pages; i++) {
if (coremap[i].state == FREE && coremap[i].busy == 0) {
if (swapping) {
coremap[i].state = CLEAN;
} else {
coremap[i].state = DIRTY;
}
coremap[i].size = 1;
coremap[i].busy = 0;
coremap[i].pte_ptr = pte;
coremap[i].clock = false;
coremap[i].cpu_num = -1;
bzero((void *) PADDR_TO_KVADDR(i * PAGE_SIZE), PAGE_SIZE);
usedBytes = usedBytes + PAGE_SIZE;
spinlock_release(&coremap_spinlock);
paddr_t returner = PAGE_SIZE * i;
// if(swapping){
// lock_release(paging_lock);
// }
return returner;
}
}
if (swapping) {
page_ind = evict();
coremap[page_ind].state = CLEAN;
coremap[page_ind].size = 1;
coremap[page_ind].busy = 0;
coremap[page_ind].pte_ptr = pte;
coremap[page_ind].clock = false;
coremap[page_ind].cpu_num = -1;
bzero((void *) PADDR_TO_KVADDR(page_ind * PAGE_SIZE), PAGE_SIZE);
spinlock_release(&coremap_spinlock);
paddr_t returner = PAGE_SIZE * page_ind;
return returner;
} else {
spinlock_release(&coremap_spinlock);
return 0;
}
}
void page_free(paddr_t paddr) {
int i = paddr/PAGE_SIZE;
vm_tlbshootdownvaddr(PADDR_TO_KVADDR(paddr));
// vm_tlbshootdownvaddr_for_all_cpus(PADDR_TO_KVADDR(paddr));
if(coremap[i].cpu_num > -1){
vm_tlbshootdownvaddr_for_specific_cpu(PADDR_TO_KVADDR(paddr), coremap[i].cpu_num);
}
spinlock_acquire(&coremap_spinlock);
coremap[i].state = FREE;
coremap[i].size = 1;
coremap[i].busy = 0;
coremap[i].pte_ptr = NULL;
coremap[i].clock = false;
coremap[i].cpu_num = -1;
usedBytes = usedBytes - PAGE_SIZE;
spinlock_release(&coremap_spinlock);
return;
}
void swapdisk_init(void){
struct stat swapdisk_stat;
char *swapdisk = kstrdup("lhd0raw:");
int result;
swapping = true;
swapdisk_index = 0; //stores the swapdisk ptr index
result = vfs_open(swapdisk, O_RDWR, 0, &swapdisk_vnode);
if (result) {
swapping = false;
}
if (swapping) {
clock_pte_ptr = first_free_addr;
// paging_lock = lock_create("paging_lock");
VOP_STAT(swapdisk_vnode, &swapdisk_stat);
num_swappages = swapdisk_stat.st_size / PAGE_SIZE;
swapdisk_bitmap = bitmap_create(SWAPDISK_SIZE);
KASSERT(swapdisk_bitmap != NULL);
}
}
void swapout(vaddr_t swapaddr, paddr_t paddr){
int result;
struct iovec iov;
struct uio ku;
vaddr_t kva=PADDR_TO_KVADDR(paddr);
enum uio_rw mode = UIO_WRITE;
uio_kinit(&iov, &ku, (char *)kva, PAGE_SIZE, swapaddr, mode);
result=VOP_WRITE(swapdisk_vnode, &ku);
if (result) {
panic("\nSwapout error:%d", result);
}
}
void swapin(vaddr_t swapaddr, paddr_t paddr){
int result;
struct iovec iov;
struct uio ku;
vaddr_t kva=PADDR_TO_KVADDR(paddr);
enum uio_rw mode = UIO_READ;
uio_kinit(&iov, &ku, (char *)kva, PAGE_SIZE, swapaddr, mode);
result=VOP_READ(swapdisk_vnode, &ku);
if (result) {
panic("\nSwapin error:%d", result);
}
}
int evict(){
int victim, flag;
flag = 0;
while (flag == 0) {
clock_pte_ptr = clock_pte_ptr % num_pages;
if (clock_pte_ptr < first_free_addr) {
clock_pte_ptr = clock_pte_ptr + first_free_addr;
}
if (((coremap[clock_pte_ptr].state == DIRTY)
|| (coremap[clock_pte_ptr].state == CLEAN))
&& (coremap[clock_pte_ptr].busy == 0)) {
if (!coremap[clock_pte_ptr].clock) {
flag = 1;
} else {
coremap[clock_pte_ptr].clock = false;
}
}
clock_pte_ptr++;
}
if(flag == 0){
return -1;
}
victim = clock_pte_ptr - 1;
coremap[victim].busy = 1;
KASSERT(coremap[victim].pte_ptr != NULL);
paddr_t paddr = PAGE_SIZE * victim;
vm_tlbshootdownvaddr(coremap[victim].pte_ptr->vpn);
spinlock_release(&coremap_spinlock);
// vm_tlbshootdownvaddr_for_all_cpus(coremap[victim].pte_ptr->vpn);
if(coremap[victim].cpu_num > -1){
vm_tlbshootdownvaddr_for_specific_cpu(coremap[victim].pte_ptr->vpn, coremap[victim].cpu_num);
}
lock_acquire(coremap[victim].pte_ptr->pte_lock);
if (coremap[victim].state == DIRTY){
swapout(coremap[victim].pte_ptr->swapdisk_pos, paddr);
}
spinlock_acquire(&coremap_spinlock);
coremap[victim].state = CLEAN;
coremap[victim].pte_ptr->state = DISK;
lock_release(coremap[victim].pte_ptr->pte_lock);
return victim;
}
unsigned
int coremap_used_bytes() {
return usedBytes;
}
void vm_tlbshootdown_all(void) {
spinlock_acquire(&tlb_spinlock);
int x = splhigh();
for (int i = 0; i < NUM_TLB; i++){
tlb_write(TLBHI_INVALID(i),TLBLO_INVALID(),i);
}
splx(x);
spinlock_release(&tlb_spinlock);
}
void vm_tlbshootdown(const struct tlbshootdown *ts) {
vm_tlbshootdownvaddr(ts->vaddr);
}
void vm_tlbshootdownvaddr(vaddr_t vaddr) {
uint32_t lo, hi;
spinlock_acquire(&tlb_spinlock);
int x = splhigh();
int i=tlb_probe(vaddr & PAGE_FRAME, 0);
if(i >= 0)
{
tlb_read(&hi, &lo, i);
tlb_write(TLBHI_INVALID(i),TLBLO_INVALID(),i);
}
splx(x);
spinlock_release(&tlb_spinlock);
}
int vm_fault(int faulttype, vaddr_t faultaddress) {
vaddr_t stack_top, stack_bottom;
vaddr_t vbase, vtop;
bool fheap = false;
bool fstack = false;
bool fregion = false;
struct addrspace *as = curproc->p_addrspace;
struct region *reg = as->region;
stack_top = USERSTACK;
stack_bottom = USERSTACK - MYVM_STACKPAGES * PAGE_SIZE;
if (faultaddress >= as->heap_bottom && faultaddress < as->heap_top) {
fheap = true;
} else if ((faultaddress >= stack_bottom) && (faultaddress < stack_top)) {
fstack = true;
} else { //search regions
while (reg != NULL) {
vbase = reg->base_vaddr;
vtop = vbase + (PAGE_SIZE * reg->num_pages);
if (faultaddress >= vbase && faultaddress < vtop) {
fregion = true;
break;
}
reg = reg->next;
}
}
if (!(fregion || fheap || fstack)) {
return EFAULT;
}
//2. Check if the operation is valid by checking the page permission
//first check if present in the page table, if not, create page
int found = 0;
int tlb_index = -1;
struct PTE *curr, *last;
if (as->pte == NULL) {
found = 1;
as->pte = kmalloc(sizeof(struct PTE));
if(as->pte == NULL){
return ENOMEM;
}
if(swapping){
as->pte->pte_lock = lock_create("pte_lock");
lock_acquire(as->pte->pte_lock);
}
as->pte->ppn = page_alloc(as->pte);
if(as->pte->ppn == (vaddr_t)0){
return ENOMEM;
}
as->pte->vpn = faultaddress & PAGE_FRAME;
as->pte->state = MEM;
as->pte->next = NULL;
// if (swapping) {
// unsigned x;
// if (!bitmap_alloc(swapdisk_bitmap, &x)) {
// as->pte->swapdisk_pos = x * PAGE_SIZE;
// } else {
// panic("\nRan out of swapdisk");
// }
// }
swapdisk_index++;
as->pte->swapdisk_pos = swapdisk_index * PAGE_SIZE;
as->pte_last = as->pte;
curr = as->pte;
} else {
//if the first pte is the required pte
for (curr = as->pte; curr != NULL; curr = curr->next){
if(curr->vpn == (faultaddress & PAGE_FRAME)){
found = 1;
if(swapping){
lock_acquire(curr->pte_lock);
}
break;
}
}
}
if (found == 0) {
//vaddr not found. kmalloc and add to tlb
curr = kmalloc(sizeof(struct PTE));
if(curr == NULL){
return ENOMEM;
}
if(swapping){
curr->pte_lock = lock_create("pte_lock");
lock_acquire(curr->pte_lock);
}
curr->ppn = page_alloc(curr);
if(curr->ppn == (vaddr_t)0){
return ENOMEM;
}
curr->vpn = faultaddress & PAGE_FRAME;
curr->state = MEM;
curr->next = NULL;
// if (swapping) {
// unsigned x;
// if (!bitmap_alloc(swapdisk_bitmap, &x)) {
// curr->swapdisk_pos = x * PAGE_SIZE;
// } else {
// panic("\nRan out of swapdisk");
// }
// }
swapdisk_index++;
curr->swapdisk_pos = swapdisk_index * PAGE_SIZE;
if(!swapping){
for (last = as->pte; last->next != NULL; last = last->next);
last->next = curr;
} else {
as->pte_last->next = curr;
as->pte_last = curr;
}
}
if (faulttype == VM_FAULT_READ || faulttype == VM_FAULT_WRITE) {
//random write
if((curr->state == DISK) && (swapping == true)){
if (found == 1){
curr->ppn = page_alloc(curr);
}
spinlock_acquire(&coremap_spinlock);
coremap[(curr->ppn/PAGE_SIZE)].busy = 1;
spinlock_release(&coremap_spinlock);
swapin(curr->swapdisk_pos, curr->ppn);
spinlock_acquire(&coremap_spinlock);
coremap[(curr->ppn/PAGE_SIZE)].busy = 0;
if (faulttype == VM_FAULT_WRITE) {
coremap[(curr->ppn / PAGE_SIZE)].state = DIRTY;
} else {
coremap[(curr->ppn / PAGE_SIZE)].state = CLEAN;
}
coremap[(curr->ppn/PAGE_SIZE)].clock = true;
coremap[(curr->ppn/PAGE_SIZE)].cpu_num = curcpu->c_number;
spinlock_release(&coremap_spinlock);
// lock_release(paging_lock);
curr->state = MEM;
}
spinlock_acquire(&tlb_spinlock);
int x = splhigh();
tlb_index = tlb_probe(faultaddress & PAGE_FRAME, 0);
paddr_t phy_page_no = curr->ppn;
if(tlb_index < 0){
tlb_random((faultaddress & PAGE_FRAME ), ((phy_page_no & PAGE_FRAME)| TLBLO_VALID));
}else{
tlb_write((faultaddress & PAGE_FRAME), ((phy_page_no & PAGE_FRAME)| TLBLO_VALID), tlb_index);
}
splx(x);
spinlock_release(&tlb_spinlock);
} else if (faulttype == VM_FAULT_READONLY){
if (swapping) {
spinlock_acquire(&coremap_spinlock);
coremap[(curr->ppn / PAGE_SIZE)].state = DIRTY;
coremap[(curr->ppn / PAGE_SIZE)].clock = true;
coremap[(curr->ppn / PAGE_SIZE)].cpu_num = curcpu->c_number;
spinlock_release(&coremap_spinlock);
}
spinlock_acquire(&tlb_spinlock);
int x = splhigh();
tlb_index = tlb_probe(faultaddress & PAGE_FRAME, 0);
if(tlb_index >= 0){
paddr_t phy_page_no = curr->ppn;
tlb_write((faultaddress & PAGE_FRAME), ((phy_page_no & PAGE_FRAME) | TLBLO_DIRTY | TLBLO_VALID), tlb_index);
}
splx(x);
spinlock_release(&tlb_spinlock);
}
if (swapping) {
lock_release(curr->pte_lock);
}
return 0;
}
<file_sep>/Debug/userland/lib/libc/stdlib/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../userland/lib/libc/stdlib/abort.c \
../userland/lib/libc/stdlib/exit.c \
../userland/lib/libc/stdlib/getenv.c \
../userland/lib/libc/stdlib/malloc.c \
../userland/lib/libc/stdlib/qsort.c \
../userland/lib/libc/stdlib/random.c \
../userland/lib/libc/stdlib/system.c
OBJS += \
./userland/lib/libc/stdlib/abort.o \
./userland/lib/libc/stdlib/exit.o \
./userland/lib/libc/stdlib/getenv.o \
./userland/lib/libc/stdlib/malloc.o \
./userland/lib/libc/stdlib/qsort.o \
./userland/lib/libc/stdlib/random.o \
./userland/lib/libc/stdlib/system.o
C_DEPS += \
./userland/lib/libc/stdlib/abort.d \
./userland/lib/libc/stdlib/exit.d \
./userland/lib/libc/stdlib/getenv.d \
./userland/lib/libc/stdlib/malloc.d \
./userland/lib/libc/stdlib/qsort.d \
./userland/lib/libc/stdlib/random.d \
./userland/lib/libc/stdlib/system.d
# Each subdirectory must supply rules for building sources it contributes
userland/lib/libc/stdlib/%.o: ../userland/lib/libc/stdlib/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/Debug/kern/lib/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../kern/lib/array.c \
../kern/lib/bitmap.c \
../kern/lib/bswap.c \
../kern/lib/kgets.c \
../kern/lib/kprintf.c \
../kern/lib/misc.c \
../kern/lib/time.c \
../kern/lib/uio.c
OBJS += \
./kern/lib/array.o \
./kern/lib/bitmap.o \
./kern/lib/bswap.o \
./kern/lib/kgets.o \
./kern/lib/kprintf.o \
./kern/lib/misc.o \
./kern/lib/time.o \
./kern/lib/uio.o
C_DEPS += \
./kern/lib/array.d \
./kern/lib/bitmap.d \
./kern/lib/bswap.d \
./kern/lib/kgets.d \
./kern/lib/kprintf.d \
./kern/lib/misc.d \
./kern/lib/time.d \
./kern/lib/uio.d
# Each subdirectory must supply rules for building sources it contributes
kern/lib/%.o: ../kern/lib/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/Debug/kern/fs/semfs/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../kern/fs/semfs/semfs_fsops.c \
../kern/fs/semfs/semfs_obj.c \
../kern/fs/semfs/semfs_vnops.c
OBJS += \
./kern/fs/semfs/semfs_fsops.o \
./kern/fs/semfs/semfs_obj.o \
./kern/fs/semfs/semfs_vnops.o
C_DEPS += \
./kern/fs/semfs/semfs_fsops.d \
./kern/fs/semfs/semfs_obj.d \
./kern/fs/semfs/semfs_vnops.d
# Each subdirectory must supply rules for building sources it contributes
kern/fs/semfs/%.o: ../kern/fs/semfs/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/Debug/makefile
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
-include ../makefile.init
RM := rm -rf
# All of the sources participating in the build are defined here
-include sources.mk
-include userland/testbin/zero/subdir.mk
-include userland/testbin/waiter/subdir.mk
-include userland/testbin/userthreads/subdir.mk
-include userland/testbin/usemtest/subdir.mk
-include userland/testbin/triplesort/subdir.mk
-include userland/testbin/triplemat/subdir.mk
-include userland/testbin/triplehuge/subdir.mk
-include userland/testbin/tictac/subdir.mk
-include userland/testbin/tail/subdir.mk
-include userland/testbin/sty/subdir.mk
-include userland/testbin/stacktest/subdir.mk
-include userland/testbin/spinner/subdir.mk
-include userland/testbin/sparsefile/subdir.mk
-include userland/testbin/sort/subdir.mk
-include userland/testbin/sink/subdir.mk
-include userland/testbin/shll/subdir.mk
-include userland/testbin/shelltest/subdir.mk
-include userland/testbin/schedpong/subdir.mk
-include userland/testbin/sbrktest/subdir.mk
-include userland/testbin/rmtest/subdir.mk
-include userland/testbin/rmdirtest/subdir.mk
-include userland/testbin/redirect/subdir.mk
-include userland/testbin/readwritetest/subdir.mk
-include userland/testbin/randcall/subdir.mk
-include userland/testbin/quintsort/subdir.mk
-include userland/testbin/quintmat/subdir.mk
-include userland/testbin/quinthuge/subdir.mk
-include userland/testbin/psort/subdir.mk
-include userland/testbin/poisondisk/subdir.mk
-include userland/testbin/parallelvm/subdir.mk
-include userland/testbin/palin/subdir.mk
-include userland/testbin/opentest/subdir.mk
-include userland/testbin/multiexec/subdir.mk
-include userland/testbin/matmult/subdir.mk
-include userland/testbin/malloctest/subdir.mk
-include userland/testbin/kitchen/subdir.mk
-include userland/testbin/huge/subdir.mk
-include userland/testbin/hog/subdir.mk
-include userland/testbin/hash/subdir.mk
-include userland/testbin/guzzle/subdir.mk
-include userland/testbin/frack/subdir.mk
-include userland/testbin/forktest/subdir.mk
-include userland/testbin/forkbomb/subdir.mk
-include userland/testbin/filetest/subdir.mk
-include userland/testbin/fileonlytest/subdir.mk
-include userland/testbin/faulter/subdir.mk
-include userland/testbin/farm/subdir.mk
-include userland/testbin/factorial/subdir.mk
-include userland/testbin/f_test/subdir.mk
-include userland/testbin/dirtest/subdir.mk
-include userland/testbin/dirseek/subdir.mk
-include userland/testbin/dirconc/subdir.mk
-include userland/testbin/ctest/subdir.mk
-include userland/testbin/crash/subdir.mk
-include userland/testbin/consoletest/subdir.mk
-include userland/testbin/conman/subdir.mk
-include userland/testbin/closetest/subdir.mk
-include userland/testbin/bloat/subdir.mk
-include userland/testbin/bigseek/subdir.mk
-include userland/testbin/bigfork/subdir.mk
-include userland/testbin/bigfile/subdir.mk
-include userland/testbin/bigexec/subdir.mk
-include userland/testbin/badcall/subdir.mk
-include userland/testbin/argtest/subdir.mk
-include userland/testbin/add/subdir.mk
-include userland/sbin/sfsck/subdir.mk
-include userland/sbin/reboot/subdir.mk
-include userland/sbin/poweroff/subdir.mk
-include userland/sbin/mksfs/subdir.mk
-include userland/sbin/halt/subdir.mk
-include userland/sbin/dumpsfs/subdir.mk
-include userland/lib/libtest/subdir.mk
-include userland/lib/libc/unix/subdir.mk
-include userland/lib/libc/time/subdir.mk
-include userland/lib/libc/string/subdir.mk
-include userland/lib/libc/stdlib/subdir.mk
-include userland/lib/libc/stdio/subdir.mk
-include userland/lib/libc/arch/mips/subdir.mk
-include userland/lib/hostcompat/subdir.mk
-include userland/lib/crt0/mips/subdir.mk
-include userland/bin/true/subdir.mk
-include userland/bin/tac/subdir.mk
-include userland/bin/sync/subdir.mk
-include userland/bin/sh/subdir.mk
-include userland/bin/rmdir/subdir.mk
-include userland/bin/rm/subdir.mk
-include userland/bin/pwd/subdir.mk
-include userland/bin/mv/subdir.mk
-include userland/bin/mkdir/subdir.mk
-include userland/bin/ls/subdir.mk
-include userland/bin/ln/subdir.mk
-include userland/bin/false/subdir.mk
-include userland/bin/cp/subdir.mk
-include userland/bin/cat/subdir.mk
-include kern/vm/subdir.mk
-include kern/vfs/subdir.mk
-include kern/thread/subdir.mk
-include kern/test/subdir.mk
-include kern/syscall/subdir.mk
-include kern/synchprobs/subdir.mk
-include kern/proc/subdir.mk
-include kern/main/subdir.mk
-include kern/lib/subdir.mk
-include kern/fs/sfs/subdir.mk
-include kern/fs/semfs/subdir.mk
-include kern/dev/lamebus/subdir.mk
-include kern/dev/generic/subdir.mk
-include kern/compile/DUMBVM/subdir.mk
-include kern/compile/ASST3/subdir.mk
-include kern/compile/ASST2/subdir.mk
-include kern/arch/sys161/main/subdir.mk
-include kern/arch/sys161/dev/subdir.mk
-include kern/arch/mips/vm/subdir.mk
-include kern/arch/mips/thread/subdir.mk
-include kern/arch/mips/syscall/subdir.mk
-include kern/arch/mips/locore/subdir.mk
-include common/libtest161/subdir.mk
-include common/libc/string/subdir.mk
-include common/libc/stdlib/subdir.mk
-include common/libc/printf/subdir.mk
-include common/libc/arch/mips/subdir.mk
-include common/gcc-millicode/subdir.mk
-include build/userland/testbin/zero/subdir.mk
-include build/userland/testbin/waiter/subdir.mk
-include build/userland/testbin/usemtest/subdir.mk
-include build/userland/testbin/triplesort/subdir.mk
-include build/userland/testbin/triplemat/subdir.mk
-include build/userland/testbin/triplehuge/subdir.mk
-include build/userland/testbin/tictac/subdir.mk
-include build/userland/testbin/tail/subdir.mk
-include build/userland/testbin/sty/subdir.mk
-include build/userland/testbin/stacktest/subdir.mk
-include build/userland/testbin/spinner/subdir.mk
-include build/userland/testbin/sparsefile/subdir.mk
-include build/userland/testbin/sort/subdir.mk
-include build/userland/testbin/sink/subdir.mk
-include build/userland/testbin/shll/subdir.mk
-include build/userland/testbin/shelltest/subdir.mk
-include build/userland/testbin/schedpong/subdir.mk
-include build/userland/testbin/sbrktest/subdir.mk
-include build/userland/testbin/rmtest/subdir.mk
-include build/userland/testbin/rmdirtest/subdir.mk
-include build/userland/testbin/redirect/subdir.mk
-include build/userland/testbin/readwritetest/subdir.mk
-include build/userland/testbin/randcall/subdir.mk
-include build/userland/testbin/quintsort/subdir.mk
-include build/userland/testbin/quintmat/subdir.mk
-include build/userland/testbin/quinthuge/subdir.mk
-include build/userland/testbin/psort/subdir.mk
-include build/userland/testbin/poisondisk/subdir.mk
-include build/userland/testbin/parallelvm/subdir.mk
-include build/userland/testbin/palin/subdir.mk
-include build/userland/testbin/opentest/subdir.mk
-include build/userland/testbin/multiexec/subdir.mk
-include build/userland/testbin/matmult/subdir.mk
-include build/userland/testbin/malloctest/subdir.mk
-include build/userland/testbin/kitchen/subdir.mk
-include build/userland/testbin/huge/subdir.mk
-include build/userland/testbin/hog/subdir.mk
-include build/userland/testbin/hash/subdir.mk
-include build/userland/testbin/guzzle/subdir.mk
-include build/userland/testbin/frack/subdir.mk
-include build/userland/testbin/forktest/subdir.mk
-include build/userland/testbin/forkbomb/subdir.mk
-include build/userland/testbin/filetest/subdir.mk
-include build/userland/testbin/fileonlytest/subdir.mk
-include build/userland/testbin/faulter/subdir.mk
-include build/userland/testbin/farm/subdir.mk
-include build/userland/testbin/factorial/subdir.mk
-include build/userland/testbin/f_test/subdir.mk
-include build/userland/testbin/dirtest/subdir.mk
-include build/userland/testbin/dirseek/subdir.mk
-include build/userland/testbin/dirconc/subdir.mk
-include build/userland/testbin/ctest/subdir.mk
-include build/userland/testbin/crash/subdir.mk
-include build/userland/testbin/consoletest/subdir.mk
-include build/userland/testbin/conman/subdir.mk
-include build/userland/testbin/closetest/subdir.mk
-include build/userland/testbin/bloat/subdir.mk
-include build/userland/testbin/bigseek/subdir.mk
-include build/userland/testbin/bigfork/subdir.mk
-include build/userland/testbin/bigfile/subdir.mk
-include build/userland/testbin/bigexec/subdir.mk
-include build/userland/testbin/badcall/subdir.mk
-include build/userland/testbin/argtest/subdir.mk
-include build/userland/testbin/add/subdir.mk
-include build/userland/sbin/sfsck/subdir.mk
-include build/userland/sbin/reboot/subdir.mk
-include build/userland/sbin/poweroff/subdir.mk
-include build/userland/sbin/mksfs/subdir.mk
-include build/userland/sbin/halt/subdir.mk
-include build/userland/sbin/dumpsfs/subdir.mk
-include build/userland/lib/libtest161/subdir.mk
-include build/userland/lib/libtest/subdir.mk
-include build/userland/lib/libc/subdir.mk
-include build/userland/lib/crt0/subdir.mk
-include build/userland/bin/true/subdir.mk
-include build/userland/bin/tac/subdir.mk
-include build/userland/bin/sync/subdir.mk
-include build/userland/bin/sh/subdir.mk
-include build/userland/bin/rmdir/subdir.mk
-include build/userland/bin/rm/subdir.mk
-include build/userland/bin/pwd/subdir.mk
-include build/userland/bin/mv/subdir.mk
-include build/userland/bin/mkdir/subdir.mk
-include build/userland/bin/ls/subdir.mk
-include build/userland/bin/ln/subdir.mk
-include build/userland/bin/false/subdir.mk
-include build/userland/bin/cp/subdir.mk
-include build/userland/bin/cat/subdir.mk
-include build/install/lib/subdir.mk
-include subdir.mk
-include objects.mk
ifneq ($(MAKECMDGOALS),clean)
ifneq ($(strip $(C_DEPS)),)
-include $(C_DEPS)
endif
endif
-include ../makefile.defs
# Add inputs and outputs from these tool invocations to the build variables
# All Target
all: OS
# Tool invocations
OS: $(OBJS) $(USER_OBJS)
@echo 'Building target: $@'
@echo 'Invoking: Cross GCC Linker'
gcc -o "OS" $(OBJS) $(USER_OBJS) $(LIBS)
@echo 'Finished building target: $@'
@echo ' '
# Other Targets
clean:
-$(RM) $(EXECUTABLES)$(OBJS)$(C_DEPS) OS
-@echo ' '
.PHONY: all clean dependents
.SECONDARY:
-include ../makefile.targets
<file_sep>/Debug/userland/lib/hostcompat/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../userland/lib/hostcompat/err.c \
../userland/lib/hostcompat/hostcompat.c \
../userland/lib/hostcompat/ntohll.c \
../userland/lib/hostcompat/time.c
OBJS += \
./userland/lib/hostcompat/err.o \
./userland/lib/hostcompat/hostcompat.o \
./userland/lib/hostcompat/ntohll.o \
./userland/lib/hostcompat/time.o
C_DEPS += \
./userland/lib/hostcompat/err.d \
./userland/lib/hostcompat/hostcompat.d \
./userland/lib/hostcompat/ntohll.d \
./userland/lib/hostcompat/time.d
# Each subdirectory must supply rules for building sources it contributes
userland/lib/hostcompat/%.o: ../userland/lib/hostcompat/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/Debug/kern/compile/ASST3/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../kern/compile/ASST3/.depend.__printf.c \
../kern/compile/ASST3/.depend.adddi3.c \
../kern/compile/ASST3/.depend.addrspace.c \
../kern/compile/ASST3/.depend.anddi3.c \
../kern/compile/ASST3/.depend.array.c \
../kern/compile/ASST3/.depend.arraytest.c \
../kern/compile/ASST3/.depend.ashldi3.c \
../kern/compile/ASST3/.depend.ashrdi3.c \
../kern/compile/ASST3/.depend.atoi.c \
../kern/compile/ASST3/.depend.autoconf.c \
../kern/compile/ASST3/.depend.beep.c \
../kern/compile/ASST3/.depend.beep_ltimer.c \
../kern/compile/ASST3/.depend.bitmap.c \
../kern/compile/ASST3/.depend.bitmaptest.c \
../kern/compile/ASST3/.depend.bswap.c \
../kern/compile/ASST3/.depend.bzero.c \
../kern/compile/ASST3/.depend.clock.c \
../kern/compile/ASST3/.depend.cmpdi2.c \
../kern/compile/ASST3/.depend.con_lser.c \
../kern/compile/ASST3/.depend.console.c \
../kern/compile/ASST3/.depend.copyinout.c \
../kern/compile/ASST3/.depend.cpu.c \
../kern/compile/ASST3/.depend.device.c \
../kern/compile/ASST3/.depend.devnull.c \
../kern/compile/ASST3/.depend.divdi3.c \
../kern/compile/ASST3/.depend.emu.c \
../kern/compile/ASST3/.depend.emu_att.c \
../kern/compile/ASST3/.depend.file_syscalls.c \
../kern/compile/ASST3/.depend.fstest.c \
../kern/compile/ASST3/.depend.hmacunit.c \
../kern/compile/ASST3/.depend.iordi3.c \
../kern/compile/ASST3/.depend.kgets.c \
../kern/compile/ASST3/.depend.kmalloc.c \
../kern/compile/ASST3/.depend.kmalloctest.c \
../kern/compile/ASST3/.depend.kprintf.c \
../kern/compile/ASST3/.depend.lamebus.c \
../kern/compile/ASST3/.depend.lamebus_machdep.c \
../kern/compile/ASST3/.depend.lhd.c \
../kern/compile/ASST3/.depend.lhd_att.c \
../kern/compile/ASST3/.depend.lib.c \
../kern/compile/ASST3/.depend.loadelf.c \
../kern/compile/ASST3/.depend.lrandom.c \
../kern/compile/ASST3/.depend.lrandom_att.c \
../kern/compile/ASST3/.depend.lser.c \
../kern/compile/ASST3/.depend.lser_att.c \
../kern/compile/ASST3/.depend.lshldi3.c \
../kern/compile/ASST3/.depend.lshrdi3.c \
../kern/compile/ASST3/.depend.ltimer.c \
../kern/compile/ASST3/.depend.ltimer_att.c \
../kern/compile/ASST3/.depend.ltrace.c \
../kern/compile/ASST3/.depend.ltrace_att.c \
../kern/compile/ASST3/.depend.main.c \
../kern/compile/ASST3/.depend.memcpy.c \
../kern/compile/ASST3/.depend.memmove.c \
../kern/compile/ASST3/.depend.memset.c \
../kern/compile/ASST3/.depend.menu.c \
../kern/compile/ASST3/.depend.misc.c \
../kern/compile/ASST3/.depend.moddi3.c \
../kern/compile/ASST3/.depend.muldi3.c \
../kern/compile/ASST3/.depend.myvm.c \
../kern/compile/ASST3/.depend.negdi2.c \
../kern/compile/ASST3/.depend.notdi2.c \
../kern/compile/ASST3/.depend.proc.c \
../kern/compile/ASST3/.depend.proc_syscalls.c \
../kern/compile/ASST3/.depend.qdivrem.c \
../kern/compile/ASST3/.depend.ram.c \
../kern/compile/ASST3/.depend.random.c \
../kern/compile/ASST3/.depend.random_lrandom.c \
../kern/compile/ASST3/.depend.rtclock.c \
../kern/compile/ASST3/.depend.rtclock_ltimer.c \
../kern/compile/ASST3/.depend.runprogram.c \
../kern/compile/ASST3/.depend.rwtest.c \
../kern/compile/ASST3/.depend.secure.c \
../kern/compile/ASST3/.depend.semfs_fsops.c \
../kern/compile/ASST3/.depend.semfs_obj.c \
../kern/compile/ASST3/.depend.semfs_vnops.c \
../kern/compile/ASST3/.depend.semunit.c \
../kern/compile/ASST3/.depend.sfs_balloc.c \
../kern/compile/ASST3/.depend.sfs_bmap.c \
../kern/compile/ASST3/.depend.sfs_dir.c \
../kern/compile/ASST3/.depend.sfs_fsops.c \
../kern/compile/ASST3/.depend.sfs_inode.c \
../kern/compile/ASST3/.depend.sfs_io.c \
../kern/compile/ASST3/.depend.sfs_vnops.c \
../kern/compile/ASST3/.depend.sha256.c \
../kern/compile/ASST3/.depend.snprintf.c \
../kern/compile/ASST3/.depend.spinlock.c \
../kern/compile/ASST3/.depend.spl.c \
../kern/compile/ASST3/.depend.strcat.c \
../kern/compile/ASST3/.depend.strchr.c \
../kern/compile/ASST3/.depend.strcmp.c \
../kern/compile/ASST3/.depend.strcpy.c \
../kern/compile/ASST3/.depend.strlen.c \
../kern/compile/ASST3/.depend.strrchr.c \
../kern/compile/ASST3/.depend.strtok_r.c \
../kern/compile/ASST3/.depend.subdi3.c \
../kern/compile/ASST3/.depend.switchframe.c \
../kern/compile/ASST3/.depend.synch.c \
../kern/compile/ASST3/.depend.synchtest.c \
../kern/compile/ASST3/.depend.syscall.c \
../kern/compile/ASST3/.depend.test161.c \
../kern/compile/ASST3/.depend.thread.c \
../kern/compile/ASST3/.depend.thread_machdep.c \
../kern/compile/ASST3/.depend.threadlist.c \
../kern/compile/ASST3/.depend.threadlisttest.c \
../kern/compile/ASST3/.depend.threadtest.c \
../kern/compile/ASST3/.depend.time.c \
../kern/compile/ASST3/.depend.time_syscalls.c \
../kern/compile/ASST3/.depend.trap.c \
../kern/compile/ASST3/.depend.tt3.c \
../kern/compile/ASST3/.depend.ucmpdi2.c \
../kern/compile/ASST3/.depend.udivdi3.c \
../kern/compile/ASST3/.depend.uio.c \
../kern/compile/ASST3/.depend.umoddi3.c \
../kern/compile/ASST3/.depend.vfscwd.c \
../kern/compile/ASST3/.depend.vfsfail.c \
../kern/compile/ASST3/.depend.vfslist.c \
../kern/compile/ASST3/.depend.vfslookup.c \
../kern/compile/ASST3/.depend.vfspath.c \
../kern/compile/ASST3/.depend.vnode.c \
../kern/compile/ASST3/.depend.xordi3.c \
../kern/compile/ASST3/autoconf.c \
../kern/compile/ASST3/vers.c
O_SRCS += \
../kern/compile/ASST3/__printf.o \
../kern/compile/ASST3/adddi3.o \
../kern/compile/ASST3/addrspace.o \
../kern/compile/ASST3/anddi3.o \
../kern/compile/ASST3/array.o \
../kern/compile/ASST3/arraytest.o \
../kern/compile/ASST3/ashldi3.o \
../kern/compile/ASST3/ashrdi3.o \
../kern/compile/ASST3/atoi.o \
../kern/compile/ASST3/autoconf.o \
../kern/compile/ASST3/beep.o \
../kern/compile/ASST3/beep_ltimer.o \
../kern/compile/ASST3/bitmap.o \
../kern/compile/ASST3/bitmaptest.o \
../kern/compile/ASST3/bswap.o \
../kern/compile/ASST3/bzero.o \
../kern/compile/ASST3/cache-mips161.o \
../kern/compile/ASST3/clock.o \
../kern/compile/ASST3/cmpdi2.o \
../kern/compile/ASST3/con_lser.o \
../kern/compile/ASST3/console.o \
../kern/compile/ASST3/copyinout.o \
../kern/compile/ASST3/cpu.o \
../kern/compile/ASST3/device.o \
../kern/compile/ASST3/devnull.o \
../kern/compile/ASST3/divdi3.o \
../kern/compile/ASST3/emu.o \
../kern/compile/ASST3/emu_att.o \
../kern/compile/ASST3/exception-mips1.o \
../kern/compile/ASST3/file_syscalls.o \
../kern/compile/ASST3/fstest.o \
../kern/compile/ASST3/hmacunit.o \
../kern/compile/ASST3/iordi3.o \
../kern/compile/ASST3/kgets.o \
../kern/compile/ASST3/kmalloc.o \
../kern/compile/ASST3/kmalloctest.o \
../kern/compile/ASST3/kprintf.o \
../kern/compile/ASST3/lamebus.o \
../kern/compile/ASST3/lamebus_machdep.o \
../kern/compile/ASST3/lhd.o \
../kern/compile/ASST3/lhd_att.o \
../kern/compile/ASST3/lib.o \
../kern/compile/ASST3/loadelf.o \
../kern/compile/ASST3/lrandom.o \
../kern/compile/ASST3/lrandom_att.o \
../kern/compile/ASST3/lser.o \
../kern/compile/ASST3/lser_att.o \
../kern/compile/ASST3/lshldi3.o \
../kern/compile/ASST3/lshrdi3.o \
../kern/compile/ASST3/ltimer.o \
../kern/compile/ASST3/ltimer_att.o \
../kern/compile/ASST3/ltrace.o \
../kern/compile/ASST3/ltrace_att.o \
../kern/compile/ASST3/main.o \
../kern/compile/ASST3/memcpy.o \
../kern/compile/ASST3/memmove.o \
../kern/compile/ASST3/memset.o \
../kern/compile/ASST3/menu.o \
../kern/compile/ASST3/misc.o \
../kern/compile/ASST3/moddi3.o \
../kern/compile/ASST3/muldi3.o \
../kern/compile/ASST3/myvm.o \
../kern/compile/ASST3/negdi2.o \
../kern/compile/ASST3/notdi2.o \
../kern/compile/ASST3/proc.o \
../kern/compile/ASST3/proc_syscalls.o \
../kern/compile/ASST3/qdivrem.o \
../kern/compile/ASST3/ram.o \
../kern/compile/ASST3/random.o \
../kern/compile/ASST3/random_lrandom.o \
../kern/compile/ASST3/rtclock.o \
../kern/compile/ASST3/rtclock_ltimer.o \
../kern/compile/ASST3/runprogram.o \
../kern/compile/ASST3/rwtest.o \
../kern/compile/ASST3/secure.o \
../kern/compile/ASST3/semfs_fsops.o \
../kern/compile/ASST3/semfs_obj.o \
../kern/compile/ASST3/semfs_vnops.o \
../kern/compile/ASST3/semunit.o \
../kern/compile/ASST3/setjmp.o \
../kern/compile/ASST3/sfs_balloc.o \
../kern/compile/ASST3/sfs_bmap.o \
../kern/compile/ASST3/sfs_dir.o \
../kern/compile/ASST3/sfs_fsops.o \
../kern/compile/ASST3/sfs_inode.o \
../kern/compile/ASST3/sfs_io.o \
../kern/compile/ASST3/sfs_vnops.o \
../kern/compile/ASST3/sha256.o \
../kern/compile/ASST3/snprintf.o \
../kern/compile/ASST3/spinlock.o \
../kern/compile/ASST3/spl.o \
../kern/compile/ASST3/start.o \
../kern/compile/ASST3/strcat.o \
../kern/compile/ASST3/strchr.o \
../kern/compile/ASST3/strcmp.o \
../kern/compile/ASST3/strcpy.o \
../kern/compile/ASST3/strlen.o \
../kern/compile/ASST3/strrchr.o \
../kern/compile/ASST3/strtok_r.o \
../kern/compile/ASST3/subdi3.o \
../kern/compile/ASST3/switch.o \
../kern/compile/ASST3/switchframe.o \
../kern/compile/ASST3/synch.o \
../kern/compile/ASST3/synchtest.o \
../kern/compile/ASST3/syscall.o \
../kern/compile/ASST3/test161.o \
../kern/compile/ASST3/thread.o \
../kern/compile/ASST3/thread_machdep.o \
../kern/compile/ASST3/threadlist.o \
../kern/compile/ASST3/threadlisttest.o \
../kern/compile/ASST3/threadstart.o \
../kern/compile/ASST3/threadtest.o \
../kern/compile/ASST3/time.o \
../kern/compile/ASST3/time_syscalls.o \
../kern/compile/ASST3/tlb-mips161.o \
../kern/compile/ASST3/trap.o \
../kern/compile/ASST3/tt3.o \
../kern/compile/ASST3/ucmpdi2.o \
../kern/compile/ASST3/udivdi3.o \
../kern/compile/ASST3/uio.o \
../kern/compile/ASST3/umoddi3.o \
../kern/compile/ASST3/vers.o \
../kern/compile/ASST3/vfscwd.o \
../kern/compile/ASST3/vfsfail.o \
../kern/compile/ASST3/vfslist.o \
../kern/compile/ASST3/vfslookup.o \
../kern/compile/ASST3/vfspath.o \
../kern/compile/ASST3/vnode.o \
../kern/compile/ASST3/xordi3.o
S_UPPER_SRCS += \
../kern/compile/ASST3/.depend.cache-mips161.S \
../kern/compile/ASST3/.depend.exception-mips1.S \
../kern/compile/ASST3/.depend.setjmp.S \
../kern/compile/ASST3/.depend.start.S \
../kern/compile/ASST3/.depend.switch.S \
../kern/compile/ASST3/.depend.threadstart.S \
../kern/compile/ASST3/.depend.tlb-mips161.S
OBJS += \
./kern/compile/ASST3/.depend.__printf.o \
./kern/compile/ASST3/.depend.adddi3.o \
./kern/compile/ASST3/.depend.addrspace.o \
./kern/compile/ASST3/.depend.anddi3.o \
./kern/compile/ASST3/.depend.array.o \
./kern/compile/ASST3/.depend.arraytest.o \
./kern/compile/ASST3/.depend.ashldi3.o \
./kern/compile/ASST3/.depend.ashrdi3.o \
./kern/compile/ASST3/.depend.atoi.o \
./kern/compile/ASST3/.depend.autoconf.o \
./kern/compile/ASST3/.depend.beep.o \
./kern/compile/ASST3/.depend.beep_ltimer.o \
./kern/compile/ASST3/.depend.bitmap.o \
./kern/compile/ASST3/.depend.bitmaptest.o \
./kern/compile/ASST3/.depend.bswap.o \
./kern/compile/ASST3/.depend.bzero.o \
./kern/compile/ASST3/.depend.cache-mips161.o \
./kern/compile/ASST3/.depend.clock.o \
./kern/compile/ASST3/.depend.cmpdi2.o \
./kern/compile/ASST3/.depend.con_lser.o \
./kern/compile/ASST3/.depend.console.o \
./kern/compile/ASST3/.depend.copyinout.o \
./kern/compile/ASST3/.depend.cpu.o \
./kern/compile/ASST3/.depend.device.o \
./kern/compile/ASST3/.depend.devnull.o \
./kern/compile/ASST3/.depend.divdi3.o \
./kern/compile/ASST3/.depend.emu.o \
./kern/compile/ASST3/.depend.emu_att.o \
./kern/compile/ASST3/.depend.exception-mips1.o \
./kern/compile/ASST3/.depend.file_syscalls.o \
./kern/compile/ASST3/.depend.fstest.o \
./kern/compile/ASST3/.depend.hmacunit.o \
./kern/compile/ASST3/.depend.iordi3.o \
./kern/compile/ASST3/.depend.kgets.o \
./kern/compile/ASST3/.depend.kmalloc.o \
./kern/compile/ASST3/.depend.kmalloctest.o \
./kern/compile/ASST3/.depend.kprintf.o \
./kern/compile/ASST3/.depend.lamebus.o \
./kern/compile/ASST3/.depend.lamebus_machdep.o \
./kern/compile/ASST3/.depend.lhd.o \
./kern/compile/ASST3/.depend.lhd_att.o \
./kern/compile/ASST3/.depend.lib.o \
./kern/compile/ASST3/.depend.loadelf.o \
./kern/compile/ASST3/.depend.lrandom.o \
./kern/compile/ASST3/.depend.lrandom_att.o \
./kern/compile/ASST3/.depend.lser.o \
./kern/compile/ASST3/.depend.lser_att.o \
./kern/compile/ASST3/.depend.lshldi3.o \
./kern/compile/ASST3/.depend.lshrdi3.o \
./kern/compile/ASST3/.depend.ltimer.o \
./kern/compile/ASST3/.depend.ltimer_att.o \
./kern/compile/ASST3/.depend.ltrace.o \
./kern/compile/ASST3/.depend.ltrace_att.o \
./kern/compile/ASST3/.depend.main.o \
./kern/compile/ASST3/.depend.memcpy.o \
./kern/compile/ASST3/.depend.memmove.o \
./kern/compile/ASST3/.depend.memset.o \
./kern/compile/ASST3/.depend.menu.o \
./kern/compile/ASST3/.depend.misc.o \
./kern/compile/ASST3/.depend.moddi3.o \
./kern/compile/ASST3/.depend.muldi3.o \
./kern/compile/ASST3/.depend.myvm.o \
./kern/compile/ASST3/.depend.negdi2.o \
./kern/compile/ASST3/.depend.notdi2.o \
./kern/compile/ASST3/.depend.proc.o \
./kern/compile/ASST3/.depend.proc_syscalls.o \
./kern/compile/ASST3/.depend.qdivrem.o \
./kern/compile/ASST3/.depend.ram.o \
./kern/compile/ASST3/.depend.random.o \
./kern/compile/ASST3/.depend.random_lrandom.o \
./kern/compile/ASST3/.depend.rtclock.o \
./kern/compile/ASST3/.depend.rtclock_ltimer.o \
./kern/compile/ASST3/.depend.runprogram.o \
./kern/compile/ASST3/.depend.rwtest.o \
./kern/compile/ASST3/.depend.secure.o \
./kern/compile/ASST3/.depend.semfs_fsops.o \
./kern/compile/ASST3/.depend.semfs_obj.o \
./kern/compile/ASST3/.depend.semfs_vnops.o \
./kern/compile/ASST3/.depend.semunit.o \
./kern/compile/ASST3/.depend.setjmp.o \
./kern/compile/ASST3/.depend.sfs_balloc.o \
./kern/compile/ASST3/.depend.sfs_bmap.o \
./kern/compile/ASST3/.depend.sfs_dir.o \
./kern/compile/ASST3/.depend.sfs_fsops.o \
./kern/compile/ASST3/.depend.sfs_inode.o \
./kern/compile/ASST3/.depend.sfs_io.o \
./kern/compile/ASST3/.depend.sfs_vnops.o \
./kern/compile/ASST3/.depend.sha256.o \
./kern/compile/ASST3/.depend.snprintf.o \
./kern/compile/ASST3/.depend.spinlock.o \
./kern/compile/ASST3/.depend.spl.o \
./kern/compile/ASST3/.depend.start.o \
./kern/compile/ASST3/.depend.strcat.o \
./kern/compile/ASST3/.depend.strchr.o \
./kern/compile/ASST3/.depend.strcmp.o \
./kern/compile/ASST3/.depend.strcpy.o \
./kern/compile/ASST3/.depend.strlen.o \
./kern/compile/ASST3/.depend.strrchr.o \
./kern/compile/ASST3/.depend.strtok_r.o \
./kern/compile/ASST3/.depend.subdi3.o \
./kern/compile/ASST3/.depend.switch.o \
./kern/compile/ASST3/.depend.switchframe.o \
./kern/compile/ASST3/.depend.synch.o \
./kern/compile/ASST3/.depend.synchtest.o \
./kern/compile/ASST3/.depend.syscall.o \
./kern/compile/ASST3/.depend.test161.o \
./kern/compile/ASST3/.depend.thread.o \
./kern/compile/ASST3/.depend.thread_machdep.o \
./kern/compile/ASST3/.depend.threadlist.o \
./kern/compile/ASST3/.depend.threadlisttest.o \
./kern/compile/ASST3/.depend.threadstart.o \
./kern/compile/ASST3/.depend.threadtest.o \
./kern/compile/ASST3/.depend.time.o \
./kern/compile/ASST3/.depend.time_syscalls.o \
./kern/compile/ASST3/.depend.tlb-mips161.o \
./kern/compile/ASST3/.depend.trap.o \
./kern/compile/ASST3/.depend.tt3.o \
./kern/compile/ASST3/.depend.ucmpdi2.o \
./kern/compile/ASST3/.depend.udivdi3.o \
./kern/compile/ASST3/.depend.uio.o \
./kern/compile/ASST3/.depend.umoddi3.o \
./kern/compile/ASST3/.depend.vfscwd.o \
./kern/compile/ASST3/.depend.vfsfail.o \
./kern/compile/ASST3/.depend.vfslist.o \
./kern/compile/ASST3/.depend.vfslookup.o \
./kern/compile/ASST3/.depend.vfspath.o \
./kern/compile/ASST3/.depend.vnode.o \
./kern/compile/ASST3/.depend.xordi3.o \
./kern/compile/ASST3/autoconf.o \
./kern/compile/ASST3/vers.o
C_DEPS += \
./kern/compile/ASST3/.depend.__printf.d \
./kern/compile/ASST3/.depend.adddi3.d \
./kern/compile/ASST3/.depend.addrspace.d \
./kern/compile/ASST3/.depend.anddi3.d \
./kern/compile/ASST3/.depend.array.d \
./kern/compile/ASST3/.depend.arraytest.d \
./kern/compile/ASST3/.depend.ashldi3.d \
./kern/compile/ASST3/.depend.ashrdi3.d \
./kern/compile/ASST3/.depend.atoi.d \
./kern/compile/ASST3/.depend.autoconf.d \
./kern/compile/ASST3/.depend.beep.d \
./kern/compile/ASST3/.depend.beep_ltimer.d \
./kern/compile/ASST3/.depend.bitmap.d \
./kern/compile/ASST3/.depend.bitmaptest.d \
./kern/compile/ASST3/.depend.bswap.d \
./kern/compile/ASST3/.depend.bzero.d \
./kern/compile/ASST3/.depend.clock.d \
./kern/compile/ASST3/.depend.cmpdi2.d \
./kern/compile/ASST3/.depend.con_lser.d \
./kern/compile/ASST3/.depend.console.d \
./kern/compile/ASST3/.depend.copyinout.d \
./kern/compile/ASST3/.depend.cpu.d \
./kern/compile/ASST3/.depend.device.d \
./kern/compile/ASST3/.depend.devnull.d \
./kern/compile/ASST3/.depend.divdi3.d \
./kern/compile/ASST3/.depend.emu.d \
./kern/compile/ASST3/.depend.emu_att.d \
./kern/compile/ASST3/.depend.file_syscalls.d \
./kern/compile/ASST3/.depend.fstest.d \
./kern/compile/ASST3/.depend.hmacunit.d \
./kern/compile/ASST3/.depend.iordi3.d \
./kern/compile/ASST3/.depend.kgets.d \
./kern/compile/ASST3/.depend.kmalloc.d \
./kern/compile/ASST3/.depend.kmalloctest.d \
./kern/compile/ASST3/.depend.kprintf.d \
./kern/compile/ASST3/.depend.lamebus.d \
./kern/compile/ASST3/.depend.lamebus_machdep.d \
./kern/compile/ASST3/.depend.lhd.d \
./kern/compile/ASST3/.depend.lhd_att.d \
./kern/compile/ASST3/.depend.lib.d \
./kern/compile/ASST3/.depend.loadelf.d \
./kern/compile/ASST3/.depend.lrandom.d \
./kern/compile/ASST3/.depend.lrandom_att.d \
./kern/compile/ASST3/.depend.lser.d \
./kern/compile/ASST3/.depend.lser_att.d \
./kern/compile/ASST3/.depend.lshldi3.d \
./kern/compile/ASST3/.depend.lshrdi3.d \
./kern/compile/ASST3/.depend.ltimer.d \
./kern/compile/ASST3/.depend.ltimer_att.d \
./kern/compile/ASST3/.depend.ltrace.d \
./kern/compile/ASST3/.depend.ltrace_att.d \
./kern/compile/ASST3/.depend.main.d \
./kern/compile/ASST3/.depend.memcpy.d \
./kern/compile/ASST3/.depend.memmove.d \
./kern/compile/ASST3/.depend.memset.d \
./kern/compile/ASST3/.depend.menu.d \
./kern/compile/ASST3/.depend.misc.d \
./kern/compile/ASST3/.depend.moddi3.d \
./kern/compile/ASST3/.depend.muldi3.d \
./kern/compile/ASST3/.depend.myvm.d \
./kern/compile/ASST3/.depend.negdi2.d \
./kern/compile/ASST3/.depend.notdi2.d \
./kern/compile/ASST3/.depend.proc.d \
./kern/compile/ASST3/.depend.proc_syscalls.d \
./kern/compile/ASST3/.depend.qdivrem.d \
./kern/compile/ASST3/.depend.ram.d \
./kern/compile/ASST3/.depend.random.d \
./kern/compile/ASST3/.depend.random_lrandom.d \
./kern/compile/ASST3/.depend.rtclock.d \
./kern/compile/ASST3/.depend.rtclock_ltimer.d \
./kern/compile/ASST3/.depend.runprogram.d \
./kern/compile/ASST3/.depend.rwtest.d \
./kern/compile/ASST3/.depend.secure.d \
./kern/compile/ASST3/.depend.semfs_fsops.d \
./kern/compile/ASST3/.depend.semfs_obj.d \
./kern/compile/ASST3/.depend.semfs_vnops.d \
./kern/compile/ASST3/.depend.semunit.d \
./kern/compile/ASST3/.depend.sfs_balloc.d \
./kern/compile/ASST3/.depend.sfs_bmap.d \
./kern/compile/ASST3/.depend.sfs_dir.d \
./kern/compile/ASST3/.depend.sfs_fsops.d \
./kern/compile/ASST3/.depend.sfs_inode.d \
./kern/compile/ASST3/.depend.sfs_io.d \
./kern/compile/ASST3/.depend.sfs_vnops.d \
./kern/compile/ASST3/.depend.sha256.d \
./kern/compile/ASST3/.depend.snprintf.d \
./kern/compile/ASST3/.depend.spinlock.d \
./kern/compile/ASST3/.depend.spl.d \
./kern/compile/ASST3/.depend.strcat.d \
./kern/compile/ASST3/.depend.strchr.d \
./kern/compile/ASST3/.depend.strcmp.d \
./kern/compile/ASST3/.depend.strcpy.d \
./kern/compile/ASST3/.depend.strlen.d \
./kern/compile/ASST3/.depend.strrchr.d \
./kern/compile/ASST3/.depend.strtok_r.d \
./kern/compile/ASST3/.depend.subdi3.d \
./kern/compile/ASST3/.depend.switchframe.d \
./kern/compile/ASST3/.depend.synch.d \
./kern/compile/ASST3/.depend.synchtest.d \
./kern/compile/ASST3/.depend.syscall.d \
./kern/compile/ASST3/.depend.test161.d \
./kern/compile/ASST3/.depend.thread.d \
./kern/compile/ASST3/.depend.thread_machdep.d \
./kern/compile/ASST3/.depend.threadlist.d \
./kern/compile/ASST3/.depend.threadlisttest.d \
./kern/compile/ASST3/.depend.threadtest.d \
./kern/compile/ASST3/.depend.time.d \
./kern/compile/ASST3/.depend.time_syscalls.d \
./kern/compile/ASST3/.depend.trap.d \
./kern/compile/ASST3/.depend.tt3.d \
./kern/compile/ASST3/.depend.ucmpdi2.d \
./kern/compile/ASST3/.depend.udivdi3.d \
./kern/compile/ASST3/.depend.uio.d \
./kern/compile/ASST3/.depend.umoddi3.d \
./kern/compile/ASST3/.depend.vfscwd.d \
./kern/compile/ASST3/.depend.vfsfail.d \
./kern/compile/ASST3/.depend.vfslist.d \
./kern/compile/ASST3/.depend.vfslookup.d \
./kern/compile/ASST3/.depend.vfspath.d \
./kern/compile/ASST3/.depend.vnode.d \
./kern/compile/ASST3/.depend.xordi3.d \
./kern/compile/ASST3/autoconf.d \
./kern/compile/ASST3/vers.d
# Each subdirectory must supply rules for building sources it contributes
kern/compile/ASST3/%.o: ../kern/compile/ASST3/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
kern/compile/ASST3/%.o: ../kern/compile/ASST3/%.S
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Assembler'
as -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/Debug/sources.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
OBJ_SRCS :=
ASM_SRCS :=
C_SRCS :=
O_SRCS :=
S_UPPER_SRCS :=
EXECUTABLES :=
OBJS :=
C_DEPS :=
# Every subdirectory with source files must be described here
SUBDIRS := \
build/install/lib \
build/userland/bin/cat \
build/userland/bin/cp \
build/userland/bin/false \
build/userland/bin/ln \
build/userland/bin/ls \
build/userland/bin/mkdir \
build/userland/bin/mv \
build/userland/bin/pwd \
build/userland/bin/rm \
build/userland/bin/rmdir \
build/userland/bin/sh \
build/userland/bin/sync \
build/userland/bin/tac \
build/userland/bin/true \
build/userland/lib/crt0 \
build/userland/lib/libc \
build/userland/lib/libtest \
build/userland/lib/libtest161 \
build/userland/sbin/dumpsfs \
build/userland/sbin/halt \
build/userland/sbin/mksfs \
build/userland/sbin/poweroff \
build/userland/sbin/reboot \
build/userland/sbin/sfsck \
build/userland/testbin/add \
build/userland/testbin/argtest \
build/userland/testbin/badcall \
build/userland/testbin/bigexec \
build/userland/testbin/bigfile \
build/userland/testbin/bigfork \
build/userland/testbin/bigseek \
build/userland/testbin/bloat \
build/userland/testbin/closetest \
build/userland/testbin/conman \
build/userland/testbin/consoletest \
build/userland/testbin/crash \
build/userland/testbin/ctest \
build/userland/testbin/dirconc \
build/userland/testbin/dirseek \
build/userland/testbin/dirtest \
build/userland/testbin/f_test \
build/userland/testbin/factorial \
build/userland/testbin/farm \
build/userland/testbin/faulter \
build/userland/testbin/fileonlytest \
build/userland/testbin/filetest \
build/userland/testbin/forkbomb \
build/userland/testbin/forktest \
build/userland/testbin/frack \
build/userland/testbin/guzzle \
build/userland/testbin/hash \
build/userland/testbin/hog \
build/userland/testbin/huge \
build/userland/testbin/kitchen \
build/userland/testbin/malloctest \
build/userland/testbin/matmult \
build/userland/testbin/multiexec \
build/userland/testbin/opentest \
build/userland/testbin/palin \
build/userland/testbin/parallelvm \
build/userland/testbin/poisondisk \
build/userland/testbin/psort \
build/userland/testbin/quinthuge \
build/userland/testbin/quintmat \
build/userland/testbin/quintsort \
build/userland/testbin/randcall \
build/userland/testbin/readwritetest \
build/userland/testbin/redirect \
build/userland/testbin/rmdirtest \
build/userland/testbin/rmtest \
build/userland/testbin/sbrktest \
build/userland/testbin/schedpong \
build/userland/testbin/shelltest \
build/userland/testbin/shll \
build/userland/testbin/sink \
build/userland/testbin/sort \
build/userland/testbin/sparsefile \
build/userland/testbin/spinner \
build/userland/testbin/stacktest \
build/userland/testbin/sty \
build/userland/testbin/tail \
build/userland/testbin/tictac \
build/userland/testbin/triplehuge \
build/userland/testbin/triplemat \
build/userland/testbin/triplesort \
build/userland/testbin/usemtest \
build/userland/testbin/waiter \
build/userland/testbin/zero \
common/gcc-millicode \
common/libc/arch/mips \
common/libc/printf \
common/libc/stdlib \
common/libc/string \
common/libtest161 \
kern/arch/mips/locore \
kern/arch/mips/syscall \
kern/arch/mips/thread \
kern/arch/mips/vm \
kern/arch/sys161/dev \
kern/arch/sys161/main \
kern/compile/ASST2 \
kern/compile/ASST3 \
kern/compile/DUMBVM \
kern/dev/generic \
kern/dev/lamebus \
kern/fs/semfs \
kern/fs/sfs \
kern/lib \
kern/main \
kern/proc \
kern/synchprobs \
kern/syscall \
kern/test \
kern/thread \
kern/vfs \
kern/vm \
userland/bin/cat \
userland/bin/cp \
userland/bin/false \
userland/bin/ln \
userland/bin/ls \
userland/bin/mkdir \
userland/bin/mv \
userland/bin/pwd \
userland/bin/rm \
userland/bin/rmdir \
userland/bin/sh \
userland/bin/sync \
userland/bin/tac \
userland/bin/true \
userland/lib/crt0/mips \
userland/lib/hostcompat \
userland/lib/libc/arch/mips \
userland/lib/libc/stdio \
userland/lib/libc/stdlib \
userland/lib/libc/string \
userland/lib/libc/time \
userland/lib/libc/unix \
userland/lib/libtest \
userland/sbin/dumpsfs \
userland/sbin/halt \
userland/sbin/mksfs \
userland/sbin/poweroff \
userland/sbin/reboot \
userland/sbin/sfsck \
userland/testbin/add \
userland/testbin/argtest \
userland/testbin/badcall \
userland/testbin/bigexec \
userland/testbin/bigfile \
userland/testbin/bigfork \
userland/testbin/bigseek \
userland/testbin/bloat \
userland/testbin/closetest \
userland/testbin/conman \
userland/testbin/consoletest \
userland/testbin/crash \
userland/testbin/ctest \
userland/testbin/dirconc \
userland/testbin/dirseek \
userland/testbin/dirtest \
userland/testbin/f_test \
userland/testbin/factorial \
userland/testbin/farm \
userland/testbin/faulter \
userland/testbin/fileonlytest \
userland/testbin/filetest \
userland/testbin/forkbomb \
userland/testbin/forktest \
userland/testbin/frack \
userland/testbin/guzzle \
userland/testbin/hash \
userland/testbin/hog \
userland/testbin/huge \
userland/testbin/kitchen \
userland/testbin/malloctest \
userland/testbin/matmult \
userland/testbin/multiexec \
userland/testbin/opentest \
userland/testbin/palin \
userland/testbin/parallelvm \
userland/testbin/poisondisk \
userland/testbin/psort \
userland/testbin/quinthuge \
userland/testbin/quintmat \
userland/testbin/quintsort \
userland/testbin/randcall \
userland/testbin/readwritetest \
userland/testbin/redirect \
userland/testbin/rmdirtest \
userland/testbin/rmtest \
userland/testbin/sbrktest \
userland/testbin/schedpong \
userland/testbin/shelltest \
userland/testbin/shll \
userland/testbin/sink \
userland/testbin/sort \
userland/testbin/sparsefile \
userland/testbin/spinner \
userland/testbin/stacktest \
userland/testbin/sty \
userland/testbin/tail \
userland/testbin/tictac \
userland/testbin/triplehuge \
userland/testbin/triplemat \
userland/testbin/triplesort \
userland/testbin/usemtest \
userland/testbin/userthreads \
userland/testbin/waiter \
userland/testbin/zero \
<file_sep>/Debug/kern/vm/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../kern/vm/addrspace.c \
../kern/vm/copyinout.c \
../kern/vm/kmalloc.c \
../kern/vm/myvm.c
OBJS += \
./kern/vm/addrspace.o \
./kern/vm/copyinout.o \
./kern/vm/kmalloc.o \
./kern/vm/myvm.o
C_DEPS += \
./kern/vm/addrspace.d \
./kern/vm/copyinout.d \
./kern/vm/kmalloc.d \
./kern/vm/myvm.d
# Each subdirectory must supply rules for building sources it contributes
kern/vm/%.o: ../kern/vm/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/Debug/kern/dev/lamebus/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../kern/dev/lamebus/beep_ltimer.c \
../kern/dev/lamebus/con_lscreen.c \
../kern/dev/lamebus/con_lser.c \
../kern/dev/lamebus/emu.c \
../kern/dev/lamebus/emu_att.c \
../kern/dev/lamebus/lamebus.c \
../kern/dev/lamebus/lhd.c \
../kern/dev/lamebus/lhd_att.c \
../kern/dev/lamebus/lnet.c \
../kern/dev/lamebus/lnet_att.c \
../kern/dev/lamebus/lrandom.c \
../kern/dev/lamebus/lrandom_att.c \
../kern/dev/lamebus/lscreen.c \
../kern/dev/lamebus/lscreen_att.c \
../kern/dev/lamebus/lser.c \
../kern/dev/lamebus/lser_att.c \
../kern/dev/lamebus/ltimer.c \
../kern/dev/lamebus/ltimer_att.c \
../kern/dev/lamebus/ltrace.c \
../kern/dev/lamebus/ltrace_att.c \
../kern/dev/lamebus/random_lrandom.c \
../kern/dev/lamebus/rtclock_ltimer.c
OBJS += \
./kern/dev/lamebus/beep_ltimer.o \
./kern/dev/lamebus/con_lscreen.o \
./kern/dev/lamebus/con_lser.o \
./kern/dev/lamebus/emu.o \
./kern/dev/lamebus/emu_att.o \
./kern/dev/lamebus/lamebus.o \
./kern/dev/lamebus/lhd.o \
./kern/dev/lamebus/lhd_att.o \
./kern/dev/lamebus/lnet.o \
./kern/dev/lamebus/lnet_att.o \
./kern/dev/lamebus/lrandom.o \
./kern/dev/lamebus/lrandom_att.o \
./kern/dev/lamebus/lscreen.o \
./kern/dev/lamebus/lscreen_att.o \
./kern/dev/lamebus/lser.o \
./kern/dev/lamebus/lser_att.o \
./kern/dev/lamebus/ltimer.o \
./kern/dev/lamebus/ltimer_att.o \
./kern/dev/lamebus/ltrace.o \
./kern/dev/lamebus/ltrace_att.o \
./kern/dev/lamebus/random_lrandom.o \
./kern/dev/lamebus/rtclock_ltimer.o
C_DEPS += \
./kern/dev/lamebus/beep_ltimer.d \
./kern/dev/lamebus/con_lscreen.d \
./kern/dev/lamebus/con_lser.d \
./kern/dev/lamebus/emu.d \
./kern/dev/lamebus/emu_att.d \
./kern/dev/lamebus/lamebus.d \
./kern/dev/lamebus/lhd.d \
./kern/dev/lamebus/lhd_att.d \
./kern/dev/lamebus/lnet.d \
./kern/dev/lamebus/lnet_att.d \
./kern/dev/lamebus/lrandom.d \
./kern/dev/lamebus/lrandom_att.d \
./kern/dev/lamebus/lscreen.d \
./kern/dev/lamebus/lscreen_att.d \
./kern/dev/lamebus/lser.d \
./kern/dev/lamebus/lser_att.d \
./kern/dev/lamebus/ltimer.d \
./kern/dev/lamebus/ltimer_att.d \
./kern/dev/lamebus/ltrace.d \
./kern/dev/lamebus/ltrace_att.d \
./kern/dev/lamebus/random_lrandom.d \
./kern/dev/lamebus/rtclock_ltimer.d
# Each subdirectory must supply rules for building sources it contributes
kern/dev/lamebus/%.o: ../kern/dev/lamebus/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/Debug/userland/lib/libc/string/subdir.mk
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
../userland/lib/libc/string/memcmp.c \
../userland/lib/libc/string/strerror.c \
../userland/lib/libc/string/strtok.c
OBJS += \
./userland/lib/libc/string/memcmp.o \
./userland/lib/libc/string/strerror.o \
./userland/lib/libc/string/strtok.o
C_DEPS += \
./userland/lib/libc/string/memcmp.d \
./userland/lib/libc/string/strerror.d \
./userland/lib/libc/string/strtok.d
# Each subdirectory must supply rules for building sources it contributes
userland/lib/libc/string/%.o: ../userland/lib/libc/string/%.c
@echo 'Building file: $<'
@echo 'Invoking: Cross GCC Compiler'
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
<file_sep>/kern/vm/addrspace.c
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004, 2005, 2008, 2009
* The President and Fellows of Harvard College.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the 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 UNIVERSITY 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 UNIVERSITY 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.
*/
#include <types.h>
#include <kern/errno.h>
#include <lib.h>
#include <addrspace.h>
#include <vm.h>
#include <proc.h>
#include <synch.h>
#include <bitmap.h>
struct addrspace *
as_create(void) {
struct addrspace *as;
as = kmalloc(sizeof(struct addrspace));
if (as == NULL) {
return NULL;
}
as->pte = NULL;
as->pte_last = NULL;
as->region = NULL;
as->stack_ptr = USERSTACK;
as->heap_bottom = (vaddr_t) 0;
as->heap_top = (vaddr_t) 0;
return as;
}
int as_copy(struct addrspace *old_addrspace, struct addrspace **ret) {
// if(swapping){
// lock_acquire(paging_lock);
// }
struct addrspace *new_as;
new_as = as_create();
if (new_as == NULL) {
return ENOMEM;
}
//Copy regions
struct region *old_region = old_addrspace->region;
struct region *temp, *newreg;
while (old_region != NULL) {
if (new_as->region == NULL) {
new_as->region = (struct region *) kmalloc(sizeof(struct region));
if (new_as->region == NULL) {
return ENOMEM;
}
new_as->region->next = NULL;
newreg = new_as->region;
} else {
for (temp = new_as->region; temp->next != NULL; temp = temp->next)
;
newreg = (struct region *) kmalloc(sizeof(struct region));
if (newreg == NULL) {
return ENOMEM;
}
temp->next = newreg;
}
newreg->base_vaddr = old_region->base_vaddr;
newreg->num_pages = old_region->num_pages;
newreg->permission = old_region->permission;
newreg->old_permission = old_region->old_permission;
newreg->next = NULL;
old_region = old_region->next;
}
struct PTE *old_pte_itr = old_addrspace->pte;
struct PTE *new_pte;
struct PTE *temp1;
while (old_pte_itr != NULL) {
if (new_as->pte == NULL) {
new_as->pte = (struct PTE *) kmalloc(sizeof(struct PTE));
if (new_as->pte == NULL) {
return ENOMEM;
}
if (swapping) {
new_as->pte->pte_lock = lock_create("pte_lock");
lock_acquire(new_as->pte->pte_lock);
lock_acquire(old_pte_itr->pte_lock);
}
new_as->pte->next = NULL;
new_pte = new_as->pte;
if (swapping) {
new_as->pte_last = new_as->pte;
}
} else {
if (!swapping) {
for (temp1 = new_as->pte; temp1->next != NULL;
temp1 = temp1->next)
;
}
new_pte = (struct PTE *) kmalloc(sizeof(struct PTE));
if (new_pte == NULL) {
return ENOMEM;
}
if (swapping) {
new_pte->pte_lock = lock_create("pte_lock");
lock_acquire(new_pte->pte_lock);
lock_acquire(old_pte_itr->pte_lock);
new_as->pte_last->next = new_pte;
new_as->pte_last = new_pte;
}
if (!swapping) {
temp1->next = new_pte;
}
}
new_pte->vpn = old_pte_itr->vpn;
new_pte->permission = old_pte_itr->permission;
new_pte->state = DISK;
// if (swapping) {
// unsigned x;
// if (!bitmap_alloc(swapdisk_bitmap, &x)) {
// new_pte->swapdisk_pos = x * PAGE_SIZE;
// } else {
// panic("\nRan out of swapdisk");
// }
// }
swapdisk_index++;
new_pte->swapdisk_pos = swapdisk_index * PAGE_SIZE;
new_pte->next = NULL;
if (swapping) {
// KASSERT(old_pte_itr->state == MEM);
// KASSERT(old_pte_itr->ppn != (paddr_t)0);
if (old_pte_itr->state == DISK) {
// lock_acquire(old_pte_itr->pte_lock);
old_pte_itr->ppn = page_alloc(old_pte_itr);
spinlock_acquire(&coremap_spinlock);
coremap[(old_pte_itr->ppn / PAGE_SIZE)].busy = 1;
spinlock_release(&coremap_spinlock);
swapin(old_pte_itr->swapdisk_pos, old_pte_itr->ppn);
spinlock_acquire(&coremap_spinlock);
coremap[(old_pte_itr->ppn / PAGE_SIZE)].state = CLEAN;
coremap[(old_pte_itr->ppn / PAGE_SIZE)].clock = true;
spinlock_release(&coremap_spinlock);
old_pte_itr->state = MEM;
// lock_release(old_pte_itr->pte_lock);
}
// vm_tlbshootdownvaddr(old_pte_itr->vpn);
swapout(new_pte->swapdisk_pos, old_pte_itr->ppn);
new_pte->state = DISK;
spinlock_acquire(&coremap_spinlock);
coremap[(old_pte_itr->ppn / PAGE_SIZE)].busy = 0;
spinlock_release(&coremap_spinlock);
new_pte->ppn = (paddr_t) 0;
} else {
new_pte->ppn = page_alloc(new_pte);
if (new_pte->ppn == (paddr_t) 0) {
return ENOMEM;
}
memmove((void *) PADDR_TO_KVADDR(new_pte->ppn),
(const void *) PADDR_TO_KVADDR(old_pte_itr->ppn),
PAGE_SIZE);
}
if (swapping) {
lock_release(old_pte_itr->pte_lock);
lock_release(new_pte->pte_lock);
}
old_pte_itr = old_pte_itr->next;
}
new_as->heap_bottom = old_addrspace->heap_bottom;
new_as->heap_top = old_addrspace->heap_top;
new_as->stack_ptr = old_addrspace->stack_ptr;
// if(swapping){
// lock_release(paging_lock);
// }
*ret = new_as;
return 0;
}
void as_destroy(struct addrspace *as) {
// if(swapping){
// lock_acquire(paging_lock);
// }
if (as != NULL) {
vm_tlbshootdown_all();
struct region *reg = as->region;
struct region *temp1;
while (reg != NULL) {
temp1 = reg;
reg = reg->next;
kfree(temp1);
}
struct PTE *pte_itr = as->pte;
struct PTE *temp2;
while (pte_itr != NULL) {
if (swapping) {
lock_acquire(pte_itr->pte_lock);
if (pte_itr->state == MEM) {
page_free(pte_itr->ppn);
}
// KASSERT(bitmap_isset(swapdisk_bitmap, (pte_itr->swapdisk_pos / PAGE_SIZE)));
// bitmap_unmark(swapdisk_bitmap,(pte_itr->swapdisk_pos / PAGE_SIZE));
} else {
page_free(pte_itr->ppn);
}
temp2 = pte_itr;
if (swapping) {
lock_release(temp2->pte_lock);
lock_destroy(temp2->pte_lock);
}
pte_itr = pte_itr->next;
kfree(temp2);
}
kfree(as);
}
// if(swapping){
// lock_release(paging_lock);
// }
}
void as_activate(void) {
int i, spl;
struct addrspace *as;
as = proc_getas();
if (as == NULL) {
return;
}
/* Disable interrupts on this CPU while frobbing the TLB. */
spl = splhigh();
for (i = 0; i < NUM_TLB; i++) {
tlb_write(TLBHI_INVALID(i), TLBLO_INVALID(), i);
}
splx(spl);
}
void as_deactivate(void) {
}
int as_define_region(struct addrspace *as, vaddr_t vaddr, size_t memsize,
int readable, int writeable, int executable) {
//Aligning the region
memsize += vaddr & ~(vaddr_t) PAGE_FRAME;
vaddr &= PAGE_FRAME;
memsize = (memsize + PAGE_SIZE - 1) & PAGE_FRAME;
size_t num_pages;
num_pages = memsize / PAGE_SIZE;
struct region *reg_end;
if (as->region == NULL) {
as->region = (struct region *) kmalloc(sizeof(struct region));
if (as->region == NULL) {
return ENOMEM;
}
as->region->next = NULL;
reg_end = as->region;
} else {
for (reg_end = as->region; reg_end->next != NULL;
reg_end = reg_end->next)
;
reg_end->next = (struct region *) kmalloc(sizeof(struct region));
if (reg_end->next == NULL) {
return ENOMEM;
}
reg_end = reg_end->next;
reg_end->next = NULL;
}
reg_end->num_pages = num_pages;
reg_end->permission = 7 & (readable | writeable | executable);
reg_end->base_vaddr = vaddr;
as->heap_bottom = (vaddr + (PAGE_SIZE * num_pages)); //&PAGE_FRAME;
as->heap_top = as->heap_bottom;
return 0;
}
int as_prepare_load(struct addrspace *as) {
struct region * regionitr;
regionitr = as->region;
while (regionitr != NULL) {
regionitr->old_permission = regionitr->permission;
regionitr->permission = 7 & (010 | 001); //write + execute
regionitr = regionitr->next;
}
return 0;
}
int as_complete_load(struct addrspace *as) {
struct region * regionitr;
regionitr = as->region;
while (regionitr != NULL) {
regionitr->permission = regionitr->old_permission;
regionitr = regionitr->next;
}
return 0;
}
int as_define_stack(struct addrspace *as, vaddr_t *stackptr) {
/* Initial user-level stack pointer */
*stackptr = USERSTACK; // - (MYVM_STACKPAGES * PAGE_SIZE);
as->stack_ptr = USERSTACK; // - (MYVM_STACKPAGES * PAGE_SIZE);
return 0;
}
<file_sep>/kern/syscall/runprogram.c
/*
* Copyright (c) 2000, 2001, 2002, 2003, 2004, 2005, 2008, 2009
* The President and Fellows of Harvard College.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the 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 UNIVERSITY 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 UNIVERSITY 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.
*/
/*
* Sample/test code for running a user program. You can use this for
* reference when implementing the execv() system call. Remember though
* that execv() needs to do more than runprogram() does.
*/
#include <types.h>
#include <kern/errno.h>
#include <kern/fcntl.h>
#include <lib.h>
#include <proc.h>
#include <current.h>
#include <addrspace.h>
#include <vm.h>
#include <vfs.h>
#include <syscall.h>
#include <test.h>
#include <synch.h>
/*
* Load program "progname" and start running it in usermode.
* Does not return except on error.
*
* Calls vfs_open on progname and thus may destroy it.
*/
int
runprogram(char *progname)
{
// kprintf("\n\n\n***Inside runprogram.c\n\n\n");
struct addrspace *as;
struct vnode *v;
vaddr_t entrypoint, stackptr;
int result;
/* Open the file. */
result = vfs_open(progname, O_RDONLY, 0, &v);
if (result) {
return result;
}
/* We should be a new process. */
KASSERT(proc_getas() == NULL);
/* Create a new address space. */
as = as_create();
if (as == NULL) {
vfs_close(v);
return ENOMEM;
}
/* Switch to it and activate it. */
proc_setas(as);
as_activate();
//logic for creating console streams
//console in
if(curproc->proc_filedesc[0]==NULL){
struct vnode *ret_in; //empty nvnode
struct filedesc *filedesc_ptr_in;
filedesc_ptr_in = kmalloc(sizeof(*filedesc_ptr_in));
if(filedesc_ptr_in == NULL){
vfs_close(v);
return ENOMEM;
}
mode_t mode = 0664;
filedesc_ptr_in->name = kstrdup("con:");
filedesc_ptr_in->flags = O_RDONLY;
int returner_in = vfs_open(filedesc_ptr_in->name, filedesc_ptr_in->flags, mode,
&ret_in);
if (returner_in) {
vfs_close(v);
kfree(filedesc_ptr_in);
return returner_in;
}
filedesc_ptr_in->fd_lock = lock_create("con:input"); //not sure when i should use this lock
if(filedesc_ptr_in->fd_lock == NULL){
vfs_close(v);
kfree(filedesc_ptr_in);
return ENOMEM;
}
filedesc_ptr_in->isempty = 0; //not empty
filedesc_ptr_in->fd_vnode = ret_in; //pointer to vnode object to be stored in filedesc->vnode
filedesc_ptr_in->read_count = 1;
filedesc_ptr_in->offset = 0;
filedesc_ptr_in->fd_refcount = 1;
curproc->proc_filedesc[0] = filedesc_ptr_in;
//output stream
struct vnode *ret_out; //empty nvnode
struct filedesc *filedesc_ptr_out;
mode = 0664;
filedesc_ptr_out = kmalloc(sizeof(*filedesc_ptr_out));
if(filedesc_ptr_out == NULL){
vfs_close(v);
kfree(filedesc_ptr_in);
return ENOMEM;
}
filedesc_ptr_out->flags = O_WRONLY;
filedesc_ptr_out->name = kstrdup("con:");
int returner_out = vfs_open(filedesc_ptr_out->name, filedesc_ptr_out->flags, mode,
&ret_out);
if (returner_out) {
vfs_close(v);
kfree(filedesc_ptr_in);
kfree(filedesc_ptr_out);
return returner_out;
}
filedesc_ptr_out->fd_lock = lock_create("con:output"); //not sure when i should use this lock
if(filedesc_ptr_out->fd_lock == NULL){
vfs_close(v);
kfree(filedesc_ptr_in);
kfree(filedesc_ptr_out);
return ENOMEM;
}
filedesc_ptr_out->isempty = 0; //not empty
filedesc_ptr_out->fd_vnode = ret_out; //pointer to vnode object to be stored in filedesc->vnode
filedesc_ptr_out->read_count = 1;
filedesc_ptr_out->offset = 0;
filedesc_ptr_out->fd_refcount = 1;
curproc->proc_filedesc[1] = filedesc_ptr_out;
//console err
struct vnode *ret_err; //empty nvnode
struct filedesc *filedesc_ptr_err;
mode = 0664;
filedesc_ptr_err = kmalloc(sizeof(*filedesc_ptr_err));
if(filedesc_ptr_err == NULL){
vfs_close(v);
kfree(filedesc_ptr_in);
kfree(filedesc_ptr_out);
return ENOMEM;
}
filedesc_ptr_err->flags = O_WRONLY;
filedesc_ptr_err->name = kstrdup("con:");
int returner_err = vfs_open(filedesc_ptr_err->name, filedesc_ptr_err->flags, mode,
&ret_err);
if (returner_err) {
vfs_close(v);
kfree(filedesc_ptr_in);
kfree(filedesc_ptr_out);
kfree(filedesc_ptr_err);
return returner_err;
}
filedesc_ptr_err->fd_lock = lock_create("con:error"); //not sure when i should use this lock
if(filedesc_ptr_err->fd_lock == NULL){
vfs_close(v);
kfree(filedesc_ptr_in);
kfree(filedesc_ptr_out);
kfree(filedesc_ptr_err);
return ENOMEM;
}
filedesc_ptr_err->isempty = 0; //not empty
filedesc_ptr_err->fd_vnode = ret_err; //pointer to vnode object to be stored in filedesc->vnode
filedesc_ptr_err->read_count = 1;
filedesc_ptr_err->offset = 0;
filedesc_ptr_err->fd_refcount = 1;
curproc->proc_filedesc[2] = filedesc_ptr_err;
}
/* Load the executable. */
result = load_elf(v, &entrypoint);
if (result) {
/* p_addrspace will go away when curproc is destroyed */
vfs_close(v);
kfree(curproc->proc_filedesc[0]);
kfree(curproc->proc_filedesc[1]);
kfree(curproc->proc_filedesc[2]);
return result;
}
/* Done with the file now. */
vfs_close(v);
/* Define the user stack in the address space */
result = as_define_stack(as, &stackptr);
if (result) {
/* p_addrspace will go away when curproc is destroyed */
return result;
}
/* Warp to user mode. */
enter_new_process(0 /*argc*/, NULL /*userspace addr of argv*/,
NULL /*userspace addr of environment*/,
stackptr, entrypoint);
/* enter_new_process does not return. */
panic("enter_new_process returned\n");
// kprintf("process created, with name %s", curproc->p_name);
// kprintf("\n\n\n***Exiting runprogram.c\n\n\n");
return EINVAL;
}
| 1b4d2901dee4ab2e7878aec0823271485231127d | [
"C",
"Makefile"
]
| 33 | Makefile | SudharchithSonty/OperatingSystems | 4246eba5cdcdddcf93b0d295821ce57ae26f83dd | df4a496996dd0e0aeba7a153979119acd24a9ed4 |
refs/heads/master | <repo_name>nchristanto/Data-Engineering_pre-eliminary_kulina<file_sep>/pseudo_input.py
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 21 18:49:57 2018
@author: <NAME>
"""
input = 1345679
digit = list(str(input))
jlh = len(digit)
for i in range (jlh):
jlh_nol = jlh - i
number = digit[i].ljust(jlh_nol,'0')
print(number)
<file_sep>/prime.py
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 21 17:43:26 2018
@author: <NAME>
"""
"""bilangan prima antara 1-101"""
def prime(x) :
prim = True
if x >= 2 :
for i in range (2,x) :
if x % i == 0 :
prim = False
else :
prim = False
return prim
for i in range(1,101) :
if prime(i) :
print (i)
<file_sep>/fibonacci.py
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 21 17:47:14 2018
@author: <NAME>
"""
"""bilangan fibbonacci"""
a,b,c = 0,1,0
for i in range(10) :
print(a)
c = a+b
a = b
b = c
| 6ef21e5c91b5e5f76e170e3b78b91550914f6253 | [
"Python"
]
| 3 | Python | nchristanto/Data-Engineering_pre-eliminary_kulina | e6b718a102d9a30db373acdc3238106ef45d9d18 | 765a078571f37fe1acccb8cf63bb1b83274ecb2a |
refs/heads/master | <file_sep>import React, {Component} from 'react';
import {Table, Modal, ModalHeader, ModalBody, ModalFooter,
Button} from 'reactstrap';
import PropTypes from 'prop-types';
import qs from 'qs';
import {asyncUsernameToUserId} from 'components/utility/index';
import {getNewRatings} from 'codeforces-rating-system';
export default class StandingsPreview extends Component {
constructor(props) {
super(props);
this.state = {
standings: [],
rawData: [],
};
this.formatStandings = this.formatStandings.bind(this);
}
async componentWillReceiveProps(nextProps) {
const {rawData, classId} = nextProps;
if (this.state.rawData === rawData) return;
let standings = rawData.split('\n').filter((x)=> x);
standings = await Promise.all(standings.map(async (s) => {
const arr = s.split(',').map((x) => x.trim());
const position = parseInt(arr[0], 10);
const username = arr[1];
let userId;
let previousRating;
try {
userId = await asyncUsernameToUserId(username);
const ratingApiQs = qs.stringify({
classroomId: classId,
userIds: [userId], // TODO: Reduce number of api calls
});
const ratingApi = `/api/v1/ratings?${ratingApiQs}`;
let resp = await fetch(ratingApi, {
credentials: 'same-origin',
});
resp = await resp.json();
if (resp.status === 200 || resp.status === 202) {
previousRating = resp.data[0].currentRating;
} else throw resp;
} catch (err) {
console.log(err);
}
if (previousRating === -1) previousRating = 1500;
return {position, username, userId, previousRating};
}));
standings = getNewRatings(standings);
this.setState({standings, rawData});
}
formatStandings() {
const standings = this.state.standings;
const tr = standings.map((s)=>{
return (
<tr key={s.username}>
<td>{s.position}</td>
<td>{s.username}</td>
<td>{s.userId}</td>
<td>{s.newRating}</td>
<td>{s.previousRating}</td>
<td>{s.delta}</td>
</tr>
);
});
return (
<Table>
<thead>
<tr>
<th>Position</th>
<th>Username</th>
<th>UserId</th>
<th>New Rating</th>
<th>Previous Rating</th>
<th>Delta</th>
</tr>
</thead>
<tbody>
{tr}
</tbody>
</Table>
);
}
render() {
const {modalState, toggle, addStandings} = this.props;
return (
<Modal isOpen={modalState} toggle={toggle} className='modal-lg'>
<ModalHeader>Standings Preview</ModalHeader>
<ModalBody style={{
overflowX: 'auto',
}}>{this.formatStandings()}</ModalBody>
<ModalFooter>
<Button color="primary" onClick={()=>{
addStandings(this.state.standings);
}}>
Add Standings</Button>
<Button color="secondary" onClick={toggle}>Cancel</Button>
</ModalFooter>
</Modal>
);
}
}
StandingsPreview.propTypes = {
modalState: PropTypes.bool.isRequired,
toggle: PropTypes.func.isRequired,
rawData: PropTypes.string.isRequired,
classId: PropTypes.string.isRequired,
addStandings: PropTypes.func.isRequired,
};
<file_sep>import React, {Component} from 'react';
import {Row, Col, Table} from 'reactstrap';
import {Form, FormGroup, Input, Label, Button} from 'reactstrap';
import {UncontrolledDropdown, DropdownToggle, DropdownMenu, DropdownItem}
from 'reactstrap';
import {connect} from 'react-redux';
import Notifications, {error, success}
from 'react-notification-system-redux';
import Loadable from 'react-loading-overlay';
import {Redirect} from 'react-router-dom';
class ProblemList extends Component {
constructor(props) {
super(props);
this.state = {
loadingState: true,
loadingMessage: 'Fetching data...',
title: '',
problems: [],
view: 'normal',
ojname: '',
problemId: '',
redirectDashboard: false,
};
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.removeProblem = this.removeProblem.bind(this);
}
handleError(err) {
if (err.status) {
this.props.showNotification(error({
title: 'Error',
message: err.message,
autoDismiss: 500,
}));
}
console.error(err);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value,
});
}
async handleSubmit(e) {
e.preventDefault();
const {problemListId} = this.props.match.params;
this.setState({
loadingState: true,
loadingMessage: 'Adding Problem to List...',
});
const {ojname, problemId} = this.state;
try {
let resp = await fetch(`/api/v1/problembanks/${ojname}/${problemId}`, {
credentials: 'same-origin',
});
resp = await resp.json();
if (resp.status !== 200) throw resp;
const data = resp.data;
resp = await fetch(`/api/v1/problemlists/${problemListId}/problems`, {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data),
credentials: 'same-origin',
});
resp = await resp.json();
if (resp.status !== 201) throw resp;
const newProblems = [...this.state.problems];
if (resp.data) newProblems.push(resp.data);
this.setState({
problems: newProblems,
ojname: '',
problemId: '',
});
this.props.showNotification(success({
title: 'Success',
message: `Problem added: ${ojname}:${problemId}`,
}));
} catch (err) {
this.handleError(err);
} finally {
this.setState({
loadingState: false,
});
}
}
async componentWillMount() {
const {problemListId} = this.props.match.params;
try {
let resp = await fetch(`/api/v1/problemlists/${problemListId}`, {
method: 'GET',
credentials: 'same-origin',
});
resp = await resp.json();
if (resp.status !== 200) throw resp;
this.setState({
title: resp.data.title,
problems: resp.data.problems,
});
} catch (err) {
this.handleError(err);
} finally {
this.setState({
loadingState: false,
});
}
}
settingsList() {
return (
<UncontrolledDropdown>
<DropdownToggle className='fa fa-lg fa-cog' color='light'></DropdownToggle>
<DropdownMenu>
<DropdownItem>
<div
className='btn btn-primary btn-block'
onClick={()=>this.setState({view: 'addProblem'})}
> Add Problem </div>
</DropdownItem>
<DropdownItem>
<div
className='btn btn-danger btn-block'
onClick={()=>this.deleteProblemList()}
> Delete List </div>
</DropdownItem>
</DropdownMenu>
</UncontrolledDropdown>
);
}
async removeProblem(id) {
const {problemListId} = this.props.match.params;
try {
this.setState({
loadingState: true,
loadingMessage: 'Deleting Problem from List...',
});
let resp = await fetch(`/api/v1/problemlists/${problemListId}/problems/${id}`, {
method: 'DELETE',
credentials: 'same-origin',
});
resp = await resp.json();
if ( resp.status !== 201 ) throw resp;
const newProblems = this.state.problems.filter((x)=>x._id !== id);
this.setState({
problems: newProblems,
});
} catch (err) {
this.handleError(err);
} finally {
this.setState({
loadingState: false,
});
}
}
async deleteProblemList() {
const {problemListId} = this.props.match.params;
try {
this.setState({
loadingState: true,
loadingMessage: 'Deleting the entire list...',
});
let resp = await fetch(`/api/v1/problemlists/${problemListId}`, {
method: 'DELETE',
credentials: 'same-origin',
});
resp = await resp.json();
if (resp.status !== 201) throw resp;
this.setState({
redirectDashboard: true,
});
} catch (err) {
this.handleError(err);
} finally {
if (!this.state.redirectDashboard) {
this.setState({
loadingState: false,
});
}
}
}
problemListView() {
return (
<Table>
<thead>
<tr>
<th>#</th>
<th>Problem</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
{this.state.problems.map((p, index)=>{
return (
<tr key={p._id}>
<td>{index}</td>
<td>
<a href={p.link}>
{`${p.platform} - ${p.problemId} ${p.title}`}
</a>
</td>
<td className="text-center text-danger">
<i className="fa fa-times pointer" onClick={()=>this.removeProblem(p._id)}/>
</td>
</tr>
);
})}
</tbody>
</Table>
);
}
addProblemView() {
const {ojnames} = this.props;
const ojnamesOnly = ojnames.map((x)=>x.name);
const ojnamesMap = {};
ojnames.forEach((x)=>ojnamesMap[x.name] = x);
return (
<Col className="text-center">
<h1>Add Problem View</h1>
<Form onSubmit={this.handleSubmit}>
<FormGroup>
<Label>OJ Name</Label>
<Input type='select' name="ojname" onChange={this.handleInputChange}
value={this.state.ojname}
>
<option value='' disabled> Select a OJ</option>
{ojnamesOnly.map((x)=><option key={x} value={x}>{x}</option>)}
</Input>
</FormGroup>
<FormGroup>
<Label>Problem ID {this.state.ojname
? `(Match Regex: "${ojnamesMap[this.state.ojname].format}")`: ''}</Label>
<Input name="problemId" onChange={this.handleInputChange} value={this.state.problemId}
pattern={this.state.ojname?ojnamesMap[this.state.ojname].format:''}
/>
</FormGroup>
<Button type="submit" color="primary">Add</Button>{ ' ' }
<Button color="secondary" onClick={()=>this.setState({view:'normal'})}>Cancel</Button>
</Form>
</Col>
);
}
render() {
return (
<Loadable active={this.state.loadingState} spinner={true}
text={this.state.loadingMessage || 'Please wait a moment...'}>
<Notifications notifications={this.props.notifications}/>
{this.state.redirectDashboard && (<Redirect to={'/coach'}/>)}
<Row>
<Col>
<h1>Problem List: {this.state.title}</h1>
</Col>
<Col className='text-right'>
{this.settingsList()}
</Col>
</Row>
<Row>
<Col>
{this.problemListView()}
</Col>
{
this.state.view === 'addProblem'? this.addProblemView(): null
}
</Row>
</Loadable>
);
}
}
function mapStateToProps(state) {
return {
notifications: state.notifications,
user: state.user,
ojnames: state.ojnames,
};
}
function mapDispatchToProps(dispatch) {
return {
showNotification(msg) {
dispatch(msg);
},
};
}
export default connect(mapStateToProps, mapDispatchToProps)(ProblemList);
<file_sep>import React, {Component} from 'react';
import {Row, Col} from 'reactstrap';
import {connect} from 'react-redux';
import Notifications from 'react-notification-system-redux';
import ClassroomListContainer from './ClassroomListContainer';
import ProblemListContainer from './ProblemListContainer';
class Dashboard extends Component {
render() {
return (
<div>
<Notifications
notifications={this.props.notifications}
/>
<Row>
<Col>
<ClassroomListContainer {...this.props}/>
</Col>
<Col>
<ProblemListContainer {...this.props}/>
</Col>
</Row>
</div>
);
}
}
function mapStateToProps(state) {
return {
notifications: state.notifications,
user: state.user,
};
}
function mapDispatchToProps(dispatch) {
return {
showNotification(msg) {
dispatch(msg);
},
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);
<file_sep>import React from 'react';
import {LinkContainer} from 'react-router-bootstrap';
import {
Table, Row, Col, Button, UncontrolledDropdown, DropdownToggle, DropdownMenu,
DropdownItem,
} from 'reactstrap';
import PropTypes from 'prop-types';
import ProgressButton from 'react-progress-button';
import {success} from 'react-notification-system-redux';
/** Setting List */
function SettingsList({classId, name}) {
return (
<UncontrolledDropdown>
<DropdownToggle className='fa fa-lg fa-cog' color='light'></DropdownToggle>
<DropdownMenu>
<LinkContainer to={`/classroom/${classId}/addStudent`}>
<DropdownItem>
<Button color='primary' className='btn-block'> Add Student </Button>
</DropdownItem>
</LinkContainer>
<LinkContainer to={`/classroom/${classId}/removeStudent`}>
<DropdownItem>
<Button color='danger' className='btn-block'>Remove Student</Button>
</DropdownItem>
</LinkContainer>
</DropdownMenu>
</UncontrolledDropdown>
);
}
SettingsList.propTypes = {
classId: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
};
/** Student List */
async function syncAll(students, props) {
const usernames = students.map((s)=>s.username);
for (let username of usernames) {
try {
let resp = await fetch(`/api/v1/users/${username}/sync-solve-count`, {
method: 'PUT',
credentials: 'same-origin',
});
resp = await resp.json();
if (resp.status !== 202) throw resp;
} catch (err) {
console.error(`Error synching user: ${username}`, err);
}
}
props.showNotification(success({
title: 'Request Receieved',
message: 'Please wait while we process your request',
position: 'tr',
autoDismiss: 5,
}));
}
function StudentPortal(props) {
const {students, classId, name, owner} = props;
students.sort((a, b)=>{
return b.currentRating - a.currentRating;
});
let tabulatedStudentsList = students.map((s, ind) => (
<tr key={s._id}>
<td>{ind + 1}</td>
<td>
<LinkContainer to={`/users/profile/${s.username}`}>
<a>
{s.username}
</a>
</LinkContainer>
</td>
<td>{s.currentRating}</td>
</tr>
));
return (
<div className='text-center'>
<Row>
<Col>
<h2>Student Portal</h2>
</Col>
{
owner?
<Col className='text-right'>
<SettingsList classId={classId} name={name}/>
</Col>:
<span></span>
}
</Row>
<Row className="mb-1">
<Col>
<LinkContainer to={`/classroom/${classId}/leaderboard`}>
<Button color="primary">Leaderboard</Button>
</LinkContainer>
</Col>
<Col>
{
owner?
<ProgressButton
className="ml-1"
onClick={()=>syncAll(students, props)}
>
Sync All
</ProgressButton>: ''
}
</Col>
</Row>
<Table>
<thead>
<tr>
<th> Index </th>
<th> Username </th>
<th> Rating </th>
</tr>
</thead>
<tbody>
{ tabulatedStudentsList }
</tbody>
</Table>
</div>
);
}
StudentPortal.propTypes = {
classId: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
students: PropTypes.arrayOf(PropTypes.shape({
_id: PropTypes.string.isRequired,
username: PropTypes.string.isRequired,
})).isRequired,
owner: PropTypes.bool.isRequired,
};
export default StudentPortal;
<file_sep>import React, {Component} from 'react';
// import {LinkContainer} from 'react-router-bootstrap';
import {Row, Col, Table, Button} from 'reactstrap';
import {PropTypes} from 'prop-types';
import Spinner from 'react-spinkit';
import Loadable from 'react-loading-overlay';
import {success} from 'react-notification-system-redux';
export class OJSolve extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
showInputForOj: '',
};
this.unsetOjUsername = this.unsetOjUsername.bind(this);
this.setUsername = this.setUsername.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value,
});
}
async updateSolveCount() {
const {displayUser} = this.props;
const username = displayUser.username;
try {
this.setState({
loading: true,
});
let resp = await fetch(`/api/v1/users/${username}/sync-solve-count`, {
method: 'PUT',
credentials: 'same-origin',
});
resp = await resp.json();
if (resp.status !== 202) throw resp;
} catch (err) {
if (err.status) alert(err.message);
console.error(err);
} finally {
this.setState({
loading: false,
});
this.props.showNotification(success({
title: 'Request Receieved',
message: 'Please wait while we process your request',
position: 'tr',
autoDismiss: 5,
}));
}
}
async unsetOjUsername(username, ojname) {
const {updateOjStats} = this.props;
this.setState({
loading: true,
});
try {
let resp = await fetch(`/api/v1/users/${username}/unset-oj-username/${ojname}`, {
method: 'PUT',
credentials: 'same-origin',
});
resp = await resp.json();
if ( resp.status !== 201 ) throw resp;
updateOjStats(resp.data);
} catch (err) {
if (err.status) alert(err.message);
console.error(err);
}
this.setState({
loading: false,
});
}
async setUsername(ojname) {
const {displayUser, updateOjStats} = this.props;
const {username} = displayUser;
this.setState({
loading: true,
});
const userId = this.state.ojusername;
try {
let resp = await fetch(`/api/v1/users/${username}/set-oj-username/${ojname}/${userId}`, {
method: 'PUT',
credentials: 'same-origin',
});
resp = await resp.json();
if ( resp.status !== 201) throw resp;
updateOjStats(resp.data);
} catch (err) {
if (err.status) alert(err.message);
console.error(err);
}
this.setState({
loading: false,
});
}
ojUsernameField(oj, index) {
const {displayUser, owner} = this.props;
const {username} = displayUser;
const {showInputForOj} = this.state;
const displayOjUsername = (
<span>
{oj.userIds[0]}
{owner? <i
className="fa fa-times text-danger ml-1 pointer"
onClick={()=>this.unsetOjUsername(username, oj.ojname)}
/>: ''}
</span>
);
const inputForm = (
<div>
<input type='text' name='ojusername' onChange={this.handleInputChange}/>
<Button color='primary ml-1' onClick={()=>this.setUsername(oj.ojname)}>
Set
</Button>
</div>
);
const setUsername = (
<div>
{ owner
? (<div>
{showInputForOj === oj.ojname
? inputForm
: <span
className="btn-link pointer"
onClick={()=>this.setState({showInputForOj: oj.ojname})}
>
Set Username
</span>
}
</div>)
: <span>Not Set</span>
}
</div>
);
return oj.userIds[0]? displayOjUsername: setUsername;
}
render() {
const {displayUser} = this.props;
const ojStats = displayUser.ojStats;
const ojSolve = ojStats? (
<Table>
<thead>
<tr>
<th>Index</th>
<th>OJ</th>
<th>UID</th>
<th>Solve</th>
</tr>
</thead>
<tbody>
{displayUser.ojStats.map((oj, index)=>{
return (
<tr key={oj._id}>
<td>{index}</td>
<td>{oj.ojname}</td>
<td>{this.ojUsernameField(oj, index)}</td>
<td>{oj.solveCount}</td>
</tr>
);
})}
</tbody>
</Table>
): (
<span>Loading</span>
);
const totalSolve = ojStats?
ojStats
.map((oj)=>oj.solveCount?oj.solveCount:0)
.reduce((total, current)=>{
return total+current;
}, 0):
0;
return (
<Loadable active={this.state.loading}
spinner={true}
text='Please wait a moment...'>
<Row>
<Col xs="2"></Col>
<Col xs="8">
<h4>Solve Count: {totalSolve}</h4>
</Col>
<Col xs="2">
{
this.state.loading?
<Spinner name="circle"/>:
<i className="fa fa-refresh btn" title="Sync All OJ"
onClick={()=>this.updateSolveCount()}/>
}
</Col>
</Row>
{ojSolve}
</Loadable>
);
}
}
OJSolve.propTypes = {
displayUser: PropTypes.shape(),
updateOjStats: PropTypes.func.isRequired,
owner: PropTypes.bool.isRequired,
};
<file_sep>import React from 'react';
import {Row, Col, ListGroup, ListGroupItem} from 'reactstrap';
import {LinkContainer} from 'react-router-bootstrap';
import {PropTypes} from 'prop-types';
import {
RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar,
ResponsiveContainer,
} from 'recharts';
import {OJSolve} from './OJSolve.js';
function DrawRadarChart({userRootStats}) {
if ( !userRootStats ) {
return (
<span>Loading</span>
);
}
const children = userRootStats.children;
const data = children.map((child)=>{
const value = child.total? child.user/child.total: 0;
return {
subject: child.title,
A: value,
};
});
return (
<ResponsiveContainer width='100%' aspect={4.0/3.0}>
<RadarChart data={data}>
<PolarGrid />
<PolarAngleAxis dataKey="subject" />
<PolarRadiusAxis domain={[0, 1]}/>
<Radar dataKey="A" stroke='#8884d8' fill='#8884d8'
fillOpacity={0.6} />
</RadarChart>
</ResponsiveContainer>
);
}
DrawRadarChart.propTypes = {
userRootStats: PropTypes.shape(),
};
export function Profile(props) {
const {user, classrooms, displayUser, updateOjStats} = props;
const loadingInfo = displayUser.username === undefined;
const owner = user.username === displayUser.username;
const {userRootStats} = displayUser;
const personalInfo = loadingInfo? <span>Loading</span>: (
<ListGroup className="d-inline-flex">
{
owner?
<ListGroupItem>
<i className="fa fa-envelope"></i> {user.email}
</ListGroupItem>: ''
}
<ListGroupItem>
<i className="fa fa-user"></i> {displayUser.username}
</ListGroupItem>
{
owner?
<ListGroupItem>
<i className="fa fa-key"></i> Change Password
</ListGroupItem>: ''
}
<ListGroupItem>
<i className="fa fa-users"></i> {
displayUser.status[0].toUpperCase().slice(0, 1) +
displayUser.status.slice(1)
}
</ListGroupItem>
</ListGroup>
);
const classroomPortal = classrooms.length ? (
<ListGroup className="d-inline-flex">
{classrooms.map((val, index)=>{
return (
<LinkContainer to={`/classroom/${val._id}`} key={val._id}>
<ListGroupItem className="btn-link">
{`${val.coach.username}/${val.name}`}
</ListGroupItem>
</LinkContainer>
);
})}
</ListGroup>):
<span>Not enrolled in any class</span>;
return (
<div>
<div className="text-center">
<h3> Profile Page </h3>
</div>
<Row className="align-items justify-content-center">
<Col className="text-center">
<div>
<h4>Personal Info</h4>
{personalInfo}
</div>
</Col>
<Col className="text-center">
<div>
<h4>Classrooms</h4>
{classroomPortal}
</div>
</Col>
<Col className="text-center" xs={12}>
<div>
<h4>Overview</h4>
<DrawRadarChart userRootStats={userRootStats}/>
</div>
</Col>
<Col className="text-center">
<OJSolve {...props}
displayUser={displayUser} updateOjStats={updateOjStats} owner={owner}
/>
</Col>
</Row>
</div>
);
};
Profile.propTypes = {
user: PropTypes.shape(),
classrooms: PropTypes.arrayOf(PropTypes.shape()),
displayUser: PropTypes.shape(),
updateOjStats: PropTypes.func.isRequired,
};
<file_sep>import React, {Component} from 'react';
import {connect} from 'react-redux';
import {withRouter} from 'react-router-dom';
import {LinkContainer} from 'react-router-bootstrap';
import {
Nav, NavItem, Dropdown, DropdownItem, DropdownToggle, DropdownMenu, NavLink,
} from 'reactstrap';
import PropTypes from 'prop-types';
function mapStateToProps(state) {
return {
user: state.user,
};
}
function mapDispatchToProps(dispatch) {
return {};
}
class Header extends Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = {
dropdownOpen: false,
};
}
toggle() {
this.setState({
dropdownOpen: !this.state.dropdownOpen,
});
}
render() {
const path = this.props.location.pathname;
const isClassroomRegex = /^\/classroom/;
const isClassroom = isClassroomRegex.exec(path)?true:false;
const classId = path.split('/')[2];
const {username} = this.props.user;
const tools = (
<Dropdown nav isOpen={this.state.dropdownOpen} toggle={this.toggle}>
<DropdownToggle nav caret>
Tools
</DropdownToggle>
<DropdownMenu>
<LinkContainer to={`/classroom/${classId}/whoSolvedIt`}>
<DropdownItem>Who Solved It?</DropdownItem>
</LinkContainer>
</DropdownMenu>
</Dropdown>
);
return (
<div>
<h1 className='text-center'> CPPS </h1>
<Nav tabs>
<NavItem>
<NavLink href='/'>
<i className='fa fa-home mr-1'></i>
Home
</NavLink>
</NavItem>
<NavItem>
<LinkContainer to='/coach'>
<NavLink>Dashboard</NavLink>
</LinkContainer>
</NavItem>
{isClassroom?
<NavItem>
<LinkContainer to={`/classroom/${classId}`}>
<NavLink>Classroom</NavLink>
</LinkContainer>
</NavItem>:
<span></span>
}
{/* Tools */}
{isClassroom ? tools: <span></span>}
<span className="ml-auto"></span>
<NavItem>
<NavLink href='/admin/dashboard'>
<i className='fa fa-dashboard mr-1'></i>
Admin
</NavLink>
</NavItem>
<NavItem>
<LinkContainer to={`/users/profile/${username}`}>
<NavLink>
<i className='fa fa-user mr-1'></i>
Profile
</NavLink>
</LinkContainer>
</NavItem>
<NavItem>
<NavLink href='/user/logout'>
<i className='fa fa-sign-out mr-1'></i>
Logout
</NavLink>
</NavItem>
</Nav>
</div>
);
}
}
Header.propTypes = {
location: PropTypes.shape({
pathname: PropTypes.string.isRequired,
}),
user: PropTypes.shape({
username: PropTypes.string.isRequired,
}),
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Header));
<file_sep>import React, {Component} from 'react';
import {LinkContainer} from 'react-router-bootstrap';
import {
Row, Col, Button, UncontrolledDropdown, DropdownToggle, DropdownMenu,
DropdownItem,
} from 'reactstrap';
import PropTypes from 'prop-types';
import StudentPortal from 'components/studentPortal/StudentPortal';
import ContestPortalContainer from
'components/contestPortal/ContestPortalContainer';
import Notifications from 'react-notification-system-redux';
/** Setting List */
function SettingsList({classId, name}) {
return (
<UncontrolledDropdown>
<DropdownToggle className='fa fa-lg fa-cog' color='light'></DropdownToggle>
<DropdownMenu>
<LinkContainer to={{
pathname: `/classroom/${classId}/deleteClass`,
state: {
name: name,
},
}}>
<DropdownItem>
<Button color='danger' className='btn-block'> Delete Class </Button>
</DropdownItem>
</LinkContainer>
</DropdownMenu>
</UncontrolledDropdown>
);
}
SettingsList.propTypes = {
classId: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
};
class Classroom extends Component {
render() {
const {classId, name, owner} = this.props;
const {notifications} = this.props;
return (
<div>
<Notifications
notifications={notifications}
/>
<Row className='align-items-center'>
<Col xs='2' className='text-left'>
<LinkContainer to='/coach'>
<div className='btn'>
<i className='fa fa-lg fa-arrow-left'></i>
</div>
</LinkContainer>
</Col>
<Col xs='8'>
<h1 className='text-center'>{this.props.name} </h1>
</Col>
<Col xs='2' className='text-right'>
{
owner?
<SettingsList classId={classId} name={name}/>:
<span></span>
}
</Col>
</Row>
<Row>
<Col>
<StudentPortal
{...this.props}
students={this.props.students}
classId={classId}
name={name}
owner={owner}
/>
</Col>
<Col>
<ContestPortalContainer classId={classId} owner={owner} />
</Col>
</Row>
</div>
);
}
}
/** PropTypes */
Classroom.propTypes = {
classId: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
students: PropTypes.arrayOf(PropTypes.shape({
_id: PropTypes.string.isRequired,
username: PropTypes.string.isRequired,
})).isRequired,
owner: PropTypes.bool.isRequired,
};
export default Classroom;
<file_sep>import React, {Component} from 'react';
import ClassroomList from './ClassroomList';
export default class ClassroomListContainer extends Component {
constructor(props) {
super(props);
this.state = {
classDetails: [],
};
}
async componentDidMount() {
try {
const api = '/api/v1/classrooms';
let resp = await fetch(api, {
method: 'get',
headers: {'Content-Type': 'application/json'},
credentials: 'same-origin',
});
resp = await resp.json();
if (resp.status !== 200) {
throw resp;
}
this.setState({
classDetails: resp.data,
});
return;
} catch (err) {
if (err.status) alert(err.message);
console.log(err);
return;
}
}
render() {
return <ClassroomList classrooms={this.state.classDetails}/>;
}
}
<file_sep>import React from 'react';
import {Link} from 'react-router-dom';
import {LinkContainer} from 'react-router-bootstrap';
import {
Table, Row, Col, Button, UncontrolledDropdown, DropdownToggle, DropdownMenu,
DropdownItem,
} from 'reactstrap';
import PropTypes from 'prop-types';
/** Setting List */
function SettingsList({classId}) {
return (
<UncontrolledDropdown>
<DropdownToggle className='fa fa-lg fa-cog' color='light'></DropdownToggle>
<DropdownMenu>
<LinkContainer to={`/classroom/${classId}/contest/add-contest`}>
<DropdownItem>
<Button color='primary' className='btn-block'> Add Contest </Button>
</DropdownItem>
</LinkContainer>
</DropdownMenu>
</UncontrolledDropdown>
);
}
SettingsList.propTypes = {
classId: PropTypes.string.isRequired,
};
/** Contest List */
function ContestPortal(props) {
const {classId, data, owner} = props;
let tabulatedContestList = data.map((s, ind) => (
<tr key={s._id}>
<td>{ind + 1}</td>
<td>
<Link to={`/classroom/${classId}/contest/${s._id}`}> {s.name} </Link>
</td>
</tr>
));
return (
<div className='text-center'>
<Row>
<Col>
<h2>Contest Portal</h2>
</Col>
{
owner?
<Col className='text-right'>
<SettingsList classId={classId}/>
</Col>:
<span></span>
}
</Row>
<Table>
<thead>
<tr>
<th> Index </th>
<th> Contest </th>
</tr>
</thead>
<tbody>
{ tabulatedContestList }
</tbody>
</Table>
</div>
);
}
ContestPortal.propTypes = {
classId: PropTypes.string.isRequired,
data: PropTypes.arrayOf(PropTypes.shape({
_id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
})).isRequired,
owner: PropTypes.bool.isRequired,
};
export default ContestPortal;
| 60171fab40356cc50a64fefc0ed7106c508359b7 | [
"JavaScript"
]
| 10 | JavaScript | nuronialBlock/coach-cpps | 4ba0a42453f214d3435ba93a326f8651749edc5d | 565feae3ce8e3655f2fb08cfac882aa3a0ceb285 |
refs/heads/main | <file_sep>var num = 50/(1.7320508075);
var high = 50*(1.7320508075);
let secondsRadius;
let minutesRadius;
let hoursRadius;
function setup() {
createCanvas(400, 400);
let radius = min(width, height) / 2;
secondsRadius = radius * 0.71;
minutesRadius = radius * 0.6;
hoursRadius = radius * 0.5;
}
function draw() {
background(220);
let s = map(second(), 0, 60, 0, TWO_PI) - HALF_PI;
let m = map(minute() + norm(second(), 0, 60), 0, 60, 0, TWO_PI) - HALF_PI;
let h = map(hour() + norm(minute(), 0, 60), 0, 24, 0, TWO_PI * 2) - HALF_PI;
translate(mouseX, mouseY);
triangle(cos(h)*secondsRadius, sin(h)*secondsRadius+(num-high)/2, cos(h)*secondsRadius-25, sin(h)*secondsRadius+num/2, cos(h)*secondsRadius+25, sin(h)*secondsRadius+num/2)
triangle(cos(h)*secondsRadius, sin(h)*secondsRadius-(num-high)/2, cos(h)*secondsRadius-25, sin(h)*secondsRadius-num/2, cos(h)*secondsRadius+25, sin(h)*secondsRadius-num/2)
rect(cos(m)*secondsRadius-25,sin(m)*secondsRadius-25, 50, 50);
ellipse(cos(s)*secondsRadius,sin(s)*secondsRadius, 50, 50);
rotate(mouseX/50);
triangle(0,num-high, -50,num, 50,num);
}<file_sep>/*
제목 : 나의 자취방
처음 제가 저축한 돈으로 대출을 받아 마련한 자취방을 p5.js로 그려보았습니다.
현재 거주중인 자취방의 평명도를 그려보았습니다.
*/
function setup() {
createCanvas(800, 1100);
}
/* dashedLine 함수 출처
https://forum.processing.org/two/discussion/13585/drawing-dotted-line-around-a-rect-ie-dotted-stroke */
function dashedLine(x1, y1, x2, y2, l, g) {
var pc = dist(x1, y1, x2, y2) / 100;
var pcCount = 1;
var lPercent = gPercent = 0;
var currentPos = 0;
var xx1 = yy1 = xx2 = yy2 = 0;
while (int(pcCount * pc) < l) {
pcCount++
}
lPercent = pcCount;
pcCount = 1;
while (int(pcCount * pc) < g) {
pcCount++
}
gPercent = pcCount;
lPercent = lPercent / 100;
gPercent = gPercent / 100;
while (currentPos < 1) {
xx1 = lerp(x1, x2, currentPos);
yy1 = lerp(y1, y2, currentPos);
xx2 = lerp(x1, x2, currentPos + lPercent);
yy2 = lerp(y1, y2, currentPos + lPercent);
if (x1 > x2) {
if (xx2 < x2) {
xx2 = x2;
}
}
if (x1 < x2) {
if (xx2 > x2) {
xx2 = x2;
}
}
if (y1 > y2) {
if (yy2 < y2) {
yy2 = y2;
}
}
if (y1 < y2) {
if (yy2 > y2) {
yy2 = y2;
}
}
line(xx1, yy1, xx2, yy2);
currentPos = currentPos + lPercent + gPercent;
}
}
function draw() {
background(220);
fill(255);
strokeWeight(20);
// 방 전체 영역
rect(100, 100, 600, 900);
// 화장실 영역
rect(400, 100, 300, 300);
strokeWeight(4);
// 정문
rect(260, 92, 100, 16);
arc(360, 108, 200, 200, HALF_PI, PI, PIE);
// 부엌 영역
// 부엌 창문
rect(170, 92, 40, 8);
rect(130, 100, 80, 8);
line(170, 88, 170, 104);
// 싱크대
rect(108, 108, 120, 270);
rect(128, 210, 80, 80);
// 가스레인지
ellipse(173, 148, 30, 30);
line(153, 148, 165, 148);
line(180, 148, 192, 148);
line(173, 128, 173, 141);
line(173, 168, 173, 155);
// 수도 꼭지
ellipse(128, 240, 10, 10);
rect(128, 245, 20, 10);
ellipse(128, 260, 10, 10);
// 부엌 문
rect(108, 390, 150, 18);
line(200, 399, 350, 399);
dashedLine(250, 390, 400, 390, 5, 5);
dashedLine(250, 408, 400, 408, 5, 5);
// 화장실 영역
// 화장실 창문
rect(540, 92, 40, 8);
rect(500, 100, 80, 8);
line(540, 88, 540, 104);
// 화장실문
rect(392, 230, 16, 100);
arc(392, 330, 200, 200, PI, PI+HALF_PI, PIE);
// 변기
line(420, 115, 510, 115); // 상단 가로
line(420, 115, 420, 140); // 좌측세로
line(510, 115, 510, 140); // 우측 세로
line(420, 140, 510, 140); // 하단 가로
line(425, 140, 431, 189); // 좌측 커버
arc(465, 180, 70, 85, HALF_PI, PI*0.9); // 좌측 커버
line(505, 140, 499, 189); // 우측 커버
arc(465, 180, 70, 85, PI-PI*0.9, HALF_PI); // 우측 커버
// 세탁기
line(550, 115, 670, 115); // 상단
line(550, 230, 670, 230); // 하단
line(550, 115, 550, 230); // 좌측
line(670, 115, 670, 230); // 우측
ellipse(610, 162.5, 80, 80);
rect(570, 210, 80, 10);
// 거울
rect(680, 250, 10, 80);
// 수도 꼭지
ellipse(680, 280, 10, 10);
rect(660, 285, 20, 10);
ellipse(680, 300, 10, 10);
// 방 영역
// 냉장고
rect(108, 420, 130, 130);
rect(238, 420, 110, 20);
arc(238, 440, 220, 220, 0, HALF_PI, PIE);
// 책상1
rect(430, 408, 150, 80);
// 전자레인지
rect(440, 416, 60, 50);
// 밥솥
arc(530, 440, 80, 40, HALF_PI+PI, 0);
arc(530, 440, 80, 40, 0, HALF_PI);
arc(530, 440, 30, 40, PI, HALF_PI+PI);
arc(530, 440, 30, 40, HALF_PI, PI);
ellipse(532, 440, 20, 10);
// 행거
rect(670, 520, 10, 250);
dashedLine(620, 532, 685, 532, 1, 10);
dashedLine(620, 532, 620, 757, 1, 10);
dashedLine(620, 757, 685, 757, 1, 10);
dashedLine(685, 532, 685, 757, 1, 10);
// 서랍
rect(108, 570, 100, 80);
rect(600, 408, 80, 80);
// 메인 책상
noFill();
rect(168, 700, 240, 110);
rect(138, 700, 30, 110);
// 의자
ellipse(280, 690, 70, 70);
line(260, 670, 300, 710);
line(300, 670, 260, 710);
// 접이식 식탁
rect(118, 710, 8, 90);
ellipse(128, 755, 10, 110);
// 침대
arc(168, 840, 20, 20, PI, PI+HALF_PI);
line(158, 840, 158, 960);
arc(168, 960, 20, 20, HALF_PI, PI);
line(168, 830, 498, 830);
line(168, 970, 498, 970);
arc(498, 840, 20, 20, PI+HALF_PI, 0);
line(508, 840, 508, 960);
arc(498, 960, 20, 20, 0, HALF_PI);
// 베개
arc(178, 865, 20, 20, PI, PI+HALF_PI);
line(168, 865, 168, 935);
arc(178, 935, 20, 20, HALF_PI, PI);
line(178, 855, 188, 855);
line(178, 945, 188, 945);
arc(188, 865, 20, 20, PI+HALF_PI, 0);
line(198, 865, 198, 935);
arc(188, 935, 20, 20, 0, HALF_PI);
// 이불
arc(228, 840, 20, 20, PI, PI+HALF_PI);
line(218, 840, 218, 960);
arc(228, 960, 20, 20, HALF_PI, PI);
dashedLine(248, 830, 248, 970, 5, 15);
// 방 창문
fill(255);
rect(400, 992, 150, 8);
rect(250, 1000, 300, 8);
line(400, 986, 400, 1004);
}<file_sep>var cnt; // 붓의 형태를 관여하는 변수
function setup() {
createCanvas(400, 400);
cnt = 0;
background(220);
}
function draw() {
// space키를 누르면 cnt증가
if(keyIsPressed && keyCode == 32)
cnt+=1;
if(cnt == 3) // 붓의 종류 3가지
cnt = 0;
if(cnt == 0) { // 'space' 시 선 모양 변경
stroke(0); // 기본 색
if(keyCode == 82) // 'R' 붓 색 Red로 변경
stroke(255, 0, 0);
else if(keyCode == 71) // 'G' 붓 색 Green로 변경
stroke(0, 255, 0);
else if(keyCode == 66) // 'B' 붓 색 Blue로 변경
stroke(0, 0, 255);
if(mouseIsPressed) {
// 마우스 클릭시 붓으로 그릴 수 있음
strokeWeight(5);
line(pmouseX, pmouseY, mouseX, mouseY);
}
} else if(cnt == 1) {
fill(0);
if(keyCode == 82)
fill(255, 0, 0);
else if(keyCode == 71)
fill(0, 255, 0);
else if(keyCode == 66)
fill(0, 0, 255);
if(mouseIsPressed) {
noStroke();
ellipse(mouseX, mouseY, 20, 20);
}
} else if(cnt == 2) {
fill(0,20);
if(keyCode == 82)
fill(255, 0, 0, 20);
else if(keyCode == 71)
fill(0, 255, 0, 20);
else if(keyCode == 66)
fill(0, 0, 255, 20);
if(mouseIsPressed) {
noStroke();
ellipse(mouseX, mouseY, 30, 30);
ellipse(mouseX + 10, mouseY + 10, 15, 15);
}
}
}<file_sep># P5.js-Study_Coding
P5.js 공부 ( 나의 풀이 ) // P5.js study (my solution)
<file_sep>let gd = [],
gd_C = [];
let maxX = 400;
var state = 0;
var rain_pos = 0;
var rain_type = 0;
// setup
function setup() {
createCanvas(600, 300);
ground();
background(220);
}
// draw
function draw() {
noStroke();
// 하늘
sky();
stroke(0); // <- stroke
// 땅
fill(20, 200, 100); // <- fill
for (var i = 0; i < 250; i++) { // <- for
fill(gd_C[i][0], gd_C[i][1], gd_C[i][2], gd_C[i][3]); // <- fill
triangle(gd[i][0], gd[i][1], gd[i][2], gd[i][3], gd[i][4], gd[i][5]); // <- triangle
}
for (var i = 250; i < 450; i++) { // <- for
fill(gd_C[i][0], gd_C[i][1], gd_C[i][2], gd_C[i][3]); // <- fill
ellipse(gd[i][0], gd[i][1], gd[i][2], gd[i][3]); // <- ellipse
}
// 나무
tree();
// 비
if (mouseIsPressed) { // <- mouse 입력, if
// 왼쪽 구름 비
if ((mouseX > 0 && mouseX < 300) && (mouseY > 0 && mouseY < 200)) { // <- if
for (var i = 0; i < width / 2; i += width / 2 / 30) { // <- for
stroke(0, 255, 0); // <- stroke
rain_type++;
rain_pos += 15 + random(13);
if (rain_pos > height) { // <- if
rain_pos = 0;
}
// 비오는 애니메이션
if (rain_type % 2 == 0) { // <- if
line(i, rain_pos - 30, i, rain_pos); // <- line
line(i, rain_pos - 150, i, rain_pos - 120); // <- line
} else {
line(i, rain_pos + 30, i, rain_pos + 60); // <- line
line(i, rain_pos - 50, i, rain_pos - 30); // <- line
}
}
}
// 중앙 구름 비
if ((mouseX > 250 && mouseX < 475) && (mouseY > 0 && mouseY < 200)) { // <- if
for (var i = 250; i < 475; i += 225 / 30) { // <- for
stroke(255, 255, 0); // <- stroke
rain_type++;
rain_pos += 15 + random(13);
if (rain_pos > height) { // <- if
rain_pos = 0;
}
// 비오는 애니메이션
if (rain_type % 2 == 0) { // <- if
line(i, rain_pos - 30, i, rain_pos); // <- line
line(i, rain_pos - 150, i, rain_pos - 120); // <- line
} else {
line(i, rain_pos + 30, i, rain_pos + 60); // <- line
line(i, rain_pos - 50, i, rain_pos - 30); // <- line
}
}
}
// 움직이는 동그라미 : 네모땅 클릭시
if ((mouseX > 0 && mouseX < 400) && (mouseY > 200 && mouseY < 300)) { // <- if
ellipse(mouseX,mouseY,25+random(20), 25+random(20)); // <- ellipse
ellipse(pmouseX,pmouseY,25+random(20), 25+random(20)); // <- ellipse
}
// 움직이는 세모 : 동그라미땅 클릭시
if ((mouseX > 400 && mouseX < 600) && (mouseY > 200 && mouseY < 300)) { // <- if
triangle(mouseX+random(30),mouseY+random(30),mouseX-random(30),mouseY+random(30),mouseX+random(30),mouseY-random(30)); // <- triangle
triangle(pmouseX+random(30),pmouseY+random(30),pmouseX+random(30),pmouseY-random(30),pmouseX-random(30),pmouseY-random(30)); // <- triangle
}
}
}
function ground() {
// x : 0~400, y : 200~300
// 세모땅
for (var i = 0; i < 100; i++) { // <- for
gd[i] = [
random(400),
random(100) + 200,
random(400),
random(100) + 200,
random(400),
random(100) + 200,
];
gd_C[i] = [random(255), random(255), random(255), 40];
}
for (var i = 100; i < 125; i++) { // <- for
gd[i] = [
0,
random(100) + 200,
0,
random(100) + 200,
random(400),
random(100) + 200,
];
gd_C[i] = [random(255), random(255), random(255), 40];
}
for (var i = 125; i < 150; i++) { // <- for
gd[i] = [
400,
random(100) + 200,
400,
random(100) + 200,
random(400),
random(100) + 200,
];
gd_C[i] = [random(255), random(255), random(255), 40];
}
for (var i = 150; i < 200; i++) { // <- for
gd[i] = [
random(400),
200,
random(400),
200,
random(400),
random(100) + 200,
];
gd_C[i] = [random(255), random(255), random(255), 40];
}
for (var i = 200; i < 250; i++) { // <- for
gd[i] = [
random(400),
300,
random(400),
300,
random(400),
random(100) + 200,
];
gd_C[i] = [random(255), random(255), random(255), 40];
}
// x : 400~600, y : 200~300
// 동그라미 땅 : 왼쪽 -> 오른쪽 순서
for (var i = 250; i < 350; i++) { // <- for
gd[i] = [random(50) + 400, random(100) + 200, random(50), random(50)];
gd_C[i] = [random(255), random(255), random(255), 40];
}
for (var i = 350; i < 400; i++) { // <- for
gd[i] = [random(50) + 450, random(75) + 225, random(50), random(50)];
gd_C[i] = [random(255), random(255), random(255), 40];
}
for (var i = 400; i < 430; i++) { // <- for
gd[i] = [random(50) + 500, random(50) + 250, random(50), random(50)];
gd_C[i] = [random(255), random(255), random(255), 40];
}
for (var i = 430; i < 450; i++) { // <- for
gd[i] = [random(50) + 550, random(25) + 275, random(50), random(50)];
gd_C[i] = [random(255), random(255), random(255), 40];
}
}
function tree() {
fill(random(255), random(255), random(100)); // 나무 기둥, fill
rect(475, 200, 20, 50); // <- rect
fill(0, random(255), random(255)); // 위 나뭇잎, fill
ellipse(485, 150, 100, 60); // <- ellipse
fill(0, random(255), random(255)); // 중간 나뭇잎, fill
ellipse(485, 175, 100, 60); // <- ellipse
fill(0, random(255), random(255)); // 아래 나뭇잎, fill
ellipse(485, 200, 80, 20); // <- ellipse
}
function sky() {
fill(255); // <- fill
rect(0, 0, 600, 200); // 하얀 하늘 // <- rect
fill(0, 100, random(100) + 155); // 중앙 구름, fill
arc(250, 0, 450, 300, 0, HALF_PI, PIE); // <- arc
fill(0, 0, random(100) + 155); // 왼쪽 구름, fill
arc(0, 0, 600, 400, 0, HALF_PI, PIE); // <- arc
fill(150, 150, random(50) + 205); // 오른쪽 위 구름, fill
arc(600, 0, 100, 100, HALF_PI, PI, PIE); // <- arc
fill(50, 150, random(50) + 205); // 오른쪽 중간 구름, fill
arc(600, 200, 200, 50, PI, PI + HALF_PI, PIE); // <- arc
fill(100, 100, random(100) + 155); // 오른쪽 아래 구름, fill
arc(600, 200, 300, 150, HALF_PI, PI, PIE); // <- arc
}
<file_sep>// 불 애니메이션은 마우스를 따라다닌다.
// 불은 마우스 포인트를 대 신한다
// 성냥과 불이 맞닿으면 성냥에 불이 켜진다
// 불이 켜진 성냥의 갯수 만큼 배경이 빨갛게 변한다
// 아무 곳이든 마우스 클릭하면 모든 불이 꺼지고, background(0);
let fire = [],
on = [];
let animation, cnt = 0,
index = 0, pcnt = 0,
bgColor = 255;
var matchs = [];
function preload() {
for (var i = 0; i < 4; i++) {
matchs[i] = loadImage("match.png");
on[i] = 0;
}
}
function setup() {
createCanvas(800, 400);
animation = new Animate("fire", 9);
frameRate(9);
}
function draw() {
noCursor();
background(255, bgColor, bgColor);
for (var i = 0; i < 4; i++) {
image(matchs[i], 100 + 200 * (i - 1), 100);
}
// 성냥과 불(마우스)가 닿게 되면, 성냥에 불이 켜진다. (순서 상관 X)
for (var i = 0; i < 4; i++) {
if (mouseX > 15 + i * 200 && mouseX < 85 + i * 200) {
if (mouseY > 173) {
if(on[i] == 0) {
cnt++;
bgColor = 255 - (cnt)*50; // 불 켜진 성냥 하나당 배경 빨개짐
}
on[i] = 1;
}
}
if (on[i] == 1) {
if (on[i] == 1) {
addAnimation(0 + i * 200, 160);
}
}
}
animation.display();
if (mouseIsPressed) { // 마우스 클릭시 불 꺼짐
for(var i = 0; i < 4; i++) {
on[i] = 0;
cnt = 0;
bgColor = 255;
}
}
}
function addAnimation(fixX, fixY) {
for (var i = 0; i < this.counts; i++) {
var filename = this.imagename + (i + 1) + ".png";
fire[i] = loadImage(filename);
}
index = (index + 1) % fire.length;
image(fire[index], fixX, fixY, 100, 100);
}
class Animate {
constructor(imagePrefix, count) {
this.imagename = imagePrefix;
this.counts = count;
for (var i = 0; i < this.counts; i++) {
var filename = this.imagename + (i + 1) + ".png";
fire[i] = loadImage(filename);
}
}
display() {
index = (index + 1) % fire.length;
image(fire[index], mouseX - 50, mouseY - 50, 100, 100);
}
}<file_sep>let x = 0;
function setup() {
createCanvas(640, 740);
}
function draw() {
let k =[100,100,100]; // 회색 (RGB: 100,100,100)
let g = [150,150,150]; // 회색 (RGB: 150,150,150)
let d = [75, 75, 75]; // 검정 (RGB: 75,75,75)
let b = [50, 50, 50]; // 검정 (RGB: 50,50,50)
let B = [0, 0, 0]; // 검정 (RGB: 0,0,0)
let W = [200, 200, 200]; // 회색 (RGB: 200,200,200)
let G = [255, 255, 255]; // 횐색 (RGB: 255, 255, 255)
let value = [ /*31X37*/
W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,
W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,
W,W,W,W,W,W,W,W,W,W,B,B,B,B,B,B,B,B,W,W,W,W,W,W,W,W,W,W,W,W,W,
W,W,W,W,W,W,W,W,B,B,d,d,d,d,d,d,d,d,B,B,B,W,W,W,W,W,W,W,W,W,W,
W,W,W,W,W,W,B,B,d,d,d,d,d,d,d,d,d,d,d,d,d,B,W,W,W,W,W,W,W,W,W,
W,W,W,W,W,B,d,d,d,d,d,d,B,B,B,B,B,d,d,d,d,d,B,W,W,W,W,W,W,W,W,
W,W,W,W,B,B,B,B,B,B,B,B,W,W,g,g,g,B,d,d,d,d,B,W,W,W,W,W,W,W,W,
W,W,W,B,G,G,G,G,G,G,G,G,G,W,W,g,g,k,B,d,d,d,b,B,W,W,W,W,W,W,W,
W,W,W,B,G,G,G,G,G,G,G,G,G,W,W,g,g,k,k,B,d,d,b,B,W,W,W,W,W,W,W,
W,W,B,G,G,G,G,G,G,G,G,G,G,W,W,g,g,g,k,B,d,d,b,B,W,W,W,W,W,W,W,
W,W,B,G,G,G,G,G,G,G,G,G,W,W,W,g,g,g,k,B,d,d,b,B,B,B,B,B,W,W,W,
W,W,B,W,G,G,G,G,G,G,W,W,W,W,g,g,g,g,k,B,d,d,b,B,d,d,d,d,B,W,W,
W,W,B,W,W,W,W,W,W,W,W,W,W,g,g,g,k,k,k,B,d,d,b,B,d,d,d,d,B,W,W,
W,W,W,B,W,W,W,W,W,W,W,g,g,g,g,k,k,k,k,B,d,d,b,B,b,d,d,d,B,W,W,
W,W,W,W,B,g,g,g,g,g,g,g,g,g,k,k,k,k,B,d,d,d,b,B,b,b,d,d,B,W,W,
W,W,W,W,B,B,B,g,g,g,g,k,k,k,k,B,B,B,d,d,d,d,b,B,b,b,b,b,B,W,W,
W,W,W,W,B,d,d,B,B,B,B,B,B,B,B,d,d,d,d,d,d,d,b,B,b,b,b,b,B,W,W,
W,W,W,W,B,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,b,b,B,b,b,b,b,B,W,W,
W,W,W,W,B,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,b,b,B,b,b,b,b,B,W,W,
W,W,W,W,B,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,b,b,b,B,b,b,b,b,B,W,W,
W,W,W,W,B,b,d,d,d,d,d,d,d,d,d,d,d,d,d,d,b,b,b,B,b,b,b,b,B,W,W,
W,W,W,W,B,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,B,b,b,b,b,B,W,W,
W,W,W,W,B,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,B,b,b,b,b,B,W,W,
W,W,W,W,W,B,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,B,b,b,b,B,W,W,W,
W,W,W,W,W,B,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,B,B,B,B,W,W,W,W,
W,W,W,W,W,B,b,b,b,B,b,b,b,b,b,b,b,b,b,b,b,b,b,B,W,W,W,W,W,W,W,
W,W,W,W,W,W,B,b,b,b,B,B,b,b,b,b,b,b,b,b,b,b,B,W,W,W,W,W,W,W,W,
W,W,W,W,W,W,B,b,b,b,b,B,B,B,B,B,B,B,b,b,b,b,B,W,W,W,W,W,W,W,W,
W,W,W,W,W,W,B,b,b,b,b,B,W,W,W,W,W,B,b,b,b,b,B,W,W,W,W,W,W,W,W,
W,W,W,W,W,W,B,b,b,b,b,B,W,W,W,W,W,B,b,b,b,b,B,W,W,W,W,W,W,W,W,
W,W,W,W,W,W,B,b,b,b,b,B,W,W,W,W,W,B,b,b,b,b,B,W,W,W,W,W,W,W,W,
W,W,W,W,W,W,W,B,B,B,B,d,d,d,d,d,d,d,B,B,B,B,d,d,d,W,W,W,W,W,W,
W,W,W,W,W,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,W,W,W,
W,W,W,W,W,W,W,W,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,W,W,W,W,W,W,W,
W,W,W,W,W,W,W,W,W,W,W,W,d,d,d,d,d,d,d,d,W,W,W,W,W,W,W,W,W,W,W,
W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,
W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,
];
let w = width / 31;
noStroke();
for (let i = 0; i < 37; i++) {
for (let j = 0; j < 31; j++) {
fill(value[x][0], value[x][1], value[x][2]);
rect(j * w, i * w, 30, 30);
x++;
if (x >= 1147) x = 0;
}
}
}
<file_sep>var img1, img2, img3, img4, img5, img6;
var cnt = 1;
function setup() {
createCanvas(500, 500);
frameRate(6);
img1 = loadImage('dog1.png');
img2 = loadImage('dog2.png');
img3 = loadImage('dog4.png');
img4 = loadImage('dog5.png');
img5 = loadImage('dog6.png');
img6 = loadImage('dog7.png');
}
function draw() {
background(255);
if (cnt == 1) {
image(img1, 0, 0);
cnt++;
} else if (cnt == 2) {
image(img2, 0, 0);
cnt++;
}else if (cnt == 3) {
image(img3, 0, 0);
cnt++;
}else if (cnt == 4) {
image(img4, 0, 0);
cnt++;
}else if (cnt == 5) {
image(img5, 0, 0);
cnt++;
}else if (cnt == 6) {
image(img6, 0, 0);
cnt = 1;
}
}
<file_sep>var eSize;
var lSize;
function setup() {
createCanvas(400, 400);
background(255);
}
function draw() {
//background(240);
strokeWeight(4);
noStroke();
var cal1 = map(mouseX, 0, 400, 0, 255);
var cal2 = map(mouseY, 0, 400, 0, 128);
var cal3 = map((mouseX+mouseY)/2, 0, 400, 0, 255);
var newVal2 = map(mouseY, 0,height,10,150);
fill(cal1, cal2, cal3);
ellipse(mouseX, mouseY, newVal2, newVal2);
fill(cal3, cal1, cal2);
ellipse(mouseX, mouseY, newVal2*0.7, newVal2*0.7);
fill(cal2, cal3, cal1);
ellipse(mouseX, mouseY, newVal2*0.4, newVal2*0.4);
} | b4fe1f4b4d92526157f606b2807dae154d88727e | [
"JavaScript",
"Markdown"
]
| 9 | JavaScript | U-WangE/P5.js-Study_Coding | 13417659b5efa30ee439c4f9173f4c9d74d3e19b | 4644d89d1dd0b86fa1b42f1ffbda24fe102a7912 |
refs/heads/master | <file_sep>
/* Diferentes formas de usar una funcion ec 5 y ec 6 : */
function ventas() {
var titulo = "mis ventas";
return titulo;
}
console.log(ventas());
console.log("------------------otra forma: ");
var ventas = function () {
var titulo = "mis ventas 2";
return titulo;
}
console.log(ventas());
console.log("------------------otra forma con ec 6:");
const ventas1 = () => {
var titulo = "mis ventas 2";
return titulo;
}
console.log(ventas1());
console.log("----------------------con parametros");
function compras(producto) {
var respuesta2 = "miproduto de compra es " + producto;
return respuesta2;
}
var elproducto = "pinturas";
console.log(compras(elproducto));
console.log("----------------------con parametros y ec6");
const compras2 = (producto) => {
var larespuesta = "miproduto de compra es " + producto;
return larespuesta;
}
//solo si tiene un parámetro podemos quitar los paréntesis.
| ab5d097031825a678d6c77e7b82fc01ba0c66600 | [
"JavaScript"
]
| 1 | JavaScript | christiandaniel1/proy | 9e4ec356d91b5d4a9fd9afcfc2a36c4ad52421e2 | 7245b112c421153e5e4b6540b7ac311fc826c5e2 |
refs/heads/master | <file_sep>
using UnityEngine;
using UnityEngine.UI;
public class GamePage
{
public static GamePage Instance;
public static GamePage getInstance()
{
if (Instance == null)
{
Instance = new GamePage();
}
return Instance;
}
internal void init()
{
UnityEngine.SceneManagement.SceneManager.LoadScene("Scene2");
GameObject Prefab = (GameObject)Resources.Load("GameCanvas");
GameObject loginPanel = MainEntrance.Instantiate(Prefab);
Button button = loginPanel.transform.Find("Exit").GetComponent<Button>();
button.onClick.AddListener(ExistGame);
}
public void ExistGame()
{
UnityEngine.SceneManagement.SceneManager.LoadScene("Scene1");
}
}
<file_sep># unityShowOurs
unity demo
push规则
每次编辑完项目后,只需要将根目录下的Assets和ProjectSettings两个文件夹中的更新push到项目,只用这两个文件夹,就可以正确加载unity工程了!不要push其他文件夹!
可以自己另起一个项目,尝试修改,可用的prefabs导出来,再导入到当前项目。只把真正需要的Asset加入到项目中,尽量不要加入很多没用到的素材,否则Asset文件会很多,check、push都会被拖慢。
分支规则---欢迎补充
其他----欢迎补充
fighting~~~~~~~~~~~~~~~~
<file_sep>using UnityEngine;
public class MainEntrance : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
DontDestroyOnLoad(this.gameObject);
LoginPage.getInstance().show();
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LoginPage
{
public static LoginPage Instance;
public static LoginPage getInstance()
{
if (Instance == null)
{
Instance = new LoginPage();
}
return Instance;
}
private bool Inited;
internal void init()
{
GameObject Prefab = (GameObject)Resources.Load("LoginCanvas");
GameObject loginPanel = MainEntrance.Instantiate(Prefab);
Button button = loginPanel.transform.Find("enter").GetComponent<Button>();
button.onClick.AddListener(enter);
Inited = true;
}
public void show()
{
if (!Inited)
{
init();
}
}
public void ClickHandler(string tag)
{
}
private void enter()
{
GamePage.getInstance().init();
}
}
| b7a3af4db6004c5af302a6c76bd6b460f4f7f8c2 | [
"Markdown",
"C#"
]
| 4 | C# | whitefancy/unityShowOurs | d8975ff90ec21ff5d12b03024de9868ffb530751 | 0e1beb7a54e1134581998ae22995ddaf29589c51 |
refs/heads/master | <file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <arpa/inet.h>
#include "structOptions.c"
//DEFINIG BUFFER LENGTH AND SOCKET LEN (CONTROL MESSAGE)
int BUF_LEN = 3;
socklen_t socklen = sizeof(struct sockaddr_in);
//BOOKING DATATYPE
bookingType booking;
size_t BOOK_SIZE = sizeof(bookingType);
//FUNCTION TO GET DETAILS FROM USER
void getDetails(locDetails *loc) {
int i, t;
//GENERATE BOOKING ID
srand(time(NULL));
booking.bookingID = rand() % 10000;
printf("\n\nWELCOME TO TOURISM BOOKING!\n");
printf("1. ENTER YOUR NAME : ");
scanf("%s", booking.cusName);
printf("2. ENTER NUMBER OF PASSENGERS : ");
scanf("%d", &booking.passengerCount);
printf("\nTRAVEL OPTIONS:");
for(i = 0; i < 4; i++)
printf("\n%d - %s", loc[i].id, loc[i].locName);
printf("\n3. ENTER LOCATION CODE : ");
scanf("%d", &t);
booking.destCode = t;
strcpy(booking.destName, loc[t].locName);
printf("\n4. ENTER TRAVEL MONTH (1 TO 3) : ");
scanf("%d", &booking.travelMonth);
--booking.travelMonth;
}
int main() {
//GLOBAL VARIABLES
size_t BUF_SIZE = sizeof(char) * BUF_LEN;
char msg[BUF_LEN];
locDetails *loc = (locDetails*) malloc(sizeof(locDetails) * 4); //LOCATION DETAILS (ARRAY)
size_t LOC_LEN = sizeof(locDetails) * 4;
int flag; //1 - BOOKING CONFIRMED; 0 - BOOKING FAILED
size_t FLAG_LEN = sizeof(int);
//SOCKET
int sk = socket(AF_INET, SOCK_DGRAM, 0);
perror("AFTER SOCKET "); //DEBUG
//SOCKET STRUCT
struct sockaddr_in skp;
bzero(&skp, sizeof(struct sockaddr_in));
skp.sin_family = AF_INET;
skp.sin_port = htons(5000);
perror("AFTER HTONS "); //DEBUG
inet_pton(AF_INET, "ENTER-CLIENT-IP", &skp.sin_addr);
perror("AFTER INET_ADDR "); //DEBUG
//BIND
int bd = bind(sk, (struct sockaddr *) &skp, sizeof(struct sockaddr_in));
perror("AFTER BIND "); //DEBUG
//SOCKET - TO SEND
struct sockaddr_in skc;
bzero(&skc, sizeof(struct sockaddr_in));
skc.sin_family = AF_INET;
skc.sin_port = htons(5000);
perror("AFTER HTONS (SEND) "); //DEBUG
inet_pton(AF_INET, "ENTER-HOST-IP", &skc.sin_addr);
perror("AFTER INET_ADDR (SEND) "); //DEBUG
//GET LOCATION DETAILS FROM SERVER
//SEND REQUEST
strcpy(msg, "r1");
sendto(sk, msg, BUF_SIZE, 0, (struct sockaddr *) &skc, socklen);
perror("AFTER SENDING REQUEST ");
//RECEIVE RESPONSE
recvfrom(sk, loc, LOC_LEN, 0, (struct sockaddr *) &skc, &socklen);
perror("AFTER RECEIVING RESPONSE ");
for(int i = 0;i < 4;i++)
printf("%d\t%s\t%d %d %d\n", loc[i].id, loc[i].locName, loc[i].cap[0], loc[i].cap[1], loc[i].cap[2]);
//BEGIN PROMPT AND GET BOOKING DETAILS
getDetails(loc);
//SEND BOOKING VALUE TO SERVER
sendto(sk, &booking, BOOK_SIZE, 0, (struct sockaddr *) &skc, socklen);
perror("AFTER SENDTO (BOOKING) ");
//RECEIVE BOOKING RESPONSE
recvfrom(sk, &flag, FLAG_LEN, 0, (struct sockaddr *) &skc, &socklen);
perror("AFTER RECVFROM (BOOKING) ");
if (flag == 0)
printf("\nBOOKING REJECTED! NOT ENOUGH SEATS");
else if (flag == 1)
printf("\nBOOKING CONFIRMED! BOOKING ID: %d", booking.bookingID);
else
printf("\nRESPONSE ERROR");
printf("\nEND OF PROGRAM\n");
return 0;
}
<file_sep>//BOOKING DATA STRUCTURE
typedef struct {
int bookingID;
char cusName[64];
int passengerCount;
int destCode;
char destName[64];
int travelMonth;
} bookingType;
//LOCATION DETAILS DATA STRUCTURE
typedef struct {
int id;
char locName[64];
int cap[3];
} locDetails;
<file_sep>#!/usr/bin/env bash
printf "ENTER HOST IP: "
read hostIP
printf "ENTER CLIENT IP: "
read clientIP
printf "\nCOPYING SOURCES..."
cp sources/server.c build/sources/server.c
cp sources/client.c build/sources/client.c
cp sources/structOptions.c build/sources/structOptions.c
printf "\nCOPYING RESOURCE FILES..."
cp sources/locations.bin build/locations.bin
cp sources/bookings.txt build/bookings.txt
printf "\nEDITING SOURCE CODE..."
sed -i "s/ENTER-HOST-IP/$hostIP/g" build/sources/server.c
sed -i "s/ENTER-HOST-IP/$hostIP/g" build/sources/client.c
sed -i "s/ENTER-CLIENT-IP/$clientIP/g" build/sources/client.c
printf "\nBUILDING BINARIES..."
gcc build/sources/server.c -o build/server.out
gcc build/sources/client.c -o build/client.out
printf "\nALL DONE!\n"
<file_sep># tourism-booking-c-networking
A simple tourism booking application that makes use of UDP networking protocol
## Installation
Clone the repository
git clone https://github.com/the-bose/tourism-booking-c-networking/
Build binaries
./runthis.sh
Change to build directory
cd build
run `server.out` or `client.out` depending on machine.
### IMPORTANT
* server.out, locations.bin, and bookings.txt must be in the same directory (pwd)
* client.out can be run remotely
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "structOptions.c"
int main() {
int i, op;
//FILE POINTER
FILE *fp;
//LOCATION DETAILS - VAR
locDetails loc;
loc.id = 1;
//OPENING FILE
if ((fp = fopen("locations.bin", "wb")) == NULL) {
printf("ERROR OPENING FILE!");
exit(1);
}
while (1) {
printf("\n\nID: %d\nENTER LOCATION NAME : ", loc.id++);
scanf("%s", loc.locName);
fflush(stdin);
printf("ENTER MAXIMUM TRAVEL CAPACITY FOR :\n");
for (i = 0; i < 3; i++) {
printf(" MONTH %d : ", i + 1);
scanf("%d", &loc.cap[i]);
}
//WRITING TO FILE
fprintf(fp, "%d\t%s\t%d %d %d\n", loc.id, loc.locName, loc.cap[0], loc.cap[1], loc.cap[2]);
//LOOP
printf("Do you want to add another location? (1 - YES/0 - N0) ");
scanf("%d", &op);
if (op == 0)
break;
}
fclose(fp);
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <arpa/inet.h>
#include "structOptions.c"
#include <unistd.h>
//DEFINIG BUFFER AND SIZE (CONTROL MESSAGE)
int BUF_LEN = 3;
socklen_t socklen = sizeof(struct sockaddr_in);
//BOOKING DATATYPE
bookingType booking;
size_t BOOK_SIZE = sizeof(bookingType);
int main() {
//GLOBAL VARIABLES
size_t BUF_SIZE = sizeof(char) * BUF_LEN; //LENGTH OF SOCKET BUFFER
FILE *fp;
locDetails loc[4];
size_t LOC_LEN = sizeof(locDetails) * 4;
int flag = 0; //1 - BOOKING CONFIRMED; 0 - BOOKING FAILED
size_t FLAG_LEN = sizeof(int);
//SOCKET
int sk = socket(AF_INET, SOCK_DGRAM, 0);
perror("AFTER SOCKET "); //DEBUG
//SOCKET STRUCT
struct sockaddr_in skp;
bzero(&skp, sizeof(struct sockaddr_in));
skp.sin_family = AF_INET;
skp.sin_port = htons(5000);
perror("AFTER HTONS "); //DEBUG
inet_pton(AF_INET, "ENTER-HOST-IP", &skp.sin_addr);
perror("AFTER INET_ADDR "); //DEBUG
//SOCKET - CLIENT
struct sockaddr_in skc;
//BIND
int bd = bind(sk, (struct sockaddr *) &skp, sizeof(struct sockaddr_in));
perror("AFTER BIND "); //DEBUG
//LOOP VARIABLES
char str[BUF_LEN];
while(1) {
printf("\nUDP Server: waiting for connection...");
recvfrom(sk, str, BUF_SIZE, 0, (struct sockaddr *) &skc, &socklen);
//PROCESS RECEIVED MESSAGE AND RETURN LOCATION DETAILS
if (strcmp(str, "r1") == 0) {
int i;
fp = fopen("locations.bin", "rb");
for (i = 0;i < 4; i++)
fscanf(fp, "%d\t%s\t%d %d %d\n", &loc[i].id, loc[i].locName, &loc[i].cap[0], &loc[i].cap[1], &loc[i].cap[2]);
for (i = 0;i < 4; i++)
printf("\n%d\t%s\t%d %d %d", loc[i].id, loc[i].locName, loc[i].cap[0], loc[i].cap[1], loc[i].cap[2]);
fclose(fp);
}
//SEND TO CLIENT LOCATION LIST
printf("\nIN PID #%d", getpid());
sendto(sk, loc, LOC_LEN, 0, (struct sockaddr *) &skc, socklen);
perror("AFTER SENDTO (INITIAL) ");
//RECEIVE BOOKING FROM CLIENT
recvfrom(sk, &booking, BOOK_SIZE, 0, (struct sockaddr *) &skc, &socklen);
perror("AFTER RECVFROM (BOOKING) ");
//CHECK IF SEATS ARE AVAILABLE
if(loc[booking.destCode].cap[booking.travelMonth] < booking.passengerCount) {
flag = 0; //SEATS UNAVAILABLE
printf("\nUDP Server PID #%d : Passenger seats unavailable", getpid());
} else {
flag = 1;
//WRITING DATA TO bookings.txt
fp = fopen("bookings.txt", "ab");
fprintf(fp, "%d\t%s\t%d\t%s\t%d\n", booking.bookingID, booking.cusName, booking.passengerCount, booking.destName, booking.travelMonth);
fclose(fp);
//UPDATNG locations.bin
fp = fopen("locations.bin", "wb");
loc[booking.destCode].cap[booking.travelMonth] -= booking.passengerCount;
for (int i = 0;i < 4;i++)
fprintf(fp, "%d\t%s\t%d %d %d\n", loc[i].id, loc[i].locName, loc[i].cap[0], loc[i].cap[1], loc[i].cap[2]);
fclose(fp);
printf("\nUDP Server PID #%d : Booking confirmed", getpid());
}
//SENDING RESPONSE (FLAG)
sendto(sk, &flag, FLAG_LEN, 0, (struct sockaddr *) &skc, socklen);
}
printf("\nEND OF SERVER\n");
return 0;
}
| 1b30ed9c8a362b2b4ca49771bb8d8b788b884c11 | [
"Markdown",
"C",
"Shell"
]
| 6 | C | the-bose/tourism-booking-c-networking | 843f406fabf10af5e5520eef0ed549c6d745a0be | ed72b6d1c1942d6236a2709cec82529a5e76597f |
refs/heads/master | <repo_name>rpeterson/goforever<file_sep>/goforever.go
// goforever - processes management
// Copyright (c) 2013 <NAME> (https://github.com/gwoo).
package main
import (
"flag"
"fmt"
"log"
"os"
"github.com/gwoo/greq"
)
var d = flag.Bool("d", false, "Daemonize goforever. Must be first flag")
var conf = flag.String("conf", "goforever.toml", "Path to config file.")
var port = flag.Int("port", 8080, "Port for the server.")
var username = flag.String("username", "demo", "Username for basic auth.")
var password = flag.String("password", "<PASSWORD>", "Password for basic auth.")
var config *Config
var Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
usage := `
Process subcommands
list List processes.
show <process> Show a process.
start <process> Start a process.
stop <process> Stop a process.
restart <process> Restart a process.
`
fmt.Fprintln(os.Stderr, usage)
}
func init() {
setConfig()
setHost()
daemon = &Process{
Name: "goforever",
Args: []string{"./goforever"},
Command: "goforever",
Pidfile: "goforever.pid",
Logfile: "goforever.debug.log",
Errfile: "goforever.errors.log",
Respawn: 1,
}
flag.Usage = Usage
}
func main() {
flag.Parse()
daemon.Name = "goforever"
if *d == true {
daemon.Args = append(daemon.Args, os.Args[2:]...)
daemon.start(daemon.Name)
return
}
if len(flag.Args()) > 0 {
fmt.Printf("%s\n", Cli())
return
}
if len(flag.Args()) == 0 {
RunDaemon()
HttpServer()
return
}
}
func Cli() string {
var o []byte
var err error
sub := flag.Arg(0)
name := flag.Arg(1)
if sub == "list" {
o, _, err = greq.Get("/")
}
if name != "" {
switch sub {
case "show":
o, _, err = greq.Get("/" + name)
case "start":
o, _, err = greq.Post("/"+name, nil)
case "stop":
o, _, err = greq.Delete("/" + name)
case "restart":
o, _, err = greq.Put("/"+name, nil)
}
}
if err != nil {
fmt.Printf("Process error: %s", err)
}
return string(o)
}
func RunDaemon() {
fmt.Printf("Running %s.\n", daemon.Name)
daemon.children = make(map[string]*Process, 0)
for _, name := range config.Keys() {
daemon.children[name] = config.Get(name)
}
daemon.run()
}
func setConfig() {
c, err := LoadConfig(*conf)
if err != nil {
log.Fatalf("Config error: %s", err)
return
}
config = c
if config.Username != "" {
username = &config.Username
}
if config.Password != "" {
password = &config.Password
}
}
func setHost() {
scheme := "https"
if isHttps() == false {
scheme = "http"
}
greq.Host = fmt.Sprintf("%s://%s:%[email protected]:%d", scheme, *username, *password, *port)
}
<file_sep>/README.md
# Goforever [](https://travis-ci.org/gwoo/goforever)
Config based process manager. Goforever could be used in place of supervisor, runit, node-forever, etc.
Goforever will start an http server on the specified port.
Usage of ./goforever:
-conf="goforever.toml": Path to config file.
-d=false: Daemonize goforever. Must be first flag
-password="<PASSWORD>": Password for basic auth.
-port=8080: Port for the server.
-username="demo": Username for basic auth.
## CLI
list List processes.
show <process> Show a process.
start <process> Start a process.
stop <process> Stop a process.
restart <process> Restart a process.
## HTTP API
Return a list of managed processes
GET host:port/
Start the process
POST host:port/:name
Restart the process
PUT host:port/:name
Stop the process
DELETE host:port/:name
| fff13e43be47dc20be940df0b5c3540663be7a12 | [
"Markdown",
"Go"
]
| 2 | Go | rpeterson/goforever | 68340a6b0d843343c9a05630fe637067e9e1f713 | bc1e267e81d2947ac8696f2f5bea45837659401a |
refs/heads/master | <repo_name>Zilula/lab-11-new-components<file_sep>/pokemon-table.js
import html from './html.js';
function makeTemplate() {
return html`
<form id=add-form>
<h2>Search for Pokemon</h2>
<label>
Name:
<input id="filter-name">
</label>
<label>
Type:
<input id="filter-type">
</label>
<label>
Type2:
<input id="filter-type2">
</label>
<label>
Attack:
<input type="number" id="filter-attack">
</label>
<label>
Defense:
<input type="number" required id="filter-defense">
</label>
</form>
`;
}
const tableBody = document.getElementById('pokemon.body');
function makePokemon(pokemon) {
return html`
<tr>
<td>${pokemon.color_1}</td>
<td>${pokemon.speed}</td>
<td>${pokemon.pokemon}</td>
<td>${pokemon.type_1}</td>
<td>${pokemon.type_2}</td>
<td>${pokemon.attack}</td>
<td>${pokemon.defense}</td>
<td>${pokemon.shape}</td>
</tr>`;
}
class PokemonTable {
constructor(onAdd) {
this.onAdd = onAdd
}
render(); {
constructor(pokemon) {
for(let i = 0; i < pokemon.length; i++) {
const tr = makePokemon(pokemon[i]);
tableBody.appendChild(tr);
}
}
update(pokemon) {
while(tableBody.lastElementChild) {
tableBody.lastElementChild.remove();
}
PokemonTable.constructor(pokemon);
}
render() {
const dom = makeTemplate
}
}
}
export default PokemonTable;<file_sep>/app.js
import pokedexApi from './pokemonApi.js';
import PokemonTable from './pokemon-table.js';
import pokemonFilter from './filterPokemon.js';
const pokemon = pokedexApi.getAll();
PokemonTable.constructor(pokemon);
pokemonFilter.init(function(nameFilter, typeFilter, type2Filter, attackFilter, defenseFilter) {
let filtered;
if(nameFilter || typeFilter || type2Filter || attackFilter || defenseFilter){
nameFilter = nameFilter.toLowerCase();
filtered = pokemon.filter(function(pokemon) {
const hasName = ! nameFilter
|| pokemon.pokemon.includes(nameFilter);
const hasType = ! typeFilter
|| pokemon.type_1.includes(typeFilter);
const hasType2 = ! type2Filter
|| pokemon.type_2.includes(type2Filter);
const hasAttack = ! attackFilter
|| pokemon.attack >= attackFilter;
const hasDefense = ! defenseFilter
|| pokemon.defense >= defenseFilter;
return hasName && hasType && hasType2 && hasAttack && hasDefense;
});
}
else {
filtered = pokemon;
}
PokemonTable.update(filtered);
});
| c9d4ac08e47ae06475aaa243d1ed3b0eaab45519 | [
"JavaScript"
]
| 2 | JavaScript | Zilula/lab-11-new-components | 9ca0c3dec45a900e2b6ac12451ef3a77c876a7ab | c9117a84261e55eb04f03f94c9064da84969ecb0 |
refs/heads/master | <repo_name>edwinjose900/Deep_Learning<file_sep>/GANs/DiscriminatorWithGenerator.py
import torch
import torchvision
import torchvision.transforms as transforms
from torch.autograd import Variable
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
transform_train = transforms.Compose([
transforms.RandomResizedCrop(32, scale=(0.7, 1.0), ratio=(1.0,1.0)),
transforms.ColorJitter(
brightness=0.1*torch.randn(1),
contrast=0.1*torch.randn(1),
saturation=0.1*torch.randn(1),
hue=0.1*torch.randn(1)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
transform_test = transforms.Compose([
transforms.CenterCrop(32),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
trainset = torchvision.datasets.CIFAR10(root='./', train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True, num_workers=8)
testset = torchvision.datasets.CIFAR10(root='./', train=False, download=False, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False, num_workers=8)
class discriminator(nn.Module):
def __init__(self):
super(discriminator, self).__init__()
self.conv1 = nn.Conv2d(3,128,kernel_size=3, stride=1, padding=1)
self.ln1 = nn.LayerNorm([128,32,32]).cuda()
self.relu1 = nn.LeakyReLU(0.2)
self.conv2 = nn.Conv2d(128,128,kernel_size=3, stride=2, padding=1)
self.ln2 = nn.LayerNorm([128,16,16]).cuda()
self.relu2 = nn.LeakyReLU(0.2)
self.conv3 = nn.Conv2d(128,128,kernel_size=3, stride=1, padding=1)
self.ln3 = nn.LayerNorm([128,16,16]).cuda()
self.relu3 = nn.LeakyReLU(0.2)
self.conv4 = nn.Conv2d(128,128,kernel_size=3, stride=2, padding=1)
self.ln4 = nn.LayerNorm([128,8,8]).cuda()
self.relu4 = nn.LeakyReLU(0.2)
self.conv5 = nn.Conv2d(128,128,kernel_size=3, stride=1, padding=1)
self.ln5 = nn.LayerNorm([128,8,8]).cuda()
self.relu5 = nn.LeakyReLU(0.2)
self.conv6 = nn.Conv2d(128,128,kernel_size=3, stride=1, padding=1)
self.ln6 = nn.LayerNorm([128,8,8]).cuda()
self.relu6 = nn.LeakyReLU(0.2)
self.conv7 = nn.Conv2d(128,128,kernel_size=3, stride=1, padding=1)
self.ln7 = nn.LayerNorm([128,8,8]).cuda()
self.relu7 = nn.LeakyReLU(0.2)
self.conv8 = nn.Conv2d(128,128,kernel_size=3, stride=2, padding=1)
self.ln8 = nn.LayerNorm([128,4,4]).cuda()
self.relu8 = nn.LeakyReLU(0.2)
self.pool1 = nn.MaxPool2d(4, 4)
self.fc1 = nn.Linear(128, 1)
self.fc10 = nn.Linear(128, 10)
def forward(self, x):
x = (self.relu1((self.conv1(x))))
x = self.ln1(x)
#print(x.shape)
x = (self.relu2((self.conv2(x))))
x = self.ln2(x)
#print(x.shape)
x = (self.relu3((self.conv3(x))))
x = self.ln3(x)
#print(x.shape)
x = (self.relu4((self.conv4(x))))
x = self.ln4(x)
#print(x.shape)
x = (self.relu5((self.conv5(x))))
x = self.ln5(x)
#print(x.shape)
x = (self.relu6((self.conv6(x))))
x = self.ln6(x)
#print(x.shape)
x = (self.relu7((self.conv7(x))))
x = self.ln7(x)
#print(x.shape)
x = (self.relu8((self.conv8(x))))
x = self.ln8(x)
x = self.pool1(x)
#print(x.shape)
x = x.view(x.size(0),-1)
x1 = (self.fc1(x))
#print(x.shape)
x2 = (self.fc10(x))
#print(x.shape)
return x1,x2
class generator(nn.Module):
def __init__(self):
super(generator, self).__init__()
self.fc1 = nn.Linear(100, 128*4*4)
#self.bn1 = nn.BatchNorm2d(128)
self.conv1 = nn.ConvTranspose2d(128,128,kernel_size=4, stride=2, padding=1)
self.bn2 = nn.BatchNorm2d(128)
self.conv2 = nn.Conv2d(128,128,kernel_size=3, stride=1, padding=1)
self.bn3 = nn.BatchNorm2d(128)
self.conv3 = nn.Conv2d(128,128,kernel_size=3, stride=1, padding=1)
self.bn4 = nn.BatchNorm2d(128)
self.conv4 = nn.Conv2d(128,128,kernel_size=3, stride=1, padding=1)
self.bn5 = nn.BatchNorm2d(128)
self.conv5 = nn.ConvTranspose2d(128,128,kernel_size=4, stride=2, padding=1)
self.bn6 = nn.BatchNorm2d(128)
self.conv6 = nn.Conv2d(128,128,kernel_size=3, stride=1, padding=1)
self.bn7 = nn.BatchNorm2d(128)
self.conv7 = nn.ConvTranspose2d(128,128,kernel_size=4, stride=2, padding=1)
self.bn8 = nn.BatchNorm2d(128)
self.conv8 = nn.Conv2d(128,3,kernel_size=3, stride=1, padding=1)
def forward(self, x):
x = self.fc1(x)
x = x.view(x.size(0),128,4,4)
#x = self.bn1(x)
x = (F.relu(self.bn2(self.conv1(x))))
#print(x.shape)
x = (F.relu(self.bn3(self.conv2(x))))
#print(x.shape)
x = (F.relu(self.bn4(self.conv3(x))))
#print(x.shape)
x = (F.relu(self.bn5(self.conv4(x))))
#print(x.shape)
x = (F.relu(self.bn6(self.conv5(x))))
#print(x.shape)
x = (F.relu(self.bn7(self.conv6(x))))
#print(x.shape)
x = (F.relu(self.bn8(self.conv7(x))))
#print(x.shape)
x = F.tanh(self.conv8(x))
#print(x.shape)
return x
def calc_gradient_penalty(netD, real_data, fake_data):
DIM = 32
LAMBDA = 10
alpha = torch.rand(batch_size, 1)
alpha = alpha.expand(batch_size, int(real_data.nelement()/batch_size)).contiguous()
alpha = alpha.view(batch_size, 3, DIM, DIM)
alpha = alpha.cuda()
fake_data = fake_data.view(batch_size, 3, DIM, DIM)
interpolates = alpha * real_data.detach() + ((1 - alpha) * fake_data.detach())
interpolates = interpolates.cuda()
interpolates.requires_grad_(True)
disc_interpolates, _ = netD(interpolates)
gradients = autograd.grad(outputs=disc_interpolates, inputs=interpolates,
grad_outputs=torch.ones(disc_interpolates.size()).cuda(),
create_graph=True, retain_graph=True, only_inputs=True)[0]
gradients = gradients.view(gradients.size(0), -1)
gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean() * LAMBDA
return gradient_penalty
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import os
def plot(samples):
fig = plt.figure(figsize=(10, 10))
gs = gridspec.GridSpec(10, 10)
gs.update(wspace=0.02, hspace=0.02)
for i, sample in enumerate(samples):
ax = plt.subplot(gs[i])
plt.axis('off')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_aspect('equal')
plt.imshow(sample)
return fig
aD = discriminator()
#aD = torch.load('discriminator.model')
aD.cuda()
aG = generator()
#aG = torch.load('generator.model')
aG.cuda()
optimizer_g = torch.optim.Adam(aG.parameters(), lr=0.0001, betas=(0,0.9))
optimizer_d = torch.optim.Adam(aD.parameters(), lr=0.0001, betas=(0,0.9))
criterion = nn.CrossEntropyLoss()
np.random.seed(352)
n_z =100
n_classes = 10
label = np.asarray(list(range(10))*10)
noise = np.random.normal(0,1,(100,n_z))
label_onehot = np.zeros((100,n_classes))
label_onehot[np.arange(100), label] = 1
noise[np.arange(100), :n_classes] = label_onehot[np.arange(100)]
noise = noise.astype(np.float32)
save_noise = torch.from_numpy(noise)
save_noise = Variable(save_noise).cuda()
import time
start_time = time.time()
gen_train = 1
batch_size = 64
learning_rate = 0.0001
num_epochs = 400
# Train the model
for epoch in range(0,num_epochs):
loss1 = []
loss2 = []
loss3 = []
loss4 = []
loss5 = []
acc1 = []
if(epoch>6):
for group in optimizer_g.param_groups:
for p in group['params']:
state = optimizer_g.state[p]
if(state['step']>=1024):
state['step'] = 1000
if(epoch>6):
for group in optimizer_d.param_groups:
for p in group['params']:
state = optimizer_d.state[p]
if(state['step']>=1024):
state['step'] = 1000
aG.train()
aD.train()
for batch_idx, (X_train_batch, Y_train_batch) in enumerate(trainloader):
if(Y_train_batch.shape[0] < batch_size):
continue
# train G
if 1==1:
if((batch_idx%gen_train)==0):
for p in aD.parameters():
p.requires_grad_(False)
aG.zero_grad()
label = np.random.randint(0,n_classes,batch_size)
noise = np.random.normal(0,1,(batch_size,n_z))
label_onehot = np.zeros((batch_size,n_classes))
label_onehot[np.arange(batch_size), label] = 1
noise[np.arange(batch_size), :n_classes] = label_onehot[np.arange(batch_size)]
noise = noise.astype(np.float32)
noise = torch.from_numpy(noise)
noise = Variable(noise).cuda()
fake_label = Variable(torch.from_numpy(label)).cuda()
fake_data = aG(noise)
gen_source, gen_class = aD(fake_data)
gen_source = gen_source.mean()
gen_class = criterion(gen_class, fake_label)
gen_cost = -gen_source + gen_class
gen_cost.backward()
optimizer_g.step()
# train D
if 2==2:
for p in aD.parameters():
p.requires_grad_(True)
aD.zero_grad()
# train discriminator with input from generator
label = np.random.randint(0,n_classes,batch_size)
noise = np.random.normal(0,1,(batch_size,n_z))
label_onehot = np.zeros((batch_size,n_classes))
label_onehot[np.arange(batch_size), label] = 1
noise[np.arange(batch_size), :n_classes] = label_onehot[np.arange(batch_size)]
noise = noise.astype(np.float32)
noise = torch.from_numpy(noise)
noise = Variable(noise).cuda()
fake_label = Variable(torch.from_numpy(label)).cuda()
with torch.no_grad():
fake_data = aG(noise)
disc_fake_source, disc_fake_class = aD(fake_data)
disc_fake_source = disc_fake_source.mean()
disc_fake_class = criterion(disc_fake_class, fake_label)
# train discriminator with input from the discriminator
real_data = Variable(X_train_batch).cuda()
real_label = Variable(Y_train_batch).cuda()
disc_real_source, disc_real_class = aD(real_data)
prediction = disc_real_class.data.max(1)[1]
accuracy = ( float( prediction.eq(real_label.data).sum() ) /float(batch_size))*100.0
disc_real_source = disc_real_source.mean()
disc_real_class = criterion(disc_real_class, real_label)
gradient_penalty = calc_gradient_penalty(aD,real_data,fake_data)
disc_cost = disc_fake_source - disc_real_source + disc_real_class + disc_fake_class + gradient_penalty
disc_cost.backward()
optimizer_d.step()
loss1.append(gradient_penalty.item())
loss2.append(disc_fake_source.item())
loss3.append(disc_real_source.item())
loss4.append(disc_real_class.item())
loss5.append(disc_fake_class.item())
acc1.append(accuracy)
if((batch_idx%50)==0):
print(epoch, batch_idx, "%.2f" % np.mean(loss1),
"%.2f" % np.mean(loss2),
"%.2f" % np.mean(loss3),
"%.2f" % np.mean(loss4),
"%.2f" % np.mean(loss5),
"%.2f" % np.mean(acc1))
aD.eval()
with torch.no_grad():
test_accu = []
for batch_idx, (X_test_batch, Y_test_batch) in enumerate(testloader):
X_test_batch, Y_test_batch= Variable(X_test_batch).cuda(),Variable(Y_test_batch).cuda()
with torch.no_grad():
_, output = aD(X_test_batch)
prediction = output.data.max(1)[1] # first column has actual prob.
accuracy = ( float( prediction.eq(Y_test_batch.data).sum() ) /float(batch_size))*100.0
test_accu.append(accuracy)
accuracy_test = np.mean(test_accu)
print('Testing',accuracy_test, time.time()-start_time)
### save output
with torch.no_grad():
aG.eval()
samples = aG(save_noise)
samples = samples.data.cpu().numpy()
samples += 1.0
samples /= 2.0
samples = samples.transpose(0,2,3,1)
aG.train()
fig = plot(samples)
plt.savefig('output/%s.png' % str(epoch).zfill(3), bbox_inches='tight')
plt.close(fig)
if(((epoch+1)%1)==0):
torch.save(aG,'tempG.model')
torch.save(aD,'tempD.model')
torch.save(aG,'generator.model')
torch.save(aD,'discriminator.model')
<file_sep>/Residual Network/ResNet.py
import torch
import torchvision
import torchvision.transforms as transforms
from torch.autograd import Variable
import numpy as np
#Data Augmentation
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
trainset = torchvision.datasets.CIFAR100(root='./data', train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=16, shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR100(root='./data', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=16, shuffle=False, num_workers=2)
#classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
import matplotlib.pyplot as plt
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
def conv3x3(in_planes, out_planes, kernel_size=3, stride=1):
#print(in_planes, out_planes)
return nn.Conv2d(in_planes, out_planes, kernel_size, stride=stride, padding=1)
class BasicBlock1(nn.Module):
#expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock1, self).__init__()
self.conv1 = nn.Conv2d(32, 32, 3, 1, padding=1)
#print(inplanes, planes)
self.bn1 = nn.BatchNorm2d(32)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(32, 32,3,1,1)
self.bn2 = nn.BatchNorm2d(32)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
#print(residual.shape)
#print(x.shape)
x = self.conv1(x)
#print(x.shape)
x = self.bn1(x)
#print(x.shape)
x = self.relu(x)
#print(x.shape)
x = self.conv2(x)
#print(x.shape)
x = self.bn2(x)
#print(x.shape)
if self.downsample is not None:
residual = self.downsample(x)
#print(residual.shape)
x += residual
#print(x.shape)
#x = self.relu(x)
#print(x.shape)
return x
class BasicBlock2(nn.Module):
#expansion = 1
def __init__(self, inplanes, planes, stride=1, upsample=None):
super(BasicBlock2, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, 3, stride, padding=1)
#print(inplanes, planes)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(64, 64,3,1,1)
self.bn2 = nn.BatchNorm2d(64)
self.upsample = upsample
self.upsample1 = nn.Upsample(32)
self.stride = stride
self.conv3 = nn.Conv2d(32, 64,1,1,0)
self.inplanes = inplanes
def forward(self, x):
if(self.inplanes ==32):
residual = self.conv3(x)
else:
residual = x
#print(residual.shape)
#print(x.shape)
x = self.conv1(x)
#print(x.shape)
x = self.bn1(x)
#print(x.shape)
x = self.relu(x)
#print(x.shape)
x = self.conv2(x)
#print(x.shape)
x = self.bn2(x)
#print(x.shape)
if self.upsample is not None:
x = self.upsample1(x)
#print(x.shape)
x += residual
#print(x.shape)
#x = self.relu(x)
#print(x.shape)
return x
class BasicBlock3(nn.Module):
#expansion = 1
def __init__(self, inplanes, planes, stride=1, upsample=None):
super(BasicBlock3, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, 3, stride, padding=1)
#print(inplanes, planes)
self.bn1 = nn.BatchNorm2d(128)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(128, 128,3,1,1)
self.bn2 = nn.BatchNorm2d(128)
self.upsample = upsample
self.upsample1 = nn.Upsample(32)
self.stride = stride
self.conv3 = nn.Conv2d(64, 128,1,1,0)
self.inplanes = inplanes
def forward(self, x):
if(self.inplanes ==64):
residual = self.conv3(x)
else:
residual = x
#print(residual.shape)
#print(x.shape)
x = self.conv1(x)
#print(x.shape)
x = self.bn1(x)
#print(x.shape)
x = self.relu(x)
#print(x.shape)
x = self.conv2(x)
#print(x.shape)
x = self.bn2(x)
#print(x.shape)
if self.upsample is not None:
x = self.upsample1(x)
#print(x.shape)
x += residual
#print(x.shape)
#x = self.relu(x)
#print(x.shape)
return x
class BasicBlock4(nn.Module):
#expansion = 1
def __init__(self, inplanes, planes, stride=1, upsample=None):
super(BasicBlock4, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, 3, stride, padding=1)
#print(inplanes, planes)
self.bn1 = nn.BatchNorm2d(256)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(256, 256,3,1,1)
self.bn2 = nn.BatchNorm2d(256)
self.upsample = upsample
self.upsample1 = nn.Upsample(32)
self.stride = stride
self.conv3 = nn.Conv2d(128, 256,1,1,0)
self.inplanes = inplanes
def forward(self, x):
if(self.inplanes ==128):
residual = self.conv3(x)
else:
residual = x
#print(residual.shape)
#print(x.shape)
x = self.conv1(x)
#print(x.shape)
x = self.bn1(x)
#print(x.shape)
x = self.relu(x)
#print(x.shape)
x = self.conv2(x)
#print(x.shape)
x = self.bn2(x)
#print(x.shape)
if self.upsample is not None:
x = self.upsample1(x)
#print(x.shape)
x += residual
#print(x.shape)
#x = self.relu(x)
#print(x.shape)
return x
class ResNet(nn.Module):
def __init__(self):
super(ResNet, self).__init__()
self.conv1 = conv3x3(3,32, stride=1)
self.bn1 = nn.BatchNorm2d(32)
self.dropout1 = nn.Dropout(0.3)
self.layers1 = self._make_layer1(2, 32, 32, 1)
self.layers2 = self._make_layer2(4, 32, 64, 2)
self.layers3 = self._make_layer3(4, 64, 128, 2)
self.layers4 = self._make_layer4(2, 128, 256, 2)
self.pool1 = nn.MaxPool2d(2, 2)
self.linear = nn.Linear(65536, 100)
def _make_layer1(self, layer_count, channels_in, channels, stride):
basicblock = BasicBlock1(channels_in, channels, stride)
basicblock1 = BasicBlock1(channels, channels)
downsample = None
if ((stride != 1) or (channels_in != channels)):
downsample = nn.Sequential(conv3x3(channels_in, channels, kernel_size=1, stride=stride),nn.BatchNorm2d(channels))
layers = []
#print(channels_in, channels)
layers.append(basicblock)
#print(channels_in, channels,stride)
for i in range(1,layer_count):
layers.append(basicblock1)
#print(channels_in, channels)
return nn.Sequential(*layers)
def _make_layer2(self, layer_count, channels_in, channels, stride):
upsample = None
if (stride != 1):
upsample = 1
layers = []
layers.append(BasicBlock2(channels_in, channels, stride, upsample))
#print(channels_in, channels,stride)
for i in range(1,layer_count):
layers.append(BasicBlock2(channels, channels))
#print(channels_in, channels)
return nn.Sequential(*layers)
def _make_layer3(self, layer_count, channels_in, channels, stride):
upsample = None
if (stride != 1):
upsample = 1
layers = []
layers.append(BasicBlock3(channels_in, channels, stride, upsample))
#print(channels_in, channels,stride)
for i in range(1,layer_count):
layers.append(BasicBlock3(channels, channels))
#print(channels_in, channels)
return nn.Sequential(*layers)
def _make_layer4(self, layer_count, channels_in, channels, stride):
upsample = None
if (stride != 1):
upsample = 1
layers = []
layers.append(BasicBlock4(channels_in, channels, stride, upsample))
#print(channels_in, channels,stride)
for i in range(1,layer_count):
layers.append(BasicBlock4(channels, channels))
#print(channels_in, channels)
return nn.Sequential(*layers)
def forward(self, x):
x = self.bn1(self.conv1(x))
#print(x.shape)
x = (F.relu(x))
#print(x.shape)
x = self.dropout1(x)
#print(x.shape)
x = self.layers1(x)
#print(x.shape)
x = self.layers2(x)
#print(x.shape)
x = self.layers3(x)
#print(x.shape)
x = self.layers4(x)
#print(x.shape)
x = self.pool1(x)
#print(x.shape)
x = x.view(x.size(0), -1)
#print(x.shape)
#print('shapesfixed')
x = self.linear(x)
#print(x.shape)
#print('shapesfixed')
return x
net = ResNet()
net.cuda()
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.0001, momentum=0.9)
#optimizer = optim.Adam(net.parameters(), lr=0.0001)
for epoch in range(100):
running_loss = 0.0
train_accu = []
for i, data in enumerate(trainloader, 0):
# get the inputs
inputs, labels = data
batch_size = len(inputs)
inputs = Variable(inputs).cuda()
labels = Variable(labels).cuda()
#print('input_shape',inputs.shape)
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
prediction = outputs.data.max(1)[1]
accuracy = ( float( prediction.eq(labels.data).sum() ) /float(batch_size))*100.0
train_accu.append(accuracy)
accuracy_epoch = np.mean(train_accu)
print(epoch, accuracy_epoch)
if (epoch%5==4):
correct = 0
total = 0
for data in testloader:
inputs, labels = data
inputs, labels = Variable(inputs).cuda(), Variable(labels).cuda()
outputs = net(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
#correct += (predicted == labels).sum().item()
correct+=predicted.eq(labels.data).sum()
print('Accuracy of the network on the 10000 test images: %d %%' % (100.0 * float(correct) / float(total)))
print('Finished Training')
<file_sep>/README.md
# Deep-Learning
IE 534/CS 598 UIUC
<file_sep>/Deep Convolution Network/DCN.py
import torch
import torchvision
import torchvision.transforms as transforms
from torch.autograd import Variable
import numpy as np
import matplotlib.pyplot as plt
import torch.nn as nn
import torch.nn.functional as F
#Data Augmentation
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=128, shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3,64,kernel_size=4, stride=1, padding=2)
self.bn1 = nn.BatchNorm2d(64)
self.conv2 = nn.Conv2d(64,64,kernel_size=4, stride=1, padding=2)
self.pool1 = nn.MaxPool2d(2, 2)
self.dropout1 = nn.Dropout(0.2)
self.conv3 = nn.Conv2d(64,64,kernel_size=4, stride=1, padding=2)
self.bn2 = nn.BatchNorm2d(64)
self.conv4 = nn.Conv2d(64,64,kernel_size=4, stride=1, padding=2)
self.pool2 = nn.MaxPool2d(2, 2)
self.dropout2 = nn.Dropout(0.2)
self.conv5 = nn.Conv2d(64,64,kernel_size=4, stride=1, padding=2)
self.bn3 = nn.BatchNorm2d(64)
self.conv6 = nn.Conv2d(64,64,kernel_size=3, stride=1, padding=0)
self.dropout3 = nn.Dropout(0.2)
self.conv7 = nn.Conv2d(64,64,kernel_size=3, stride=1, padding=0)
self.bn4 = nn.BatchNorm2d(64)
self.conv8 = nn.Conv2d(64,64,kernel_size=3, stride=1, padding=0)
self.bn5 = nn.BatchNorm2d(64)
self.dropout4 = nn.Dropout(0.2)
self.fc1 = nn.Linear(1024, 500)
self.fc2 = nn.Linear(500, 10)
def forward(self, x):
x = self.bn1(F.relu(self.conv1(x)))
x = self.pool1(F.relu(self.conv2(x)))
x = self.dropout1(x)
x = self.bn2(F.relu(self.conv3(x)))
x = self.pool2(F.relu(self.conv4(x)))
x = self.dropout2(x)
x = self.bn3(F.relu(self.conv5(x)))
x = (F.relu(self.conv6(x)))
x = self.dropout3(x)
x = self.bn4(F.relu(self.conv7(x)))
x = self.bn5(F.relu(self.conv8(x)))
x = self.dropout4(x)
x = x.view(-1, 64*4*4)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
return x
net = Net()
net.cuda()
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=0.0001)
for epoch in range(100):
running_loss = 0.0
train_accu = []
for i, data in enumerate(trainloader, 0):
# get the inputs
inputs, labels = data
batch_size = len(inputs)
inputs = Variable(inputs).cuda()
labels = Variable(labels).cuda()
#print('input_shape',inputs.shape)
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
if(i>6):
for group in optimizer.param_groups:
for p in group['params']:
state = optimizer.state[p]
if(state['step']>=1024):
state['step'] = 1000
optimizer.step()
prediction = outputs.data.max(1)[1]
accuracy = ( float( prediction.eq(labels.data).sum() ) /float(batch_size))*100.0
train_accu.append(accuracy)
accuracy_epoch = np.mean(train_accu)
print(epoch, accuracy_epoch)
print('Finished Training')
#Test Accuracy
correct = 0
total = 0
for data in testloader:
inputs, labels = data
inputs, labels = Variable(inputs).cuda(), Variable(labels).cuda()
outputs = net(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
#correct += (predicted == labels).sum().item()
correct+=predicted.eq(labels.data).sum()
print('Accuracy of the network on the 10000 test images: %d %%' % (
100.0 * float(correct) / float(total)))
<file_sep>/GANs/SyntheticFeaturesLayers_WithGenerator.py
import torch
import torchvision
import torchvision.transforms as transforms
from torch.autograd import Variable
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import os
transform_test = transforms.Compose([
transforms.CenterCrop(32),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
testset = torchvision.datasets.CIFAR10(root='./', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=128, shuffle=False, num_workers=8)
testloader = enumerate(testloader)
def plot(samples):
fig = plt.figure(figsize=(10, 10))
gs = gridspec.GridSpec(10, 10)
gs.update(wspace=0.02, hspace=0.02)
for i, sample in enumerate(samples):
ax = plt.subplot(gs[i])
plt.axis('off')
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_aspect('equal')
plt.imshow(sample)
return fig
class discriminator(nn.Module):
def __init__(self):
super(discriminator, self).__init__()
self.conv1 = nn.Conv2d(3,128,kernel_size=3, stride=1, padding=1)
self.ln1 = nn.LayerNorm([128,32,32]).cuda()
self.relu1 = nn.LeakyReLU(0.2)
self.conv2 = nn.Conv2d(128,128,kernel_size=3, stride=2, padding=1)
self.ln2 = nn.LayerNorm([128,16,16]).cuda()
self.relu2 = nn.LeakyReLU(0.2)
self.conv3 = nn.Conv2d(128,128,kernel_size=3, stride=1, padding=1)
self.ln3 = nn.LayerNorm([128,16,16]).cuda()
self.relu3 = nn.LeakyReLU(0.2)
self.conv4 = nn.Conv2d(128,128,kernel_size=3, stride=2, padding=1)
self.ln4 = nn.LayerNorm([128,8,8]).cuda()
self.relu4 = nn.LeakyReLU(0.2)
self.conv5 = nn.Conv2d(128,128,kernel_size=3, stride=1, padding=1)
self.ln5 = nn.LayerNorm([128,8,8]).cuda()
self.relu5 = nn.LeakyReLU(0.2)
self.conv6 = nn.Conv2d(128,128,kernel_size=3, stride=1, padding=1)
self.ln6 = nn.LayerNorm([128,8,8]).cuda()
self.relu6 = nn.LeakyReLU(0.2)
self.conv7 = nn.Conv2d(128,128,kernel_size=3, stride=1, padding=1)
self.ln7 = nn.LayerNorm([128,8,8]).cuda()
self.relu7 = nn.LeakyReLU(0.2)
self.conv8 = nn.Conv2d(128,128,kernel_size=3, stride=2, padding=1)
self.ln8 = nn.LayerNorm([128,4,4]).cuda()
self.relu8 = nn.LeakyReLU(0.2)
self.pool1 = nn.MaxPool2d(4, 4)
self.fc1 = nn.Linear(128, 1)
self.fc10 = nn.Linear(128, 10)
def forward(self, x,extract_features=0):
x = (self.relu1((self.conv1(x))))
x = self.ln1(x)
#print(x.shape)
x = (self.relu2((self.conv2(x))))
x = self.ln2(x)
#print(x.shape)
x = (self.relu3((self.conv3(x))))
x = self.ln3(x)
#print(x.shape)
x = (self.relu4((self.conv4(x))))
x = self.ln4(x)
#if(extract_features==4):
#x = F.max_pool2d(x,8,8)
#x = x.view(x.size(0),-1)
#return x
#print(x.shape)
x = (self.relu5((self.conv5(x))))
x = self.ln5(x)
#print(x.shape)
x = (self.relu6((self.conv6(x))))
x = self.ln6(x)
#print(x.shape)
x = (self.relu7((self.conv7(x))))
x = self.ln7(x)
#print(x.shape)
x = (self.relu8((self.conv8(x))))
x = self.ln8(x)
if(extract_features==8):
x = F.max_pool2d(x,4,4)
x = x.view(x.size(0),-1)
return x
x = self.pool1(x)
#print(x.shape)
x = x.view(x.size(0),-1)
x1 = (self.fc1(x))
#print(x.shape)
x2 = (self.fc10(x))
#print(x.shape)
#x = self.fc3(x)
return x1,x2
model = discriminator()
#model.load_state_dict(torch.load('parameters.ckpt'))
model = torch.load('discriminator.model')
model.cuda()
batch_size = 64
batch_idx, (X_batch, Y_batch) = testloader.__next__()
X_batch = Variable(X_batch,requires_grad=True).cuda()
Y_batch_alternate = (Y_batch + 1)%10
Y_batch_alternate = Variable(Y_batch_alternate).cuda()
Y_batch = Variable(Y_batch).cuda()
X = X_batch.mean(dim=0)
X = X.repeat(batch_size,1,1,1)
Y = torch.arange(batch_size).type(torch.int64)
Y = Variable(Y).cuda()
lr = 0.1
weight_decay = 0.001
for i in range(200):
_,output = model(X, extract_features=8)
loss = -output[torch.arange(batch_size).type(torch.int64),torch.arange(batch_size).type(torch.int64)]
gradients = torch.autograd.grad(outputs=loss, inputs=X,
grad_outputs=torch.ones(loss.size()).cuda(),
create_graph=True, retain_graph=False, only_inputs=True)[0]
prediction = output.data.max(1)[1] # first column has actual prob.
accuracy = ( float( prediction.eq(Y.data).sum() ) /float(batch_size))*100.0
print(i,accuracy,-loss)
X = X - lr*gradients.data - weight_decay*X.data*torch.abs(X.data)
X[X>1.0] = 1.0
X[X<-1.0] = -1.0
## save new images
samples = X.data.cpu().numpy()
samples += 1.0
samples /= 2.0
samples = samples.transpose(0,2,3,1)
fig = plot(samples[0:100])
plt.savefig('visualization/max_features_8_dg.png', bbox_inches='tight')
plt.close(fig)<file_sep>/GANs/DiscriminatorWithoutGenerator.py
import torch
import torchvision
import torchvision.transforms as transforms
from torch.autograd import Variable
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
transform_train = transforms.Compose([
transforms.RandomResizedCrop(32, scale=(0.7, 1.0), ratio=(1.0,1.0)),
transforms.ColorJitter(
brightness=0.1*torch.randn(1),
contrast=0.1*torch.randn(1),
saturation=0.1*torch.randn(1),
hue=0.1*torch.randn(1)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
transform_test = transforms.Compose([
transforms.CenterCrop(32),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
trainset = torchvision.datasets.CIFAR10(root='./', train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True, num_workers=8)
testset = torchvision.datasets.CIFAR10(root='./', train=False, download=False, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False, num_workers=8)
class discriminator(nn.Module):
def __init__(self):
super(discriminator, self).__init__()
self.conv1 = nn.Conv2d(3,128,kernel_size=3, stride=1, padding=1)
self.ln1 = nn.LayerNorm([128,32,32]).cuda()
self.relu1 = nn.LeakyReLU(0.2)
self.conv2 = nn.Conv2d(128,128,kernel_size=3, stride=2, padding=1)
self.ln2 = nn.LayerNorm([128,16,16]).cuda()
self.relu2 = nn.LeakyReLU(0.2)
self.conv3 = nn.Conv2d(128,128,kernel_size=3, stride=1, padding=1)
self.ln3 = nn.LayerNorm([128,16,16]).cuda()
self.relu3 = nn.LeakyReLU(0.2)
self.conv4 = nn.Conv2d(128,128,kernel_size=3, stride=2, padding=1)
self.ln4 = nn.LayerNorm([128,8,8]).cuda()
self.relu4 = nn.LeakyReLU(0.2)
self.conv5 = nn.Conv2d(128,128,kernel_size=3, stride=1, padding=1)
self.ln5 = nn.LayerNorm([128,8,8]).cuda()
self.relu5 = nn.LeakyReLU(0.2)
self.conv6 = nn.Conv2d(128,128,kernel_size=3, stride=1, padding=1)
self.ln6 = nn.LayerNorm([128,8,8]).cuda()
self.relu6 = nn.LeakyReLU(0.2)
self.conv7 = nn.Conv2d(128,128,kernel_size=3, stride=1, padding=1)
self.ln7 = nn.LayerNorm([128,8,8]).cuda()
self.relu7 = nn.LeakyReLU(0.2)
self.conv8 = nn.Conv2d(128,128,kernel_size=3, stride=2, padding=1)
self.ln8 = nn.LayerNorm([128,4,4]).cuda()
self.relu8 = nn.LeakyReLU(0.2)
self.pool1 = nn.MaxPool2d(4, 4)
#self.fc1 = nn.Linear(196, 1)
self.fc10 = nn.Linear(128, 10)
def forward(self, x):
x = (self.relu1((self.conv1(x))))
x = self.ln1(x)
#print(x.shape)
x = (self.relu2((self.conv2(x))))
x = self.ln2(x)
#print(x.shape)
x = (self.relu3((self.conv3(x))))
x = self.ln3(x)
#print(x.shape)
x = (self.relu4((self.conv4(x))))
x = self.ln4(x)
#print(x.shape)
x = (self.relu5((self.conv5(x))))
x = self.ln5(x)
#print(x.shape)
x = (self.relu6((self.conv6(x))))
x = self.ln6(x)
#print(x.shape)
x = (self.relu7((self.conv7(x))))
x = self.ln7(x)
#print(x.shape)
x = (self.relu8((self.conv8(x))))
x = self.ln8(x)
x = self.pool1(x)
#print(x.shape)
x = x.view(x.size(0),-1)
#x = (self.fc1(x))
#print(x.shape)
x = (self.fc10(x))
#print(x.shape)
#x = self.fc3(x)
return x
model = discriminator()
#model.load_state_dict(torch.load('parameters.ckpt'))
model.cuda()
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.0001)
batch_size = 64
learning_rate = 0.0001
for epoch in range(100):
running_loss = 0.0
train_accu = []
for batch_idx, (X_train_batch, Y_train_batch) in enumerate(trainloader):
if(Y_train_batch.shape[0] < batch_size):
continue
# get the inputs
X_train_batch = Variable(X_train_batch).cuda()
Y_train_batch = Variable(Y_train_batch).cuda()
output = model(X_train_batch)
optimizer.zero_grad()
loss = criterion(output, Y_train_batch)
loss.backward()
if(epoch>6):
for group in optimizer.param_groups:
for p in group['params']:
state = optimizer.state[p]
if(state['step']>=1024):
state['step'] = 1000
optimizer.step()
prediction = output.data.max(1)[1]
accuracy = ( float( prediction.eq(Y_train_batch.data).sum() ) /float(batch_size))*100.0
train_accu.append(accuracy)
accuracy_epoch = np.mean(train_accu)
print(epoch, accuracy_epoch)
if(epoch==50):
for param_group in optimizer.param_groups:
param_group['lr'] = learning_rate/10.0
if(epoch==75):
for param_group in optimizer.param_groups:
param_group['lr'] = learning_rate/100.0
if (epoch%10==9):
correct = 0
total = 0
for batch_idx, (X_test_batch, Y_test_batch) in enumerate(testloader):
X_test_batch = Variable(X_test_batch).cuda()
Y_test_batch = Variable(Y_test_batch).cuda()
output = model(X_test_batch)
_, predicted = torch.max(output.data, 1)
total += Y_test_batch.size(0)
#correct += (predicted == labels).sum().item()
correct+=predicted.eq(Y_test_batch.data).sum()
print('Accuracy of the network on the 10000 test images: %d %%' % (100.0 * float(correct) / float(total)))
torch.save(model.state_dict(),'parameters.ckpt')
<file_sep>/Residual Network/Transfer_Learning.py
import torch
import torchvision
import torchvision.transforms as transforms
from torch.autograd import Variable
import numpy as np
import torch.nn as nn
#Data Augmentation
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
trainset = torchvision.datasets.CIFAR100(root='./data', train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True, num_workers=4)
testset = torchvision.datasets.CIFAR100(root='./data', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False, num_workers=4)
#classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
import matplotlib.pyplot as plt
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
def resnet18(pretrained = True) :
model_urls = {'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth'}
model = torchvision.models.resnet.ResNet(torchvision.models.resnet.BasicBlock, [2, 2, 2, 2])
if pretrained :
model.load_state_dict(torch.utils.model_zoo.load_url(model_urls['resnet18'], model_dir ='./'))
return model
model = resnet18(pretrained=True)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 100)
model = model.cuda()
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
# Observe that all parameters are being optimized
optimizer_ft = optim.SGD(model.parameters(), lr=0.0001, momentum=0.9)
for epoch in range(100):
running_loss = 0.0
train_accu = []
for i, data in enumerate(trainloader, 0):
# get the inputs
inputs, labels = data
US = nn.Upsample(scale_factor=7)
inputs = US(inputs)
batch_size = len(inputs)
inputs = inputs.cuda()
labels = Variable(labels).cuda()
#print('input_shape',inputs.shape)
# zero the parameter gradients
optimizer_ft.zero_grad()
# forward + backward + optimize
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer_ft.step()
prediction = outputs.data.max(1)[1]
accuracy = ( float( prediction.eq(labels.data).sum() ) /float(batch_size))*100.0
train_accu.append(accuracy)
accuracy_epoch = np.mean(train_accu)
print(epoch, accuracy_epoch)
if (epoch%5==4):
correct = 0
total = 0
for data in testloader:
inputs, labels = data
US = nn.Upsample(scale_factor=7)
inputs = US(inputs)
inputs, labels = inputs.cuda(), Variable(labels).cuda()
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
#correct += (predicted == labels).sum().item()
correct+=predicted.eq(labels.data).sum()
print('Accuracy of the network on the 10000 test images: %d %%' % (100.0 * float(correct) / float(total)))
print('Finished Training')
| 8a3d1c25c928faf4974bb47321500c5f147a2d48 | [
"Markdown",
"Python"
]
| 7 | Python | edwinjose900/Deep_Learning | 62c616b168cce504fe8596298c9715031e1dfc67 | 369686897005e2d1b14a11377007be5a015e59a1 |
refs/heads/master | <file_sep>### 说明
抓取指定页之间所有mzitu套图,保存在当前目录的temp目录下.
### 代码中出现的一些库
myrequests: 对requests进行了一些封装
[https://github.com/zzzzer91/myrequests](https://github.com/zzzzer91/myrequests)
finished: 打印函数运行所耗时间
[https://github.com/zzzzer91/finished](https://github.com/zzzzer91/finished)<file_sep>#!/usr/bin/env python3
# coding:utf-8
"""抓取mzitu指定页之间所有套图, 保存在当前目录的temp目录下."""
import re
import os
from multiprocessing import Pool
import myrequests as requests
from bs4 import BeautifulSoup
from finished import finished
def post_url_list(x=1, y=2):
"""获取指定页之间所有图集的url.
:param x: int, 起始页.
:param y: int, 结束页.
:return post_url: str, 图集链接.
"""
url = 'http://www.mzitu.com'
with requests.Session() as session:
for i in range(x, y):
if i == 1:
page_url = url
else:
page_url = '%s/page/%d/' % (url, i)
r = session.get(page_url)
if r:
soup = BeautifulSoup(r.text, 'lxml')
post_tag_list = soup.select('div.postlist li > span > a')
for post_tag in post_tag_list:
yield post_tag.get('href')
def download(url):
"""以图集名创建文件夹, 下载图集中所有图片.
:param url: str, 图集链接.
"""
pattern = re.compile(r'[\\/:*?"<>| ]')
with requests.Session() as session:
session.headers['referer'] = 'http://www.mzitu.com'
r = session.get(url)
if r:
soup = BeautifulSoup(r.text, 'lxml')
post_name = soup.select('h2.main-title')[0].get_text()
# 剔除不符合文件夹命名规则的字符
post_name = pattern.sub('', post_name)
path = 'temp/%s' % post_name
if not os.path.exists(path):
os.mkdir(path)
# 获取图片数量
img_num = int(soup.select('div.pagenavi a span')[-2].get_text())
# 图片url的模板
temp_url = soup.select('div.main-image img')[0].get('src')[:-6]
for i in range(1, img_num+1):
img_url = '%s%02d.jpg' % (temp_url, i)
r = session.get(img_url)
if r:
with open('%s/%02d.jpg' % (path, i), 'wb') as f:
f.write(r.content)
@finished
def main():
if not os.path.exists('temp'):
os.mkdir('temp')
with Pool(8) as pool:
pool.map(download, post_url_list(x=1, y=2))
if __name__ == '__main__':
main()
| eb4b3cb0e6ea3a1b8c54bc9c0429e71a5bd3cd08 | [
"Markdown",
"Python"
]
| 2 | Markdown | zzzzzer/mzitu_spider | c9af2963b3c7f15bec974213896edef1079b5b25 | 903fdff366b3e61910d566f72ebe9bb3ea5d7687 |
refs/heads/master | <file_sep># Define your working directory
setwd("C:/Users/admin/Documents/Naive Bayes")
getwd()
# Before we start modelling, let's analyse data
# Read all of the LGA profiles into a data frame
lga.profile <- read.csv("Data/Vic-2013-LGA-Profiles-NoPc.csv")
# Select candidate variables (based on my personal hunches)
lga <- lga.profile$LGA
crime <- lga.profile$SocEngag.11
soc <- lga.profile$SocEngag.21
sitting <- lga.profile$Health.25
safe <- lga.profile$SocEngag.13
education <- lga.profile$Edu.10
highblood <- lga.profile$Medical.5
poorteeth <- lga.profile$Medical.31
avoidabledeath <- lga.profile$Injury.9
doctors <- lga.profile$HealthServices.4
wellbeing <- lga.profile$WellBeing.15
# View the variables and explore them
plot(density(wellbeing))
plot(density(crime))
plot(density(soc))
plot(density(sitting))
plot(density(safe))
plot(density(highblood))
plot(density(poorteeth))
plot(density(doctors))
plot(wellbeing)
hist(wellbeing, breaks=20)
summary(wellbeing)
# Based on the distribution of "wellbeing"
# define "wellcl" to be used in Naive-Bayes classification
# with breaks: 0-0.47 Low, 0.47-0.55 Medium, >0.55 High
wellcl <- ifelse(wellbeing < 0.47, "Low", ifelse(wellbeing < 0.55, "Medium", "High"))
# Use all variables, except for the class/factor variable
wb <- data.frame(education, soc, safe, sitting, crime,
highblood, poorteeth, avoidabledeath, doctors,
wellbeing)
# Explore data to check for variable dependencies
# As all are numeric, we will rely on correlation
# Check if there are any visible correlations
pairs(wb,
main = "Wellbeing Correlations (g=Low,b=Med,r=High)",
pch = 21, bg = c("red", "green3", "blue")[unclass(factor(wellcl))])
# If we deal with nominal / discrete vars use Chi-Sq
# If we deal with continuous vars use correlation function and plots
# Get a correlation matrix
corrm <- cor(wb)
round(corrm, digits = 3)
# Print a simple correlation matrix
install.packages("corrplot", dependencies = TRUE)
library(corrplot)
corrplot(corrm, method = "circle")
# Create a correlation corgram
install.packages("corrgram", dependencies = TRUE)
library(corrgram)
corrgram(wb, order=TRUE,
main="LGA Wellbeing",
lower.panel=panel.shade, upper.panel=panel.pie,
diag.panel=panel.minmax, text.panel=panel.txt)
corrgram(wb, order=TRUE,
main="LGA Wellbeing",
panel=panel.ellipse,
text.panel=panel.txt, diag.panel=panel.minmax)
# Remove: crime, doctors, education, soc
# Redefine wb data frame by removing highly correlated vars
wb <- data.frame(safe, sitting, highblood, poorteeth,
avoidabledeath, wellcl)
View(wb)
# Includes pairs.panels
install.packages("psych", dependencies = TRUE)
library("psych")
# Includes naiveBayes
install.packages("e1071", dependencies = TRUE)
library("e1071")
# Includes confusionMatrix
install.packages("caret", dependencies = TRUE)
library(caret)
lga.profile <- read.csv("Data/Vic-2013-LGA-Profiles-NoPc.csv")
# Select candidate variables (based on my personal hunch)
lga <- lga.profile$LGA # Names and the rest
crime <- lga.profile$SocEngag.11 # Was crimes per 1000 population
soc <- lga.profile$SocEngag.21 # % of time using social media
sitting <- lga.profile$Health.25 # % of people sitting longer than 7 hours
safe <- lga.profile$SocEngag.13 # % of people feeling safe walking alone
education <- lga.profile$Edu.10 # % of people with higher education
highblood <- lga.profile$Medical.5 # % of people reporting high blood pressure
poorteeth <- lga.profile$Medical.31 # % of people with poor dental health
ad <- lga.profile$Injury.9 # Number of avoidable deaths
avoidabledeath <- (ad - min(ad))/(max(ad)-min(ad)) # Standardised avodable deaths
doctors <- lga.profile$HealthServices.4 # GPs per 1000, small number 0-1.5
wellbeing <- lga.profile$WellBeing.15 # % of people with adequate work / life balance
# Let us look again at the data
wb.raw <- data.frame(safe, sitting, highblood, poorteeth,
avoidabledeath, wellbeing)
pairs.panels(wb.raw)
# Define a categorical class variable
wellcl <- ifelse(wellbeing < 0.47, "Low",
ifelse(wellbeing < 0.55, "Medium", "High"))
wb <- data.frame(safe, sitting, highblood, poorteeth,
avoidabledeath, wellcl)
# Split data into training and validation parts
# set random seed to some value so that results are consistent
set.seed(2016)
wb.size <- length(wellbeing)
wb.train.size <- round(wb.size * 0.7) # 70% for training
wb.validation.size <- wb.size - wb.train.size # The rest for testing
wb.train.idx <- sample(seq(1:wb.size), wb.train.size) # Indeces for training
wb.train.sample <- wb[wb.train.idx,]
wb.validation.sample <- wb[-wb.train.idx,]
# Validate NB classifiers, check their performance and refine them
# Let's see the performance of all variables, excluding wellbeing
classf <- naiveBayes(
subset(wb.train.sample, select = -wellcl),
wb.train.sample$wellcl, laplace=1)
classf
preds <- predict(classf,
subset(wb.validation.sample, select = -wellcl))
table(preds, wb.validation.sample$wellcl)
round(sum(preds == wb.validation.sample$wellcl, na.rm=TRUE) /
length(wb.validation.sample$wellcl), digits = 2)
# We could better report the performance using "caret" package
library(caret)
confusionMatrix(table(preds, wb.validation.sample$wellcl))
# Many mislassifications, how about the following ideas:
# - Change the mix of variables, e.g. replace sitting with soc
# - Remove badly skewed vars, or transform them, e.g. safe
wb <- data.frame(highblood, poorteeth, avoidabledeath, wellcl)
set.seed(2016)
wb.size <- length(wellbeing)
wb.train.size <- round(wb.size * 0.7) # 70% for training
wb.validation.size <- wb.size - wb.train.size # The rest for testing
wb.train.idx <- sample(seq(1:wb.size), wb.train.size) # Indeces for training
wb.train.sample <- wb[wb.train.idx,]
wb.validation.sample <- wb[-wb.train.idx,]
# Validate NB classifiers, check their performance and refine them
# Let's see the performance of all variables, excluding wellbeing
classf <- naiveBayes(
subset(wb.train.sample, select = -wellcl),
wb.train.sample$wellcl, laplace=1)
classf
preds <- predict(classf,
subset(wb.validation.sample, select = -wellcl))
table(preds, wb.validation.sample$wellcl)
round(sum(preds == wb.validation.sample$wellcl, na.rm=TRUE) /
length(wb.validation.sample$wellcl), digits = 2)
# We could better report the performance using "caret" package
library(caret)
confusionMatrix(table(preds, wb.validation.sample$wellcl))
# - Redefine "wellcl", e.g.
wb <- data.frame(safe, sitting, highblood, poorteeth,
avoidabledeath, wellcl)
wellcl <- ifelse(wellbeing < 0.49, "Low", ifelse(wellbeing < 0.57, "Medium", "High"))
# - Add more vars and make a better selection of vars
set.seed(2016)
wb.size <- length(wellbeing)
wb.train.size <- round(wb.size * 0.7) # 70% for training
wb.validation.size <- wb.size - wb.train.size # The rest for testing
wb.train.idx <- sample(seq(1:wb.size), wb.train.size) # Indeces for training
wb.train.sample <- wb[wb.train.idx,]
wb.validation.sample <- wb[-wb.train.idx,]
# Validate NB classifiers, check their performance and refine them
# Let's see the performance of all variables, excluding wellbeing
classf <- naiveBayes(
subset(wb.train.sample, select = -wellcl),
wb.train.sample$wellcl, laplace=1)
classf
preds <- predict(classf,
subset(wb.validation.sample, select = -wellcl))
table(preds, wb.validation.sample$wellcl)
round(sum(preds == wb.validation.sample$wellcl, na.rm=TRUE) /
length(wb.validation.sample$wellcl), digits = 2)
# We could better report the performance using "caret" package
library(caret)
confusionMatrix(table(preds, wb.validation.sample$wellcl))
# And then compare NB with k-NN
# Create a simple k-NN classifier
install.packages("class", dependencies = TRUE)
library(class)
preds <- knn(
subset(wb.train.sample, select = -wellcl),
subset(wb.validation.sample, select = -wellcl),
factor(wb.train.sample$wellcl),
k = 3, prob=TRUE, use.all = TRUE)
library(caret)
confusionMatrix(table(preds, wb.validation.sample$wellcl))
preds <- knn(
subset(wb.train.sample, select = -wellcl),
subset(wb.validation.sample, select = -wellcl),
factor(wb.train.sample$wellcl),
k = 10, prob=TRUE, use.all = TRUE)
library(caret)
confusionMatrix(table(preds, wb.validation.sample$wellcl))
# We split our data randomly into training and validation parts.
# Play with the argument passed into set.seed(V) and see the results.
set.seed(2000)
# There are better ways of doing so, e.g. in the "caret" package.
# More on this in the future.
library(caret)
set.seed(2016)
train_control <- trainControl(method="repeatedcv", number=10, repeats=9)
model <- train(wellcl~., data=wb, trControl=train_control, method="nb")
print(model)
| 0178d107efd9b53c002e71c5eabea6254e650da6 | [
"R"
]
| 1 | R | khv499/Naive-Bayes-Model-for-Prediction | e8e270b0f0c566faabab1b6b7702043e2fa4a181 | 73678ffb894dec00030faa88f4399d742c9aa7a4 |
refs/heads/master | <file_sep>import ij.ImagePlus;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class GetPixelCoordinates {
//int y, x, tofind, col;
/**
* @param args the command line arguments
* @throws IOException
*/
public static void main(String args[]) throws IOException {
//read image file
ImagePlus img = new ImagePlus("/home/otavio/projects/imagepg/src/main/resources/sample.png");
List<Integer> transformed = new ArrayList<>(img.getHeight() * img.getWidth());
for (int y = 0; y < img.getHeight(); y++) {
for (int x = 0; x < img.getWidth(); x++) {
int c[] = img.getPixel(x, y);
int red = c[0];
int green = c[1];
int blue = c[2];
int index = 2 * green - (red + blue);
transformed.add(index);
}
}
int threshold = OtsuThresholder.get(transformed);
System.out.println("Threshold: " + threshold);
//-----------------------------------------------------------------
BufferedImage bufferedImage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB);
Iterator<Integer> pixels = transformed.iterator();
for (int y = 0; y < img.getHeight(); y++) {
for (int x = 0; x < img.getWidth(); x++) {
Integer pixel = pixels.next();
int color = pixel >= threshold ? Color.GREEN.getRGB() : Color.BLACK.getRGB();
bufferedImage.setRGB(x, y, color);
}
}
File outputfile = new File("/home/otavio/projects/imagepg/src/main/resources/classified.png");
ImageIO.write(bufferedImage, "png", outputfile);
}
} | 35d40b229cd655d77f950480e47e11320ec03b71 | [
"Java"
]
| 1 | Java | otaviomacedo/imagepg | 705608ff565d00f979b1aa61c77baf4306475920 | 7eda22751111b51b00861e0055bd1c90cef8b12c |
refs/heads/master | <repo_name>chrhsmt/SampleAndroid<file_sep>/README.md
# SampleAndroid
WEB+DB PRESS Vol.88「モバイル開発最前線」のサンプルコードです。
FabricやCircleCI、SciroccoCloudの設定値はXXXにしています。
<file_sep>/app/src/main/java/project/android/sample/sampleapp/App.java
package project.android.sample.sampleapp;
import android.app.Application;
import com.deploygate.sdk.DeployGate;
import com.crashlytics.android.Crashlytics;
import io.fabric.sdk.android.Fabric;
/**
* Created by s-takayanagi on 6/20/15.
*/
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
Fabric.with(this, new Crashlytics());
DeployGate.install(this);
}
}
| 6d1cd4db3f6470b8b13ec9b6e3fa89409a8af6e7 | [
"Markdown",
"Java"
]
| 2 | Markdown | chrhsmt/SampleAndroid | d7a97f24d8eb1fc753e2bdd2f4c2dac98d9db5d7 | c0fa8b75c8192e78dd58675f814350857e1a7e27 |
refs/heads/master | <file_sep>import numpy as np
import argparse
import matplotlib.pyplot as plt
import cv2
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D, Activation, MaxPool2D, Dropout, Dense, BatchNormalization, Flatten
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu', input_shape=(48, 48, 1)))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(256, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(1024, activation='relu'))
model.add(Dense(6, activation='softmax'))
model.load_weights('mymodelweights_rotate_zoom_flip.h5')
# prevents openCL usage and unnecessary logging messages
cv2.ocl.setUseOpenCL(False)
# dictionary which assigns each label an emotion (alphabetical order)
# emotion_dict = {0: "Angry", 1: "Disgusted", 2: "Fearful",
# 3: "Happy", 4: "Neutral", 5: "Sad", 6: "Surprised"}
emotion_dict = {0: "Angry", 1: "Fearful",
2: "Happy", 3: "Neutral", 4: "Sad", 5: "Surprised"}
# start the webcam feed
cap = cv2.VideoCapture(0)
while True:
# Find haar cascade to draw bounding box around face
ret, frame = cap.read()
if not ret:
break
facecasc = cv2.CascadeClassifier(
cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
# facecasc = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = facecasc.detectMultiScale(
gray, scaleFactor=1.3, minNeighbors=5)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y-50), (x+w, y+h+10), (255, 0, 0), 2)
roi_gray = gray[y:y + h, x:x + w]
cropped_img = np.expand_dims(np.expand_dims(
cv2.resize(roi_gray, (48, 48)), -1), 0)
print('array dimensions' + str(cropped_img.ndim))
prediction = model.predict(cropped_img)
maxindex = int(np.argmax(prediction))
cv2.putText(frame, emotion_dict[maxindex], (x+20, y-60),
cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)
cv2.imshow('Video', cv2.resize(
frame, (1600, 960), interpolation=cv2.INTER_CUBIC))
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
<file_sep>import face_recognition
import imageio
import os
import shutil
margin = 10
maxWidth = 0
maxHeight = 0
list_orig = os.listdir("data") # dir is your directory path
number_files_orig = len(list_orig)
try:
# creating a folder named data
if not os.path.exists('data_mouth'):
os.makedirs('data_mouth')
# if not created then raise error
except OSError:
print('Error: Creating directory of data_mouth')
for i in range(0, number_files_orig):
image = face_recognition.load_image_file("data/frame"+str(i)+".jpg")
face_landmarks_list = face_recognition.face_landmarks(image)
if(len(face_landmarks_list) >= 1):
xMin = 999999
xMax = -999999
yMin = 999999
yMax = -999999
points = face_landmarks_list[0]['bottom_lip'] + \
face_landmarks_list[0]['top_lip']
for point in points:
if point[0] < xMin:
xMin = point[0]
if point[0] > xMax:
xMax = point[0]
if point[1] < yMin:
yMin = point[1]
if point[1] > yMax:
yMax = point[1]
if(yMax-yMin > maxHeight):
maxHeight = yMax-yMin
if(xMax-xMin > maxWidth):
maxWidth = xMax-xMin
arr = imageio.imread("data/frame"+str(i)+".jpg")
imageio.imsave("data_mouth/frame" + str(i) + "mouth" + ".jpg",
arr[yMin-margin:yMax+margin, xMin-margin:xMax+margin])
print("FINISHED IMAGE. Maximum dimensions are " +
str(maxWidth)+" x "+str(maxHeight))
# list_orig = os.listdir("data") # dir is your directory path
list_mouth = os.listdir("data_mouth")
# number_files_orig = len(list_orig)
number_files_mouth = len(list_mouth)
if(number_files_mouth != number_files_orig):
shutil.rmtree("data")
print("deleted")
<file_sep># Insights-README
| e4c29659f76984629f4851a3678d14c01507636c | [
"Markdown",
"Python"
]
| 3 | Python | CornellDataScience/Insights-README | 40e65aee3cd8c633d2b7c449dadb3ba04113791f | 53db008601d34928e6632585ad8150496e9c8dfc |
refs/heads/master | <repo_name>oxivanisher/Youtube-Subscriber-Counter<file_sep>/YouTubeCounterDeepSleepV3/ESP_Helpers.h
#define UPDATEINTERVAL 2
#define RUNINTERVAL 2
#define UPDATE_SERVER "192.168.0.200"
#define UPDATE_URL "/iotappstore/iotappstorev20.php"
#define SECOND_UPDATE_SERVER "iotappstore.org"
#define SECOND_UPDATE_URL "/iotappstore/iotappstorev20.php"
#define SSIDBASE 200
#define PASSWORDBASE 220
#define MAGICBYTE 85
#define RTCMEMBEGIN 68
char ssid[20];
char password[20];
String initSSID = mySSID;
String initPassword = <PASSWORD>;
void handleTelnet() {
if (TelnetServer.hasClient()) {
// client is connected
if (!Telnet || !Telnet.connected()) {
if (Telnet) Telnet.stop(); // client disconnected
Telnet = TelnetServer.available(); // ready for new client
} else {
TelnetServer.available().stop(); // have client, block new conections
}
}
}
void printRTCmem() {
DEBUGPRINTLN1("");
DEBUGPRINTLN1("rtcMem ");
DEBUGPRINT1("markerFlag ");
DEBUGPRINTLN1(rtcMem.markerFlag);
DEBUGPRINT1("runSpaces ");
DEBUGPRINTLN1(rtcMem.runSpaces);
DEBUGPRINT1("updateSpaces ");
DEBUGPRINTLN1(rtcMem.updateSpaces);
DEBUGPRINT1("lastSubscribers ");
DEBUGPRINTLN1(rtcMem.lastSubscribers);
}
void readRTCmem() {
system_rtc_mem_read(RTCMEMBEGIN, &rtcMem, sizeof(rtcMem));
if (rtcMem.markerFlag != MAGICBYTE || rtcMem.lastSubscribers < 0 ) {
rtcMem.markerFlag = MAGICBYTE;
rtcMem.lastSubscribers = 0;
rtcMem.updateSpaces = 0;
rtcMem.runSpaces = 0;
system_rtc_mem_write(RTCMEMBEGIN, &rtcMem, sizeof(rtcMem));
}
printRTCmem();
}
void writeRTCmem() {
rtcMem.markerFlag = MAGICBYTE;
system_rtc_mem_write(RTCMEMBEGIN, &rtcMem, sizeof(rtcMem));
}
bool readCredentials() {
EEPROM.begin(512);
if (EEPROM.read(SSIDBASE - 1) != 0x5) {
Serial.println(EEPROM.read(SSIDBASE - 1), HEX);
initSSID.toCharArray(ssid, initSSID.length() + 1);
for (int ii = 0; ii <= initSSID.length(); ii++) EEPROM.write(SSIDBASE + ii, ssid[ii]);
initPassword.toCharArray(password, initPassword.length() + 1);
for (int ii = 0; ii <= initPassword.length(); ii++) EEPROM.write(PASSWORDBASE + ii, password[ii]);
EEPROM.write(SSIDBASE - 1, 0x35);
}
int i = 0;
do {
ssid[i] = EEPROM.read(SSIDBASE + i);
i++;
} while (ssid[i - 1] > 0 && i < 20);
if (i == 20) DEBUGPRINTLN1("ssid loaded");
i = 0;
do {
password[i] = EEPROM.read(PASSWORDBASE + i);
i++;
} while (password[i - 1] != 0 && i < 20);
if (i == 20) DEBUGPRINTLN1("Pass loaded");
EEPROM.end();
}
void printMacAddress() {
byte mac[6];
WiFi.macAddress(mac);
DEBUGPRINT1("MAC: ");
for (int i = 0; i < 5; i++) {
Serial.print(mac[i], HEX);
Serial.print(":");
}
Serial.println(mac[5], HEX);
}
bool iotUpdater(String server, String url, String firmware, bool immediately, bool debug) {
bool retValue = true;
DEBUGPRINTLN1("");
DEBUGPRINT1("updateSpaces ");
DEBUGPRINTLN1(rtcMem.updateSpaces);
if (rtcMem.updateSpaces >= UPDATEINTERVAL || immediately) {
if (debug) {
printMacAddress();
DEBUGPRINT1("IP = ");
DEBUGPRINTLN1(WiFi.localIP());
DEBUGPRINT1("Update_server ");
DEBUGPRINTLN1(server);
DEBUGPRINT1("UPDATE_URL ");
DEBUGPRINTLN1(url);
DEBUGPRINT1("FIRMWARE_VERSION ");
DEBUGPRINTLN1(firmware);
DEBUGPRINTLN1("Updating...");
}
t_httpUpdate_return ret = ESPhttpUpdate.update(server, 80, url, firmware);
switch (ret) {
case HTTP_UPDATE_FAILED:
retValue = false;
if (debug) Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
DEBUGPRINTLN1();
break;
case HTTP_UPDATE_NO_UPDATES:
if (debug) DEBUGPRINTLN1("HTTP_UPDATE_NO_UPDATES");
break;
case HTTP_UPDATE_OK:
if (debug) DEBUGPRINTLN1("HTTP_UPDATE_OK");
break;
}
DEBUGPRINTLN1("Zero updateSpaces");
rtcMem.updateSpaces = 0;
} else {
rtcMem.updateSpaces = ++rtcMem.updateSpaces; // not yet an update
}
writeRTCmem();
return retValue;
}
<file_sep>/YoutubeCounterNeopixelV1.0/platformio.ini
[platformio]
default_envs = d1_mini
[common]
arduino_core = espressif8266
platform = ${common.arduino_core}
framework = arduino
monitor_speed = 115200
lib_deps =
Adafruit GFX Library
Adafruit NeoMatrix
Adafruit NeoPixel
ArduinoJson
YoutubeApi
https://github.com/maxint-rd/ESP-MusicEngine
https://github.com/SensorsIot/SNTPtime
[env:d1_mini]
board = d1_mini
platform = ${common.platform}
framework = ${common.framework}
lib_deps = ${common.lib_deps}
monitor_speed = ${common.monitor_speed}
lib_ldf_mode=deep
;board_build.flash_mode = qio
; build_flags =
; -DDEBUG_ESP_CORE
; -DDEBUG_ESP_SSL
; -DDEBUG_ESP_TLS_MEM
; -DDEBUG_ESP_HTTP_CLIENT
; -DDEBUG_ESP_WIFI
<file_sep>/YoutubeCounterNeopixelV1.0/src/main.cpp
/* This is an initial sketch to be used as a "blueprint" to create apps which can be used with IOTappstory.com infrastructure
Your code can be filled wherever it is marked.
Copyright (c) [2016] [<NAME>]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <Adafruit_GFX.h>
#include <Adafruit_NeoMatrix.h>
#include <Adafruit_NeoPixel.h>
#include <YoutubeApi.h>
#include <MusicEngine.h>
#include <SNTPtime.h>
#include "config.h"
// ================================================ PIN DEFINITIONS ======================================
#define BUZ_PIN D5
#define NEO_PIN D4
#define POWER_PIN D1
#define NUMBER_OF_DIGITS 6
#define STARWARS "t112v127l12<dddg2>d2c<ba>g2d4c<ba>g2d4cc-c<a2d6dg2>d2c<ba>g2d4c<ba>g2d4cc-c<a2"
#define MAX_DIGITS 6
#ifdef DEBUG
#define DEBUG_PRINT(x) Serial.print (x)
#define DEBUG_PRINTLN(x) Serial.println (x)
// #define DEBUG_ESP true
// #define DEBUGSERIAL Serial
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTLN(x)
#endif
strDateTime timeNow;
int lastHour = 0;
unsigned long entrySubscriberLoop, entryNTPLoop, entryDispLoop;
struct subscriberStruc {
long last;
long actual;
long old[24];
} subscribers;
Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(8, 8, 6, 1, NEO_PIN,
NEO_TILE_TOP + NEO_TILE_LEFT + NEO_TILE_ROWS + NEO_TILE_PROGRESSIVE +
NEO_MATRIX_BOTTOM + NEO_MATRIX_RIGHT + NEO_MATRIX_ROWS + NEO_MATRIX_PROGRESSIVE,
NEO_GRB + NEO_KHZ800);
const uint16_t colors[] = {
matrix.Color(255, 0, 0), matrix.Color(0, 255, 0), matrix.Color(0, 0, 255), matrix.Color(255, 0 , 255)
};
MusicEngine music(BUZ_PIN);
WiFiClientSecure client;
YoutubeApi api(API_KEY, client);
SNTPtime NTPch("ch.pool.ntp.org");
// ================================================ helper functions =================================================
void beepUp() {
music.play("T80 L40 O4 CDEFGHAB>CDEFGHAB");
while (music.getIsPlaying() == 1) yield();
delay(500);
}
void beepDown() {
music.play("T1000 L40 O5 BAGFEDC<BAGFEDC<BAGFEDC");
while (music.getIsPlaying() == 1) yield();
delay(500);
}
void starwars() {
music.play(STARWARS);
while (music.getIsPlaying()) yield();
delay(500);
}
int measureLight() {
DEBUG_PRINT("Light measured: ");
DEBUG_PRINTLN(analogRead(A0));
int brightness = map(analogRead(A0), 200, 1024, 0, MAX_BRIGHTNESS);
brightness = (brightness > MAX_BRIGHTNESS) ? MAX_BRIGHTNESS : brightness; // clip value
brightness = (brightness < 5) ? 0 : brightness;
// brightness = MAX_BRIGHTNESS;
DEBUG_PRINT("Light value calculated: ");
DEBUG_PRINTLN(brightness);
return brightness;
}
void debugPrint() {
DEBUG_PRINTLN("---------Stats---------");
DEBUG_PRINT("Subscriber Count: ");
DEBUG_PRINTLN(subscribers.actual);
DEBUG_PRINT("Variance: ");
DEBUG_PRINTLN(subscribers.actual - subscribers.old[timeNow.hour]);
DEBUG_PRINT("LastSubs: ");
DEBUG_PRINTLN(subscribers.last);
DEBUG_PRINT("View Count: ");
DEBUG_PRINTLN(api.channelStats.viewCount);
DEBUG_PRINT("Comment Count: ");
DEBUG_PRINTLN(api.channelStats.commentCount);
DEBUG_PRINT("Video Count: ");
DEBUG_PRINTLN(api.channelStats.videoCount);
// Probably not needed :)
DEBUG_PRINT("hiddenSubscriberCount: ");
DEBUG_PRINTLN(subscribers.actual);
DEBUG_PRINTLN("------------------------");
}
void debugPrintSubs() {
for (int i = 0; i < 24; i++) {
DEBUG_PRINT(i);
DEBUG_PRINT(" old ");
DEBUG_PRINTLN(subscribers.old[i]);
}
}
void displayText(String tt) {
matrix.setTextWrap(false);
matrix.setBrightness(30);
matrix.fillScreen(0);
matrix.setTextColor(colors[0]);
matrix.setCursor(0, 0);
matrix.print(tt);
matrix.show();
}
void displayNeo(int subs, int variance ) {
// DEBUG_PRINTLN("Display");
matrix.fillScreen(0);
int bright = measureLight();
if (bright > -1) {
// calc to be added spaces
String res = String(subs);
for (int i = 1; res.length() < MAX_DIGITS; i++) {
res = " " + res;
}
matrix.setBrightness(bright);
matrix.setTextColor(colors[2]);
matrix.setCursor(0, 0);
matrix.print(res);
// Show arrow
// https://www.systutorials.com/ascii-table-and-ascii-code/
char arrow = 0x20; // space (equal sign was not working optically)
if (variance > 0) {
arrow = 0x1E;
matrix.setTextColor(colors[1]);
} else if (variance < 0) {
arrow = 0x1F;
matrix.setTextColor(colors[0]);
} else {
matrix.setTextColor(colors[2]);
}
matrix.setCursor(36, 0);
matrix.print(arrow);
// show variance bar
int h = map(variance, 0, 400, 0, 8);
h = (h > 8) ? 8 : h;
if (h > 0) matrix.fillRect(42, 8 - h, 1, h , colors[3]);
}
matrix.show();
}
void updateSubs() {
if (api.getChannelStatistics(CHANNEL_ID))
{
// get subscribers from YouTube
// DEBUG_PRINTLN("Get Subs");
subscribers.actual = api.channelStats.subscriberCount;
displayNeo(subscribers.actual, subscribers.actual - subscribers.old[timeNow.hour]);
DEBUG_PRINT("Subs ");
DEBUG_PRINT(subscribers.actual);
DEBUG_PRINT(" yesterday ");
DEBUG_PRINTLN(subscribers.old[timeNow.hour]);
if (subscribers.last > 0) {
if (subscribers.actual > subscribers.last ) {
beepUp();
if (subscribers.actual % 10 <= subscribers.last % 10) for (int ii = 0; ii < 1; ii++) beepUp();
if (subscribers.actual % 100 <= subscribers.last % 100) starwars();
if (subscribers.actual % 1000 <= subscribers.last % 1000) for (int ii = 0; ii < 2; ii++) starwars();
}
else {
if (subscribers.actual < subscribers.last ) beepDown();
}
}
subscribers.last = subscribers.actual;
debugPrint();
}
}
bool wifiConnect() {
int retryCounter = CONNECT_TIMEOUT * 10;
// WiFi.forceSleepWake();
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
// wifi_station_connect();
DEBUG_PRINT("(Re)connecting to Wifi: ");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
// WiFi.printDiag(Serial);
// make sure to wait for wifi connection
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
retryCounter--;
if (retryCounter <= 0) {
DEBUG_PRINT(" Timeout reached! Wifi Status: ");
DEBUG_PRINTLN(WiFi.status());
return false;
}
delay(100);
DEBUG_PRINT(".");
}
DEBUG_PRINT(" Connected with IP address ");
DEBUG_PRINTLN(WiFi.localIP());
client.setInsecure();
return true;
}
// ================================================ SETUP ================================================
void setup() {
#ifdef DEBUG
Serial.begin(SERIAL_BAUD); // initialize serial connection
DEBUG_PRINTLN("Starting up");
// delay for the serial monitor to start
delay(3000);
#endif
pinMode(POWER_PIN, INPUT);
DEBUG_PRINTLN("Initializing display");
matrix.begin();
pinMode(POWER_PIN, OUTPUT);
digitalWrite(POWER_PIN, LOW);
matrix.show();
displayText("YouTube");
pinMode(A0, INPUT);
wifiConnect();
DEBUG_PRINTLN("Getting NTP time");
while (!NTPch.setSNTPtime()) DEBUG_PRINT("."); // set internal clock
entryNTPLoop = millis() + NTP_LOOP_INTERVAL;
entrySubscriberLoop = millis() + SUBSCRIBER_INTERVAL;
beepUp();
beepUp();
DEBUG_PRINTLN("Getting initial YoutToube subscribers");
Serial.setDebugOutput(true);
while (subscribers.actual == 0) {
DEBUG_PRINT(" Subscribers before: ");
DEBUG_PRINTLN(subscribers.actual);
if (api.getChannelStatistics(CHANNEL_ID)) {
subscribers.actual = api.channelStats.subscriberCount;
DEBUG_PRINT(" Subscribers after: ");
DEBUG_PRINTLN(subscribers.actual);
} else {
DEBUG_PRINTLN("Unable to get stats");
}
}
DEBUG_PRINTLN("a");
for (int i = 0; i < 24; i++) {
if (subscribers.old[i] == 0) subscribers.old[i] = subscribers.actual - 245;
}
DEBUG_PRINTLN("b");
debugPrintSubs();
DEBUG_PRINTLN("Setup done");
}
// ================================================ LOOP =================================================
void loop() {
//-------- Your Sketch starts from here ---------------
if (millis() - entryDispLoop > DISP_LOOP_INTERVAL) {
entryDispLoop = millis();
displayNeo(subscribers.actual, subscribers.actual - subscribers.old[timeNow.hour]);
}
if (millis() - entryNTPLoop > NTP_LOOP_INTERVAL) {
// Check if the wifi is connected
// wifiConnect();
// DEBUG_PRINTLN("NTP Loop");
entryNTPLoop = millis();
timeNow = NTPch.getTime(1.0, 1); // get time from internal clock
NTPch.printDateTime(timeNow);
if (timeNow.hour != lastHour ) {
DEBUG_PRINTLN("New hour!!!");
subscribers.old[lastHour] = subscribers.actual;
subscribers.last = subscribers.actual;
debugPrintSubs();
lastHour = timeNow.hour;
}
}
if (millis() - entrySubscriberLoop > SUBSCRIBER_INTERVAL) {
// Check if the wifi is connected
// wifiConnect();
// DEBUG_PRINTLN("Subscriber Loop");
entrySubscriberLoop = millis();
updateSubs();
}
delay(1000);
DEBUG_PRINT(".");
}
<file_sep>/README.md
# Youtube-Subscriber-Counter
Youtube Subscriber Counter for ESP8266
YoutubeCounterNeopixelV1.0 is for Neopixel display. Video: https://youtu.be/IIl5nDjfkjY
YouTubeCounterV1 is IOTappStory compliant.
ModeButton is D4 for Wemos boards. Change to D3 if you use NodeMCU boards
Add your channel ID and your google API key
<file_sep>/YoutubeCounterIOTappStoryV1.0/YoutubeCounterIOTappStoryV1.0.ino
/* This is an initial sketch to be used as a "blueprint" to create apps which can be used with IOTappstory.com infrastructure
Your code can be filled wherever it is marked.
Copyright (c) [2016] [<NAME>]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#define SERIALDEBUG // Serial is used to present debugging messages
//#define DISPLAY
#include <YoutubeApi.h>
#include <SPI.h>
#include <MAX7219_Dot_Matrix.h>
#include <MusicEngine.h>
#include <SNTPtime.h>
#include <credentials.h>
#define SKETCH "YoutubeCounter "
#define VERSION "V1.6"
#define COMPDATE __DATE__ __TIME__
// ================================================ PIN DEFINITIONS ======================================
#ifdef ARDUINO_ESP8266_ESP01 // Generic ESP's
#define MODEBUTTON 0
#define BUZ_PIN 5
#define CS_PIN 2
#define LEDgreen 13
//#define LEDred 12
#else
#define MODEBUTTON D3
#define BUZ_PIN D1
#define CS_PIN D4
#define LEDgreen D7
//#define LEDred D6
#endif
#define NUMBER_OF_DIGITS 5
#define STARWARS "t112v127l12<dddg2>d2c<ba>g2d4c<ba>g2d4cc-c<a2d6dg2>d2c<ba>g2d4c<ba>g2d4cc-c<a2"
int rawIntensity, intensity;
long lastSubscribers, subscribers;
unsigned long entrySubscriberLoop;
strDateTime dateTime;
int nextRound = 0;
#include <IOTAppStory.h>
IOTAppStory IAS(SKETCH, VERSION, COMPDATE, MODEBUTTON);
MAX7219_Dot_Matrix myDisplay (NUMBER_OF_DIGITS, CS_PIN); // # digits, and then specify the CS pin
MusicEngine music(BUZ_PIN);
WiFiClientSecure client;
YoutubeApi api(API_KEY, client);
SNTPtime NTPch("ch.pool.ntp.org");
// ================================================ SETUP ================================================
void setup() {
IAS.serialdebug(true);
Serial.println("Start");
myDisplay.begin();
myDisplay.setIntensity (15);
IAS.preSetBoardname("YouTube");
IAS.preSetAutoUpdate(false); // automaticUpdate (true, false)
IAS.preSetAutoConfig(true); // automaticConfig (true, false)
IAS.preSetWifi(mySSID, myPASSWORD);
IAS.onModeButtonShortPress([]() {
Serial.println(" If mode button is released, I will enter in firmware update mode.");
Serial.println("*------------------------------------------------------------------------ -*");
dispMatrix("UPD");
});
IAS.onModeButtonLongPress([]() {
Serial.println(" If mode button is released, I will enter in configuration mode.");
Serial.println("*------------------------------------------------------------------------ -*");
dispMatrix("UPD");
});
IAS.onModeButtonVeryLongPress([]() {
Serial.println(" If mode button is released, I won't do anything.");
Serial.println("*-------------------------------------------------------------------------*");
dispMatrix("UPD");
});
IAS.begin(true, 'P');
dispMatrix(VERSION);
pinMode(A0, INPUT);
while (!NTPch.setSNTPtime()) Serial.print("."); // set internal clock
Serial.println("Setup done");
delay(3000);
}
// ================================================ LOOP =================================================
void loop() {
yield();
IAS.buttonLoop(); // this routine handles the reaction of the Flash button. If short press: update of skethc, long press: Configuration
//-------- Your Sketch starts from here ---------------
myDisplay.setIntensity (adjustIntensity());
if (millis() - entrySubscriberLoop > nextRound) {
entrySubscriberLoop = millis();
if (api.getChannelStatistics(CHANNEL_ID))
{
// get subscribers from YouTube
subscribers = api.channelStats.subscriberCount;
dispString(String(subscribers));
if ((subscribers > lastSubscribers) && (lastSubscribers > 0) ) {
beepUp();
if (subscribers % 10 <= lastSubscribers % 10) for (int ii = 0; ii < 1; ii++) beepUp();
if (subscribers % 100 <= lastSubscribers % 100) starwars();
if (subscribers % 1000 <= lastSubscribers % 1000) for (int ii = 0; ii < 3; ii++) starwars();
} else if (subscribers < lastSubscribers) beepDown();
lastSubscribers = subscribers;
Serial.println("---------Stats---------");
Serial.print("Subscriber Count: ");
Serial.println(api.channelStats.subscriberCount);
Serial.print("View Count: ");
Serial.println(api.channelStats.viewCount);
Serial.print("Comment Count: ");
Serial.println(api.channelStats.commentCount);
Serial.print("Video Count: ");
Serial.println(api.channelStats.videoCount);
// Probably not needed :)
Serial.print("hiddenSubscriberCount: ");
Serial.println(subscribers);
Serial.println("------------------------");
nextRound = 10000;
}
}
}
void dispMatrix(String content) {
#ifdef DISPLAY
Serial.println("dispMatrix");
char charBuf[50];
content.toCharArray(charBuf, 50);
myDisplay.sendString(charBuf);
#endif
}
void beepUp() {
music.play("T80 L40 O4 CDEFGHAB>CDEFGHAB");
while (music.getIsPlaying() == 1) yield();
delay(500);
}
void beepDown() {
music.play("T1000 L40 O5 BAGFEDC<BAGFEDC<BAGFEDC");
while (music.getIsPlaying() == 1) yield();
delay(500);
}
void starwars() {
music.play(STARWARS);
while (music.getIsPlaying()) yield();
delay(500);
}
int adjustIntensity() {
rawIntensity = analogRead(A0);
float _intensity = 15 - (15.0 / (560.0 - 0) * rawIntensity);
int intensity = (_intensity > 15.0) ? 15 : (int)_intensity;
intensity = (_intensity < 2.0) ? 0 : (int)_intensity;
return intensity;
}
void dispString(String dispContent) {
int intensity = adjustIntensity();
// display
if (dispContent.length() < 5) dispContent = " " + dispContent;
if (intensity == 0) dispContent = " ";
else myDisplay.setIntensity (intensity);
dispMatrix(dispContent);
}
void dispTime() {
dateTime = NTPch.getTime(1.0, 1); // get time from internal clock
NTPch.printDateTime(dateTime);
byte actualHour = dateTime.hour;
byte actualMinute = dateTime.minute;
String strMin = String(actualMinute);
if (strMin.length() < 2) strMin = "0" + strMin;
dispString(String(actualHour) + ":" + strMin);
}
<file_sep>/YouTubeCounterDeepSleepV3/YouTubeCounterDeepSleepV3.ino
#include <credentials.h>
#define DEBUG 1
#include <DebugUtils.h>
#include <ESP8266WiFi.h>
#include <EEPROM.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266httpUpdate.h>
#include <SPI.h>
#include <MAX7219_Dot_Matrix.h>
#define FIRMWARE "SubscriberCounterV3"
#define FIRMWARE_VERSION FIRMWARE"_000"
extern "C" {
#include "user_interface.h" // this is for the RTC memory read/write functions
}
#define BUZZER 5
#define NUMBER_OF_DEVICES 5
#define CS_PIN 2
typedef struct {
byte markerFlag;
long lastSubscribers;
int updateSpaces;
int runSpaces;
} rtcMemDef __attribute__((aligned(4)));
rtcMemDef rtcMem;
MAX7219_Dot_Matrix myDisplay (NUMBER_OF_DEVICES, CS_PIN); // 8 chips, and then specify the LOAD pin only
// declare telnet server
WiFiServer TelnetServer(23);
WiFiClient Telnet;
long subscribers, lastSubscribers;
WiFiClient client;
#include "ESP_Helpers.h"
int getSubscribers() {
const char* host = "api.thingspeak.com";
int subscribers = 0;
// Establish connection to host
Serial.printf("\n[Connecting to %s ... ", host);
if (client.connect(host, 80))
{
Serial.println("connected]");
// send GET request to host
String url = "/apps/thinghttp/send_request?api_key=<KEY>";
DEBUGPRINTLN1("[Sending a request]");
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
DEBUGPRINTLN1("[Response:]");
while (client.connected())
{
if (client.available())
{
String line = client.readStringUntil('\n');
int hi = line.indexOf("subscribers");
if (hi > 0) {
String tt = line.substring(hi - 6, hi - 1);
tt.replace(",", "");
subscribers = tt.toInt();
DEBUGPRINTLN1(subscribers);
}
}
}
client.stop();
DEBUGPRINTLN1("\n[Disconnected]");
}
else
{
DEBUGPRINTLN1("connection failed!]");
client.stop();
}
return subscribers;
}
void beep(int beepDuration) {
digitalWrite(BUZZER, HIGH);
delay(beepDuration);
digitalWrite(BUZZER, LOW);
delay(500);
}
void dispMatrix(String content) {
char charBuf[50];
content.toCharArray(charBuf, 50);
myDisplay.sendString(charBuf);
}
void display(long num) {
int hi = analogRead(A0);
float _intensity = 15 - (15.0 / (560.0 - 0) * hi);
int intensity = (_intensity > 15.0) ? 15 : (int)_intensity;
intensity = (_intensity < 2.0) ? 0 : (int)_intensity;
// DEBUGPRINT1("Intensity ");
// DEBUGPRINTLN1(intensity);
// for (int i=0;i<intensity;i++) beep(100);
myDisplay.setIntensity (intensity);
// display
String dispContent = String(num);
if (dispContent.length() < 5) dispContent = " " + dispContent;
DEBUGPRINT1(" dispContent ");
DEBUGPRINTLN1(dispContent);
dispMatrix(dispContent);
}
void setup() {
int wiTry = 0;
Serial.begin(115200);
Serial.println("");
DEBUGPRINTLN1("Start");
pinMode(A0, INPUT);
pinMode(BUZZER, OUTPUT);
digitalWrite(BUZZER, LOW);
readRTCmem();
myDisplay.begin ();
display(rtcMem.lastSubscribers);
if (rtcMem.runSpaces >= RUNINTERVAL) {
readCredentials();
WiFi.mode(WIFI_STA);
WiFi.begin(mySSID, myPASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
DEBUGPRINT1(".");
if (wiTry >= 30) {
ESP.reset();
} else {
wiTry++;
}
}
if (iotUpdater(UPDATE_SERVER, UPDATE_URL, FIRMWARE_VERSION, false, true) == 0) {
iotUpdater(SECOND_UPDATE_SERVER, SECOND_UPDATE_URL, FIRMWARE_VERSION, true, true);
}
TelnetServer.begin();
TelnetServer.setNoDelay(true);
subscribers = getSubscribers();
if (subscribers < rtcMem.lastSubscribers) subscribers = rtcMem.lastSubscribers;
// subscribers = rtcMem.lastSubscribers + 1;
DEBUGPRINT1("-----");
DEBUGPRINT1(rtcMem.lastSubscribers);
DEBUGPRINT1(" ");
DEBUGPRINTLN1(subscribers);
if (subscribers > rtcMem.lastSubscribers) {
beep(90);
if (subscribers % 10 == 0) for (int ii = 0; ii < 1; ii++) beep(90);
if (subscribers % 100 == 0) for (int ii = 0; ii < 3; ii++) beep(90);
if (subscribers % 1000 == 0) for (int ii = 0; ii < 5; ii++) beep(90);
if (subscribers == 10000) for (int ii = 0; ii < 100; ii++) beep(90);
}
display(subscribers);
rtcMem.lastSubscribers = subscribers;
rtcMem.runSpaces = 0;
} else {
rtcMem.runSpaces = ++rtcMem.runSpaces;
writeRTCmem();
}
writeRTCmem();
ESP.deepSleep(3000000);
}
void loop() {
handleTelnet();
int hi = analogRead(A0);
float _intensity = 15 - (15.0 / (560.0 - 20) * hi);
int intensity = (_intensity > 15.0) ? 15 : (int)_intensity;
intensity = (_intensity < 1.0) ? 1 : (int)_intensity;
DEBUGPRINT1("A0: " );
DEBUGPRINT1(hi );
DEBUGPRINT1(" Intensity ");
DEBUGPRINTLN1(intensity);
Telnet.print("A0: " );
Telnet.print(hi );
Telnet.print(" Intensity ");
Telnet.println(intensity);
delay(100);;
}
| 781765dc70a1320123d44a9c4705424dcc3475c9 | [
"Markdown",
"C",
"C++",
"INI"
]
| 6 | C | oxivanisher/Youtube-Subscriber-Counter | 9e40661ccd4678bda34f2dea17a7372325c92be8 | b5d56465b97626cfbaea41400e9291837489708c |
refs/heads/master | <repo_name>JemrickD-01/software-engineering-project<file_sep>/Initial Launch test/previous folders/transfer.php
<?php
$uname = $_POST['username'];
$password = $_POST['password'];
echo 'TEST: '.$uname;
echo 'PAS: '.$password;
function message($msg, $link){
echo'<script> alert("Hi")</script>';
echo "<script> document.location='open.php'</script>";
}
message("f","f");
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '<EMAIL>')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?><file_sep>/Initial Launch test/previous folders/validate.php
<?php
$name = $_POST['postname'];
$age = $_POST['postage'];
echo "TEST".$age;
echo "TEST 01".$name;
?><file_sep>/CRUD/insertDetails.php
<?php
include("condb.php");
$name = $_POST['name'];
$organization = $_POST['organization'];
$email = $_POST['email'];
$password= $_POST['<PASSWORD>'];
$sql = "insert into tbl_login values('$name','$password' )";
if (mysqli_query($conn, $sql)) {
echo '<script> alert("New Record") </script>';
echo "New record created successfully";
header("Location: index.php");
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// bukas promise gagawin ko na 'to
mysqli_close($conn);
?><file_sep>/CRUD/testisset.php
<?php
if (isset($_POST["name"])){
echo "Heelllo";
}
?><file_sep>/Initial Launch test/insert-data-camera/insert.php
<?php
include('condb.php');
$event_id =$_POST['post_Content'];
$sql = "INSERT INTO tbl_login VALUES ('$event_id', '123')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?><file_sep>/README.md
# SOFTWARE ENGINEERING PROJECT
# TITLE: WEB BASED APPLICATION WORK IMMERSION PORTAL
pogi test commit
<file_sep>/Initial Launch test/propostal title/eventregistration.md
# EVENT MANAGEMENT SYSTEM WITH QR ATTENDANCE AND AUTOMATED CERTIFICATES
## Dedication:
This application and other information are dedicated to the Computer Society of City College of Angeles. This application aims to help the management system of the computer society using this web application
## Further dedication:
this can be also used by the other event organizer if they seem that this system can be fitted in the way how they manage their events
## Problems:
Seminar has been the best learning area or event to join with and you’ll learn a lot from them from this type of gathering on the other hand the management has this difficulty to handle some situations such as who attended the event, where to contact them and how to create certificate automatically. It is also the problem on how to contact them from time to time, such as what are those announcement that they have.
## Solution:
Create a web application that help the organizer to create a fast transaction, automated certificate generator, and fast attendance system for them to organize everything. Such as managing the certificates, the attendance and announcement
# FEATURES OF THE APPLICATION
1. Create another admin
2. Set password for them
## **EVENT SETUP**
1. Create event
2. The event has the details such as Event Name, location , date, paid or free, guest speaker, description
3. It has also a features of some announcement message for those who will join the event (such as cancellation of the event, move date of the event, location of the event )
4. CRUD for attendees
## EVENT ATTENDANCE
1. Can send generated QR codes the details of the QR-Code is the ID number of the attendees due to the privacy of who can scan the QR code
2. Scan QR Code then automatically update to the database
## CERTIFICATES:
1. The event organizer can print to those who attended the event
2. Either they will print it or digitally send the certificates to them
## REGISTRATION
:
1. They can go to the website and choose what event they want to join
2. After they choose what event they want to join they can register themselves
3. The details are Name, Contact number, Email Address, Organization/Section , Onsite payment or Online payment
4. The attendee will receive some notification to their email if there are changes and if the event is coming
## LIMITATION:
1. It has no authentication connection to the useful application or accounts such as facebook and google
2. The admin site is only efficiently working for the latest web browser
3. The registration site can be browse using mobile application but it is only working the 2016 version and above of some browser due to the modules that been use
4. Certificate cannot customize the design , but the design is in general form theme color of the computer Society CCA
## Technologies to be used for this application:
1. HTML 5 +CSS3 for front end
2. PHP for backend server
3. Vanilla JavaScript
4. Bootstrap framework for web responsive design
5. VueJS for the camera activation
6. Instascan Library JS for QR Scanner
7. JQuery Library for data sending
| 57005f99b3f6e5128311e7477d816749be90d555 | [
"Markdown",
"PHP"
]
| 7 | PHP | JemrickD-01/software-engineering-project | 1b7fad6a459c38901ea76fb0b5ced82734e4f337 | d2bd9fd3189f3ddf1520c6ed3ec71ec3d31ef7e5 |
refs/heads/main | <repo_name>Sehee99/R-Study<file_sep>/R 기초 프로그래밍/chapter03 데이터구조.R
## 1. 벡터(Vector)
# 하나 이상의 데이터를 저장할 수 있는 1차원 저장 구조(1차원 배열)
students_age <- c(11, 12, 13, 20, 15, 21)
students_age
class(students_age)
length(students_age) # 벡터의 길이 확인하기기
# 벡터 인덱싱(R의 인덱스는 1부터 시작)
students_age[1] # 1번 인덱스의 데이터 추출하기
students_age[3] # 3번 인덱스의 데이터 추출하기
students_age[-1] # 1번 인덱스의 데이터만 제외하고 추출하기기
# 벡터 슬라이싱
students_age[1:3] # 1번부터 3번 인덱스까지의 데이터 추출하기
students_age[4:6] # 4번부터 6번 인덱스까지의 데이터 추출하기
# 벡터에 데이터 추가, 갱신
score <- c(1,2,3)
score[1] <- 10
score[4] <- 4
score
# 벡터의 데이터 타입
# 벡터는 하나의 원시 데이터 타입으로 저장되므로, 다양한 데이터 타입을 섞어 저장하면 하나의 타입으로 자동 형변환
code <- c(1,12,"30") # 문자(character) 데이터 타입으로 모두 변경됨
class(code) # 데이터 타입 확인인
code
# 순열 생성
data <- c(1:10) # 1부터 10까지 1씩 증가시켜 생성하기
data
data1 <- seq(1,10) # 1부터 10까지 1씩 증가시켜 생성하기
data1
data2 <- seq(1, 10, by=2) # 1부터 10까지 2씩 증가시켜 생성하기
data2
data3 <- rep(1, times=5) #1을 다섯 번 반복 생성하기
data3
data4 <- rep(1:3, each=3) #1부터 3을 각각 세 번씩 반복 생성하기
data4
data5 <- rep(1:3, times=3)
data5
## 2. 행렬(Matrix)
# 표 형태와 같은 2차원 데이터 저장 구조
# 벡터와 마찬가지로 모두 같은 데이터 타입이어야 함
var1 <- c(1, 2, 3, 4, 5, 6)
# var1을 이용해서 2행 3열 행렬을 생성. 기본적으로 열 우선으로 값이 채워짐
x1 <- matrix(var1, nrow=2, ncol=3)
x1
# var1을 이용해서 2열 행렬을 생성. 행의 개수는 자동 계산됨
x2 <- matrix(var1, ncol=2)
x2
# 일부 데이터만 접근
x1[1,] # x1의 1행, 모든 열
x1[,1] # x1의 모든 행, 1열
x1[2,2] #x1의 2행, 2열
# 행렬에 데이터 추가
x1
x1 <- rbind(x1, c(10, 10, 10)) # 행 추가
x1 <- cbind(x1, c(20, 20, 20)) # 열 추가
x1
## 3. 데이터프레임(Dataframe)
# 행과 열을 가진 2차원 저장 구조
# 벡터, 매트릭스와 달리 각 열이 서로 다른 데이터 타입을 가질 수 있음음
no <- c(10,20,30,40,50,60,70)
age <- c(18,15,13,12,10,9,7)
gender <- c("M", "M", "M", "M", "M", "F", "M")
# 데이터프레임 생성 예
students <- data.frame(no, age, gender)
students
# 열의 이름과 행의 이름 확인
colnames(students) # 열 이름 확인
rownames(students) # 행 이름 확인
colnames(students) <- c("no", "나이", "성별") # 열 이름 수정
rownames(students) <- c('A', 'B', 'C', 'D', 'E', 'F', 'G') # 행 이름 수정
students
# 다시 원래의 영문 열 이름으로 수정하자
colnames(students) <- c("no", "age", "gender")
students
# 일부 데이터만 접근
# 열 이름으로 특정 열에 접근하는 예
# 데이터프레임의 변수이름$열이름으로 특정 열에 접근하기
students$no
students$age
# 대괄호 안에 열이름으로 특정 열에 접근하기
# 대괄호 안에 콤마(,)를 쓴 후 열이름을 쓴다. 열이름은 " " 또는 ' '로 감쌈
students[,"no"]
students[,"age"]
# 열 인덱스로 특정 열에 접근하는 예
students[,1] # 첫번째 열 데이터가 모두 출력됨
students[,2] # 두번째 열 데이터가 모두 출력됨
# 행 이름으로 특정 행만 접근하는 예
students["A", ] # A행 데이터가 출력된다. 행이름은 " " 또는 ' '로 감쌈
# 행 이름 뒤에 콤마(,)를 반드시 써야함
# 행 인덱스로 특정 행만 접근하는 예
students[2,] # 두번째 행 데이터가 출력
# 행 인덱스 뒤에 콤마(,)를 반드시 써야함
# 행 인덱스, 열 인덱스 또는 행 이름, 열 이름으로 데이터에 접근
students[3,1] # 변수이름[행인덱스, 열인덱스]로 작성
students["A", "no"] # 변수이름["행이름", "열이름"]으로 작성
# 열 데이터 추가
students$name <- c("이용", "준희", "이훈", "서희", "승희", "하정", "하준") # 열 추가
# 행 데이터 추가가
students["H",] <- c(80,10,'M','홍길동') # 헹 추가
tail(students)
## 4. 배열(array)
# 배열은 다차원 데이터 저장 구조
# 벡터나 매트릭스처럼 하나의 원시 데이터 타입으로 저장
var1 <- c(1,2,3,4,5,6,7,8,9,10,11,12) # 벡터 생성하기
arr1 <- array(var1, dim=c(2,2,3)) # var1 벡터를 이용하여 3차원 배열 생성
arr1
arr1 <- array(var1, dim=c(2,2,3,1))
arr1
## 5. 리스트(List)
# 리스트는 다차원 데이터 저장 구조
# 배열과 달리 키와 값 쌍으로 저장할 수 있고, 값에 해당하는 데이터가 어떠한 데이터 구조도 가능
v_data <- c("02-111-2222", "01022223333") # 벡터
m_data <- matrix(c(21:26), nrow=2) # 행렬
a_data <- array(c(31:36), dim=c(2,2,2)) # 배열
d_data <- data.frame(address = c("seoul", "busan"), # 데이터프레임
name = c("Lee", "Kim"), stringsAsFactors = F)
# list(키1=값, 키2=값, ...,)와 같이 키와 값 쌍으로 리스트 생성
list_data <- list(name="홍길동",
tel=v_data,
score1=m_data
score2=a_data
friends=d_data)
# 리스트이름$키
list_data$name # list_data에서 name키와 쌍을 이루는 데이터
list_data$tel # list_data에서 tel키와 쌍을 이루는 데이터
# 리스트이름[숫자]
list_data[1] # list_data에서 첫 번째 서브 리스트
<file_sep>/데이터 분석/5. 다중선형회귀.R
# 4. 다중선형회귀
# [실습1] 다중선형회귀|모델 생성
height_father <- c(180, 172, 150, 180, 177, 160, 170, 165, 179, 159) # 아버지 키
height_mother <- c(160, 164, 166, 188, 160, 160, 171, 158, 169, 159) # 어머니 키
height_son <- c(180, 173, 163, 184, 165, 165, 175, 168, 179, 160) # 아들 키
height <- data.frame(height_father, height_mother, height_son)
head(height)
model <- lm(height_son ~ height_father + height_mother, data = height)
model
# 회귀계수
coef(model)
# [실습2] 다중선형회귀|잔차
# 잔차
r <- residuals(model)
r[0:4]
# 잔차 제곱합
deviance(model)
# [실습3] 다중선형회귀|예측
# 예측 (점 추정)
predict.lm(model, newdata = data.frame(height_father = 170, height_mother = 160))
# 예측 (구간 추정)
predict.lm(model, newdata = data.frame(height_father = 170, height_mother = 160), interval = "confidence")
# [실습4] 다중선형회귀|결정계수와 수정된 결정계수
summary(model)
# [실습5] 다중선형회귀|설명변수 선택
model <- lm(mpg ~ ., data = mtcars)
# mpg ~ . 는 종속변수가 mpg이며 그 외 모든 변수가 설명변수임을 의미하는 포뮬러(formula)
new_model <- step(model, direction = "both")
# 위처럼 현재 모델의 AIC를 구하고, 각 변수를 추가 또는 삭제했을 때 AIC를 구한 후,
# AIC가 가장 작아질 수 있는 변수를 추가하거나 제거하는 과정을 반복하여
# 최적의 설명변수를 추출한다.
### mtcars 데이터프레임의 변수 설명
# mpg: 자동차 연비
# wt: 자동차 중량
# qsec: 1/4 mile time
# am: 변속기 (0 = 자동, 1 = 수동)
# [실습6] 선형회귀|모델 진단 그래프
model <- lm(mpg ~ wt + qsec + am, data = mtcars)
plot(model)
<file_sep>/데이터 분석/1. 데이터 조작 및 EDA.R
### 1 데이터 대표값 탐색
## 1.1 평균과 중앙값
# 평균
A_salary <- c(25, 28, 50, 60, 30, 35, 40, 70, 40, 70, 40, 100, 30, 30) # 백만원 단위
B_salary <- c(20, 40, 25, 25, 35, 25, 20, 10, 55, 65, 100, 100, 150, 300)
mean(A_salary)
mean(B_salary)
# 결측값(NA)이 있는 경우 결측값을 제거하고 평균을 구할 때는 na.rm = T 인자를 사용
mean(A_salary, na.rm = T)
# 중앙값
median(A_salary)
median(B_salary)
# 결측값(NA)이 있는 경우 결측값을 제거하고 중앙값을 구할 때는 na.rm = T 인자를 사용
median(A_salary, na.rm = T)
## 1.2 절사평균
mean(A_salary, trim = 0.1) # 양끝 10%씩 값을 제외하고 평균을 구함함
mean(B_salary, trim = 0.1)
### 2 데이터 분산도 탐색
## 2.1 최소값, 최대값으로 범위 탐색
# 범위: range()
range(A_salary)
range(B_salary)
# 최소값: min(), 최대값: max()
min(A_salary)
max(A_salary)
min(B_salary)
max(B_salary)
## 2.2 분산과 표준편차
# 분산
var(A_salary)
var(B_salary)
# 표준편차
sd(A_salary)
sd(B_salary)
### 3 데이터 분포 탐색
## 3.1 백분위수와 사분위수
# 90% 백분위수
quantile(A_salary, 0.9)
quantile(B_salary, 0.9)
# 사분위수
quantile(A_salary)
quantile(B_salary)
## 3.2 상자그림
boxplot(A_salary, B_salary, names = c("A회사 salary", "B회사 salary"))
## 3.3 히스토그램
hist(A_salary, xlab = "A사 salary", ylab = "인원수, break =5")
hist(B_salary, xlab = "B사 salary", ylab = "인원수, break =5")
## 3.4 도수분포표
# 수치 데이터 -> 도수분포표 생성시 cut() 함수
cut_value <- cut(A_salary, breaks = 5)
freq <- table(cut_value)
freq
# 범주형 데이터 -> table() 함수로 도수분포표 생성
A_gender <- as.factor(c('남', '남', '남', '남', '남', '남', '남', '남', '남', '여', '여', '여', '여', '여'))
B_gender <- as.factor(c('남', '남', '남', '남', '여', '여', '여', '여', '여', '여', '여', '남', '여', '여'))
A <- data.frame(gender <- A_gender, salary <- A_salary)
B <- data.frame(gender <- B_gender, salary <- B_gender)
freqA <- table(A$gender)
freqA
freqB <- table(B$gender)
freqB
# 상대적 빈도표
# A사의 남녀 도수분포표를 구해 저장한 freqA를 이용
prop.table(freqA)
# B사의 남녀 도수분포표를 구해 저장한 freqB를 이용
prop.table(freqB)
## 3.5 막대 그래프
# A사의 남녀 도수분포표를 구해 저장한 freqA를 이용
barplot(freqA, names = c("남", "여"), col = c("skyblue", "pink"), ylim = c(0, 10))
title(main = "A사")
# B사의 남녀 도수분포표를 구해 저장한 freqB를 이용
barplot(freqB, names = c("남", "여"), col = c("skyblue", "pink"), ylim = c(0, 10))
title(main = "B사")
## 3.6 파이 그래프
pie(x = freqA, col = c("skyblue", "pink"), main = "A사")
pie(x = freqB, col = c("skyblue", "pink"), main = "B사")
### 4 변수 간 관계 탐색
## 4.1 산점도 그래프
A_salary <- c(25, 28, 50, 60, 30, 35, 40, 70, 40, 70, 40, 100, 30, 30) # 연봉 변수
A_hireyears <- c(1, 1, 5, 6, 3, 3, 4, 7, 4, 7, 4, 10, 3, 3) # 근무년차 변수
A <- data.frame(salary <- A_salary, hireyears <- A_hireyears)
# 산점도 그래프
plot(A$hireyears, A$salary, xlab = "근무년수", ylab = "연봉(백만원단위)")
# pairs() 함수: 여러가지 변수의 산점도 그래프를 한눈에 볼 수 있도록 작성
pairs(iris[, 1:4], main = "iris data")
## 4.2 상관계수
cor(A$hireyears, A$salary)
## 4.3 상관행렬
cor(iris[, 1:4])
## 4.4 상관행렬 히트맵
heatmap(cor(iris[, 1:4]))
<file_sep>/R 기초 프로그래밍/chapter04 R 기초 프로그래밍.R
## 1. 연산
# 수치 연산자
10+2; 10-2; 10*2; 10/2 # 사칙연산산
10 %% 3 # 10을 3으로 나눈 나머지. 결과는 1
10 %/%3 # 10을 3으로 나눈 몫. 결과는 3
2^3 # 자승
# 논리 연산자
10 <= 10
10 > 5
10 >= 5
n <- 20
n %in% (c(10,20,30)) # 연산자 뒤 나열한 값들 중 하나와 일치하면 참
n <- 10
n >=0 & n <= 100 # AND 연산자: 양쪽 모두 참이면 참
n <- 1000
n >= 0 | n <=100 # OR 연산자: 둘 중 하나만 참이면 참
!(10==5) # NOT 연산자: 참이면 거짓, 거짓이면 참
# 벡터와 스칼라 연산
score <- c(10, 20)
score + 2 # score 벡터의 모든 데이터에 각각 2를 더하여 반환
score # score 벡터 자체는 변경되지 않아서 이전 값을 가지고 있음
# 연산 결과를 score 변수에 반영하려면 다음과 같이 score에 연산 결과 저장
score <- score + 2 # score 벡터의 모든 데이터에 각각2를 더하고,
# 연산 결과를 score에 저장
score # score 가 변경된 것을 확인할 수 있음
# 벡터와 벡터와의 연산
score1 <- c(100,200)
score2 <- c(90,91)
sum_score <- score1 + score2 # 벡터와 벡터의 더하기 연산
sum_score # 100+90 200+91
diff <- score1 - score2
diff
score1 <- c(100,200,300,400)
score2 <- c(90,91)
sum_score <- score1 + score2 # 벡터와 벡터의 더하기 연산
sum_score # 100+90 200+91 300+90 400+91
score1 <- c(100,200,300,400, 500)
score2 <- c(90,91)
sum_score <- score1 + score2 # 벡터와 벡터의 더하기 연산
sum_score # 100+90 200+91 300+90 400+91 500+90
# 행렬과 스칼라와의 연산
m1 <- matrix(c(1,2,3,4,5,6), nrow = 2)
m1
m1 <- m1 * 10 # 행렬과 스칼라 곱하기 연산
m1
# 행렬과 행렬과의 연산
m1 <- matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3)
m2 <- matrix(c(2,2,2,2,2,2,2,2,2), nrow = 3)
m1
m2
m1 + m2 # 행렬과 행렬 간 더하기(+) 연산
## 2. 흐름제어문
## 2-1. 조건문
# if 문
score <- 76
if ( score >= 80 ) { # 조건이 TRUE이므로 아래 문장들이 실행
print("조건이 TRUE인 경우만 수행할 문장")
}
score <- 86
# if ~ else 문
if(score >= 91) { # 이 조건의 결과는 FALSE
print("A") # 조건이 TRUE일 때 수행할 문장
} else {
print("B or C or D") # 조건이 FALSE일 때 수행할 문장
}
# if ~ else if 문
score <- 86
if ( score >= 91 ) { print("A")
} else if ( score >= 81 ) { print(" B ") # score는 86이므로 이 조건이 TRUE } else if ( score = 71 ) { print(" C ")
} else if ( score >= 61 ) { print(" D ")
} else { print (" F ") }
# ifelse() 함수
# if ~ else 문장과 동일한 기능
score <- 85
ifelse(score>=91, "A", "FALSE 일 때 수행")
score <- 85
ifelse(score>=91, "A", ifelse(score>=81, "B", "C or D ") )
## 2-2. 반복문
# for 문
# 다음 for문은 첫 수행 시 num에 1이 저장된다, 그 다음 1씩 증가된 값이 저장
# num이 5가 될 때까지 { print(num) }의 문장이 반복 수행
for ( num in (1:3) ) {
print(num)
}
# for 문안에 if 문이나 다른 제어문을 중첩해서 사용할 수 있다.
for ( num in (1:5) ) {
if ( num %% 2 == 0)
print( paste( num, "짝수") )
else
print( paste( num, "홀수") )
}
# for 문을 이용해서 하나씩 수행하는 것보다 벡터나 행렬 연산을 통해서 수행하는 것이 훨씬 빠름
num <- c(1:5)
ifelse(num%%2==0, paste(num, "짝수"), paste(num, "홀수"))
## 3. 함수
a <- 10
a
# 함수 정의
a <- function () { # a는 변수가 아닌 함수로 생성
print("testa")
print("testa")
}
# 함수 생성이 함수의 실행을 의미하지는 않음.
# a()라는 함수가 생성되었을 뿐임.
# 함수 호출
a() # a() 함수가 호출되어 a() 함수에 저장된 프로그램 코드가 실행
# 매개변수가 있는 함수 정의와 호출
a <- function(num) { # num이라는 이름의 매개변수가 있는 함수를 생성
print(num) # num 변수의 값을 출력하는 코드를 작성
}
# num 매개변수에 20을 넘겨주고, 함수를 호출. 이때, 20을 매개인자라고 부름
a(20)
# num 매개변수에 10을 넘겨주고, 함수를 호출. 이때, 10을 매개인자라고 부름
a(10)
a <- function(num1, num2) { # 두 개의 매개변수
print(paste (num1, ' ', num2))
}
a(10,20 ) # 매개변수에 순서대로 매핑
# 매개변수 이름을 직접써서 데이터(매개인자) 전달
a(num1=10, num2=20)
a(num2=20, num1=10)
# 리턴 데이터가 있는 함수
calculator <- function (num1, op , num2) {
result <- 0
if (op == "+") {
result <- num1 + num2
}else if (op == "-") {
result <- num1 - num2
}else if (op == "*") {
result <- num1 * num2
}else if (op == "/") {
result <- num1 / num2
}
return (result)
}
n <- calculator(1,"+",2) # n은 calculator()로부터 반환받은 3을 저장
print(n)
n <- calculator(1,"-",2) # n은 calculator()로부터 반환받은 -1을 저장
print(n)
<file_sep>/데이터 분석/4. 단순선형회귀.R
# 3. 단순선형회귀
# [실습1] 단순선형회귀|모델 생성
data(Orange)
head(Orange)
model <- lm(circumference ~ age, Orange)
model
# 회귀계수
coef(model)
# [실습2] 단순선형회귀|잔차
# 잔차
r <- residuals(model)
r[0:4]
# fitted() 함수로 model이 예측한 값 구하기
f <- fitted(model)
# residuals() 함수로 잔차 구하기
r <- residuals(model)
# 예측한 값에 잔차를 더하여 실제값과 동일한지 확인해보자.
# 예측한 값과 잔차 더하기
f[0:4] + r[0:4]
# 위의 값이 다음의 실제 데이터와 동일함을 확인할 수 있다.
# 실제값
Orange[0:4, 'circumference']
# 잔차 제곱합
deviance(model)
# [실습3] 단순선형회귀|예측
# 예측
predict.lm(model, newdata = data.frame(age = 100))
summary(model)
# 결정계수 값은 상관계수의 제곱과 같다.
(cor(Orange$circumference, Orange$age))^2
<file_sep>/데이터 분석/2. 추론 통계.R
# 1. 추론통계
# [실습1] t-검정|일표본 검증
# A병원에서 치료한 성인 여성 감기 환자들의 치유 기간 데이터 (단위: 일)
data <- c(5, 6, 7, 5, 5, 9, 10, 3, 3, 3.5, 8, 8, 7, 2, 3, 3.5, 6, 6, 6, 6)
# 모평균이 7보다 적은지 단측 검정
t.test(data, mu=7, alternative = 'less')
# [실습2] t-검정|대응이표본 검증
# 다이어트약 복용 전 몸무게
before <- c(68.12, 56.94, 57.36, 54.64, 64.33, 48.49, 68.72, 56.19, 61.6, 58.75, 67.31, 49.7, 58.39, 58.08, 65.67, 54.5, 59.14, 55.61, 60.21, 62.91)
# 다이어트약 복용 5개월 후 몸무게
after <- c(65.90, 54.79, 57.82, 54.64, 64.84, 47.34, 67.87, 54.58, 60.65, 58.79, 65.71, 48.81, 57.0, 56.52, 64.13, 53.94, 57.22, 55.32, 61.61, 63.22)
# 대응이표본이므로 paired = TRUE 옵션 사용
# 단측 검정으로 before 데이터가 더 큰지 검정하므로 alternative = "greater" 옵션 사용
t.test(before, after, paired = TRUE, var.equal = TRUE, alternative = "greater")
# [실습3] t-검정|독립이표본 검증
# 서울 지역의 남학생의 몸무게 데이터
Seoul <- c(43.12, 40.94, 42.36, 50.64, 50, 43.39, 43.72, 40.19, 46.6, 43.75, 42.31, 44.7, 43.39, 33.08, 40.67, 49.5, 34.14, 40.61, 35.21, 37.91)
# 부산 지역의 남학생의 몸무게 데이터
Busan <- c(41.74, 42.35, 40.62, 28.64, 49.64, 40.94, 43.25, 40.3, 56.03, 43.77, 51.3, 44.26, 42.6, 32.19, 39.72, 49.2, 33.03, 40.45, 36.03, 38.1)
# 독립이표본이므로 paired = FALSE 옵션 사용
# 양측 검정이므로 alternative = "two.sided" 옵션 사용
# Seoul 데이터와 Busan 데이터의 분산이 동일하지 않아 var.equal = FALSE 옵션 사용
t.test(Seoul, Busan, paired = FALSE, var.equal = FALSE, alternative = "two.sided")
# [실습4] 분산분석|일원분산분석
anova_result <- aov(Sepal.Length ~ Species, data = iris)
# 종속변수(Sepal,Length), 독립변수(Species)
summary(anova_result)
<file_sep>/R 기초 프로그래밍/chapter05 데이터 조작.R
## 1. 데이터의 대략적인 특징 파악
# head() 함수
head(Orange) # 첫번째 행부터 6번째 행까지 추출
head(Orange,3) # 첫번째 행부터 3번째 행까지 추출
# tail() 함수
tail(Orange) # 마지막 행부터 6개의 행까지 추출
tail(Orange,10) # 마지막 행부터 10개의 행까지 추출
# str() 함수
str(Orange) # 데이터의 구조 파악악
# summary() 함수
summary(Orange)
## 2. 외부 파일 읽기
# CSV 파일 불러오기
nhis <- read.csv("c:/data/NHIS_OPEN_GJ_EUC-KR.csv")
head(nhis)
nhis <- read.csv("c:/data/NHIS_OPEN_GJ_EUC-KR.csv", fileEncoding="EUC-KR")
nhis <- read.csv("c:/data/NHIS_OPEN_GJ_UTF-8.csv", fileEncoding = "UTF-8" )
sample<- read.csv("c:/data/sample.csv", header = F,
fileEncoding="EUC-KR", stringsAsFactor = TRUE) # 문자열 데이터를 범주형 데이터로 읽음음
str(sample)
# 엑셀(slsx) 파일 불러오기
install.packages('openxlsx') # openxlsx 패키지 설치
library(openxlsx)
nhis_sheet1= read.xlsx('c:/data/NHIS_OPEN_GJ_EUC-KR.xlsx' )
# 디폴트로 엑셀 파일의 첫번째 sheet를 읽음.
nhis_sheet2= read.xlsx('c:/data/NHIS_OPEN_GJ_EUC-KR.xlsx', sheet=2)
# 두번째 sheet를 읽음.
# 빅데이터 파일 불러오기
# data.table 패키지의 fread()는 빠른 속도로 데이터를 읽어 빅데이터 파일을 읽을 때 매우 유용용
install.packages('data.table') # data.table 패키지 설치
library(data.table) # data.table 패키지 불러오기
nhis_bigdata = fread("c:/data/NHIS_OPEN_GJ_BIGDATA_UTF-8.csv", encoding = "UTF-8" )
str(nhis_bigdata)
## 3. 데이터 추출
# 행 인덱스를 이용하여 행 제한
Orange[1, ] # 1행만 추출
Orange[1:5, ] # 1행부터 5행까지 추출
Orange[6:10, ] # 6행부터 10행까지 추출
Orange[c(1,5), ] # 1행과 5행 추출
Orange[-c(1:29), ] # 1~29행 제외하고 모든 행 추출
# 데이터를 비교하여 행 제한
Orange[Orange$age ==118, ] # age컬럼의 데이터가 118인 행만 추출
Orange[Orange$age %in% c(118,484), ]
# age 컬럼의 데이터가 118 또는 484인 행만 추출
Orange[Orange$age >= 1372 , ]
# age 컬럼의 데이터가 1372와 같거나 큰 행만 추출
# 열 이름을 이용하여 열 제한
# Orange의 circumference 열만 추출. 행은 모든 행 추출
Orange[ , "circumference"]
# Orange의 Tree와 circumference 열만 추출. 행은 1행만 추출
Orange[ 1 , c("Tree","circumference")]
# 열 인덱스를 이용하여 열 제한
Orange[ , 1] # Orange 데이터프레임의 첫번째 열만 추출
Orange[ , c(1,3)] # Orange 데이터프레임의 1열과 3열만 추출
Orange[ , c(1:3)] # Orange 데이터프레임의 첫번째 열부터 3번째 열까지 추출
Orange[ , -c(1,3)] # Orange 데이터프레임의 1열과 3열만 제외하고 추출
# 행과 열 제한
# 1행~5행, circumference 열 추출
Orange[1:5 , "circumference"]
# Tree열이 3 또는 2인 행의 Tree 열과 circumference 열 추출출
Orange[Orange$Tree %in% c(3,2), c("Tree","circumference")]
# 정렬
OrangeT1 <- Orange[Orange$circumference < 50, ]
OrangeT1[ order(OrangeT1$circumference), ]
# 내림차순 정렬은 order() 안에 마이너스(-) 기호를 사용하면 됨
OrangeT1[ order( -OrangeT1$circumference ), ]
# 그룹별 집계
# Tree 별 circumference 평균
aggregate(circumference ~ Tree, Orange, mean)
## 4. 데이터 구조 변경
# 데이터프레임 준비
stu1 <- data.frame( no = c(1,2,3), midterm = c(100,90,80))
stu2 <- data.frame( no = c(1,2,3), finalterm = c(100,90,80))
stu3 <- data.frame( no = c(1,4,5), quiz = c(99,88,77))
stu4 <- data.frame( no = c(4,5,6), midterm = c(99,88,77))
# 데이터병합
stu1
stu2
merge(stu1, stu2)
stu3
merge(stu1, stu3)
merge(stu1, stu3, all=TRUE)
stu4
stu1
rbind(stu1, stu4)
stu2
cbind(stu1, stu2)
cbind(stu1, stu3)
<file_sep>/데이터 분석/7. 주성분 분석.R
# 6. 주성분 분석
# [실습1] 주성분 분석: princomp()
fit <- princomp(iris[, 1:4], cor = TRUE) # 상관행렬 이용한 주성분 분석 수행, cor = FALSE: 공분산행렬(디폴트)
# [실습2] 주성분 분석: summary()
summary(fit)
# [실습3] 주성분 분석: loadings()
loadings(fit)
# [실습4] 주성분 개수 선택법 - 스크리 그래프
screeplot(fit, type = "lines", main = "scree plot")
<file_sep>/R 기초 프로그래밍/chapter02 변수와 데이터타입.R
## 1. 변수
age <- 20
age
age <- 30
age
## 2. 데이터 타입
#숫자 데이터 타입
age <- 20
class(age)
age <- 20L
class(age)
# 문자 데이터 타입
name <- "LJI" #control + enter
class(name)
# 논리 데이터 타입
is_effective <- T
is_effective
is_effective <- F
is_effective
class(is_effective)
# 펙터 데이터 타입
sido <- factor("서울", c("서울","부산","제주"))
sido
class(sido)
levels(sido)
## 3. 상수
# NULL과 NA
a <- NULL # NULL은 변수에 값이 아직 정해지지 않았다는 의미로 변수를 초기화할 때 사용
jumsu <- c(NA, 90, 100) # NA는 '결측치'를 의미하는 상수
# Inf와 NaN
10/0 # Inf는 무한대 실수를 의미하는 상수
0/0 # NaN은 Not a Number를 의미하는 상수
<file_sep>/데이터 분석/3. 상관 분석.R
# [실습1] 피어슨 상관계수 구하기1
cor(Orange$circumference, Orange$age)
plot(Orange$circumference, Orange$age, col = "red", pch = 19) # 산점도 그리기
# [실습2] 피어슨 상관계수 구하기2
cor(iris[, 1:4])
# [실습3] 상관계수 검정
cor.test(iris$Petal.Length, iris$Petal.Width, method = "pearson") # 피어슨 상관계수 검정
cor.test(iris$Petal.Length, iris$Sepal.Width, method = "spearman") # 스피어만 상관계수 검정
| f8ecf9a6c5729b7eab34bf8fe73f358e63058aba | [
"R"
]
| 10 | R | Sehee99/R-Study | 227a86648d6e2cb138f031e1dd27e7ec0582c9ab | edefb9e80e0532a39792219d85598968b564dd40 |
refs/heads/master | <repo_name>tinchovictory/InterProcessComunication<file_sep>/hash.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include <sys/stat.h>
#include <dirent.h>
#include <libgen.h>
#include "queue.h"
#define CHILD_PROCESS_Q 5
#define FILE_NAME "hash.txt"
#define FILENAME_LENGTH 200
#define MD5_RESPONSE_LENGTH FILENAME_LENGTH + 50
void createPipe(int pipeFd[CHILD_PROCESS_Q][2], int process);
pid_t createChildProcess();
void runChildProcessCode(int pcPipe[CHILD_PROCESS_Q][2], int cpPipe[CHILD_PROCESS_Q][2], int process);
void configureChildPipes(int pcPipe[CHILD_PROCESS_Q][2], int cpPipe[CHILD_PROCESS_Q][2], int process);
void configureParentPipes(int pcPipe[CHILD_PROCESS_Q][2], int cpPipe[CHILD_PROCESS_Q][2]);
int sendFiles(T_Queue filesQueue, int pcPipe[CHILD_PROCESS_Q][2]);
void sendFileToChild(int fd, char * fileName);
void sendEndOfWrite(int pcPipe[CHILD_PROCESS_Q][2]);
void closeWritePipe(int pipeFd[CHILD_PROCESS_Q][2]);
void setNonBlockingRead(int pipeFd[2][2]);
T_Queue readHashFromChilds(int pipeFd[2][2], int filesAmount, char * shm);
T_Queue saveResponse(T_Queue responseQueue, char * str);
T_Queue writeToSharedMemory(T_Queue responseQueue, char * shm);
char * startSHM(char * shm);
int canIWrite(char * shm);
void writeEndOfSHM(char * shm);
void writeToDisk(char * str);
void removeFile();
void formatOutput(char * str);
int isFile(const char *path);
int isDirectory(const char *path);
int isValidDirectory(const char * path);
void formatFileName(char * input, char output[FILENAME_SIZE]);
T_Queue getFiles(int argc, char* argv[]);
void printErrorMsg();
int main(int argc, char* argv[]) {
pid_t pid;
T_Queue filesQueue, responseQueue;
int filesAmount;
char * shm = NULL;
/* Get files from input */
filesQueue = getFiles(argc, argv);
if(filesQueue == NULL) {
printf("\n");
exit(1);
}
/* Remove old txt file */
removeFile();
/* Pipes arrays */
int cpPipe[CHILD_PROCESS_Q][2]; /* Child - Parent pipe array */
int pcPipe[CHILD_PROCESS_Q][2]; /* Parent - Child pipe array */
int process;
/* Create CHILD_PROCESS_Q processes */
for(process = 0; process < CHILD_PROCESS_Q; process++) {
/* Create child pipe for process */
createPipe(cpPipe, process);
createPipe(pcPipe, process);
/* Create child process */
pid = createChildProcess();
/* Child proces code */
if(pid == 0) {
runChildProcessCode(pcPipe, cpPipe, process);
}
}
/* Configure parent pipes */
configureParentPipes(pcPipe, cpPipe);
/* Send files to child processes */
filesAmount = sendFiles(filesQueue, pcPipe);
/* Close write end of pipes after finishing sending files */
closeWritePipe(pcPipe);
/* Set read pipe as non-blocking */
setNonBlockingRead(cpPipe);
/* Start shared memory for printing the hashes */
shm = startSHM(shm);
/* Listen to child process. Returns files not printed by output process */
responseQueue = readHashFromChilds(cpPipe, filesAmount, shm);
/* If output process exists */
if(size(responseQueue) < filesAmount || canIWrite(shm)) {
/* Print remaining hashes in output process */
while(!isEmpty(responseQueue)) {
responseQueue = writeToSharedMemory(responseQueue, shm);
}
/* End output process. */
writeEndOfSHM(shm);
}
shmdt(shm);
return 0;
}
/*
* Create a one-way pipe for process in parameters.
*/
void createPipe(int pipeFd[CHILD_PROCESS_Q][2], int process) {
if (pipe(pipeFd[process]) < 0) {
perror("Child - Parent pipe faild");
exit(1);
}
}
/*
* Fork a child process.
* Returns child process pid.
*/
pid_t createChildProcess() {
pid_t pid = fork();
if(pid < 0) {
perror ("Fork faild");
exit(1);
}
return pid;
}
/*
* Code executed by the child process.
* Receives two pipes, from parent to child, from child to parent.
*/
void runChildProcessCode(int pcPipe[CHILD_PROCESS_Q][2], int cpPipe[CHILD_PROCESS_Q][2], int process) {
/* Configure child pipes */
configureChildPipes(pcPipe, cpPipe, process);
/* Run slave process on child */
execl("./slaveProcess", "slaveProcess", NULL, NULL);
/* Run in case of fail */
close(1);
exit(1);
}
/*
* Configure pipe, so that child process writes as stdout to pipe, and reads as stdin from pipe.
*/
void configureChildPipes(int pcPipe[CHILD_PROCESS_Q][2], int cpPipe[CHILD_PROCESS_Q][2], int process) {
/* Close stdout */
close(1);
/* Set stdout to write section of pipe */
dup(cpPipe[process][1]);
/* Close unused side of pipes */
close(cpPipe[process][0]);
close(cpPipe[process][1]);
/* Close stdin */
close(0);
/* Set stdin to read section of pipe */
dup(pcPipe[process][0]);
/* Close unuesd side of pipes */
close(pcPipe[process][0]);
close(pcPipe[process][1]);
}
/*
* Configure parent side of pipes.
*/
void configureParentPipes(int pcPipe[CHILD_PROCESS_Q][2], int cpPipe[CHILD_PROCESS_Q][2]) {
int process;
for(process = 0; process < CHILD_PROCESS_Q; process++) {
/* Close read end of pipe */
close(pcPipe[process][0]);
/* Close write end of pipe */
close(cpPipe[process][1]);
}
}
/*
* Read files from stdin.
* Return them as a queue. If there is a non-valid file it returns NULL.
*/
T_Queue getFiles(int argc, char* argv[]) {
T_Queue filesQueue;
filesQueue = newQueue();
int i;
int valid = 1;
DIR *mydir;
struct dirent *myfile;
char fileName[FILENAME_SIZE];
for(i = 1; i < argc; i++) {
if(isDirectory(argv[i]) && isValidDirectory(argv[i])) {
mydir = opendir(argv[i]);
while((myfile = readdir(mydir)) != NULL) {
if(!((strcmp(myfile->d_name, ".") == 0) || (strcmp(myfile->d_name, "..") == 0))) {
formatFileName(argv[i], fileName);
filesQueue = offer(filesQueue, fileName);
}
}
closedir(mydir);
} else if(isFile(argv[i])) {
formatFileName(argv[i], fileName);
filesQueue = offer(filesQueue, fileName);
} else if(isDirectory(argv[i])) {
continue;
} else {
if(valid) {
printErrorMsg();
}
printf("\t%s\n", argv[i]);
valid = 0;
}
}
if(!valid) {
return NULL;
}
return filesQueue;
}
/*
* Check if the path is a file.
*/
int isFile(const char *path) {
struct stat statbuf;
if(stat(path, &statbuf) != 0) {
return 0;
}
return S_ISREG(statbuf.st_mode);
}
/*
* Check if the path is a directory.
*/
int isDirectory(const char *path) {
struct stat statbuf;
if(stat(path, &statbuf) != 0) {
return 0;
}
return S_ISDIR(statbuf.st_mode);
}
/*
* Check if the directory path ends with '/*'.
*/
int isValidDirectory(const char * path) {
int pathLength = strlen(path);
if(path[pathLength-1] == '*' && path[pathLength-2] == '/') {
return 1;
}
return 0;
}
/*
* End the file name with a '\n' character.
*/
void formatFileName(char * input, char output[FILENAME_SIZE]) {
int i = 0;
while(*(input+i)) {
output[i] = input[i];
i++;
}
output[i++] = '\n';
output[i] = 0;
}
/*
* Print an error message if a file is not valid.
*/
void printErrorMsg() {
printf("\n ----- HASH -----\n");
printf("Parece que ingresaste un archivo o directorio no valido.\n");
printf("Por favor verifica que los siguientes archivos sean validos:\n");
}
/*
* Send files for hash to child processes. Distribution is according to the amount of files.
*/
int sendFiles(T_Queue filesQueue, int pcPipe[CHILD_PROCESS_Q][2]) {
int sentFiles = 0;
while(!isEmpty(filesQueue)) {
/* Temporary fileName var */
char fileName[FILENAME_SIZE] = {0};
/* Get fileName from queue */
filesQueue = poll(filesQueue,fileName);
/* Select wich process will hash it. */
int processNumber = sentFiles % CHILD_PROCESS_Q;
/* Send file name to process */
sendFileToChild(pcPipe[processNumber][1], fileName);
sentFiles++;
}
sendEndOfWrite(pcPipe);
return sentFiles;
}
/*
* Send file name to child.
*/
void sendFileToChild(int fd, char * fileName) {
write(fd, fileName, strlen(fileName));
}
/*
* Send '\0' to each child process, to inform no more writing will be done.
*/
void sendEndOfWrite(int pcPipe[CHILD_PROCESS_Q][2]) {
int i;
for(i = 0; i < CHILD_PROCESS_Q; i++) {
write(pcPipe[i][1], "\0", 1);
}
}
/*
* Close write side of pipes.
*/
void closeWritePipe(int pipeFd[CHILD_PROCESS_Q][2]) {
int i;
for(i = 0; i < CHILD_PROCESS_Q; i++) {
close(pipeFd[i][1]);
}
}
/*
* Set read pipe as non blocking. This prevents of waiting for a large file while other are ready.
*/
void setNonBlockingRead(int pipeFd[2][2]) {
int i;
for(i = 0; i < CHILD_PROCESS_Q; i++) {
int flags = fcntl(pipeFd[i][0], F_GETFL, 0);
fcntl(pipeFd[i][0], F_SETFL, flags | O_NONBLOCK);
}
}
/*
* Get hashes from child process. Reads iterative from each process.
* Hashes are saved to a buffer, so shared memory can access it.
* Hashes are saved to a file.
* Returns the hashes not printed by hashOutput process.
*/
T_Queue readHashFromChilds(int pipeFd[2][2], int filesAmount, char * shm) {
T_Queue responseQueue = newQueue();
char ch;
int count = 0;
char fileNameBuff[MD5_RESPONSE_LENGTH] = {0};
int pos;
/* Listen to child process until all files hashes are received */
while(count < filesAmount) {
int process;
/* Iterate over every process loking for data */
for(process = 0; process < CHILD_PROCESS_Q; process++) {
int resp = read(pipeFd[process][0], &ch, 1);
/* Chek if I received one character, as read returns -1 if no characters where received. */
/* Also chek if the received character is an end of read. */
/* In both cases skip the iteraton. */
if(resp <= 0 || ch == '\0') {
continue;
} else {
/* Otherwise I save the received character, adn keep reading until '\n' is received. */
pos = 0;
fileNameBuff[pos++] = ch;
while(read(pipeFd[process][0], &ch, 1) > 0 && ch != '\n') {
fileNameBuff[pos++] = ch;
if(ch == '\n') {
/* Full response received. */
break;
}
}
/* End fileName string */
fileNameBuff[pos] = 0;
/* One file was received. */
count++;
/* Format response to specified output. */
formatOutput(fileNameBuff);
/* Write file to shared memory. */
responseQueue = saveResponse(responseQueue, fileNameBuff);
/* Write file to disk. */
writeToDisk(fileNameBuff);
}
}
/* Write file to shared memory */
responseQueue = writeToSharedMemory(responseQueue, shm);
}
return responseQueue;
}
/*
* If file hash.txt exist, remove it
*/
void removeFile() {
char * file = FILE_NAME;
if(access( file, F_OK ) != -1) {
remove(file);
}
}
/*
* Write response to a file on disk.
*/
void writeToDisk(char * str) {
char * file = FILE_NAME;
FILE * fpointer;
fpointer = fopen(file,"a");
fprintf(fpointer, "%s\n", str);
fclose(fpointer);
}
/*
* Add response str to response queue.
* Retrurns response queue.
*/
T_Queue saveResponse(T_Queue responseQueue, char * str) {
responseQueue = offer(responseQueue, str);
return responseQueue;
}
/*
* Write next response from responseQueue into shared memory with output proceess.
* Returns updated responseQueue.
*/
T_Queue writeToSharedMemory(T_Queue responseQueue, char * shm) {
/* If I have hashes to print and output process is ready, I write them in shared memory. */
if(!isEmpty(responseQueue)) {
if(canIWrite(shm)) {
char fileNameBuff[MD5_RESPONSE_LENGTH] = {0};
responseQueue = poll(responseQueue, fileNameBuff);
int i;
for(i = 0; fileNameBuff[i] != 0 && i < MD5_RESPONSE_LENGTH; i++) {
shm[i] = fileNameBuff[i];
}
shm[i] = 0;
}
}
return responseQueue;
}
/*
* Initialize shared memory.
* Returns the shared portion of memory.
*/
char * startSHM(char * shm) {
int shmid;
key_t key;
/* Harcoded key */
key = 1211;
/* Create a shared memory segment with size MD5_RESPONSE_LENGTH */
if((shmid = shmget(key, MD5_RESPONSE_LENGTH, IPC_CREAT | 0666)) < 0 ) {
perror("Shared memory failed\n");
exit(1);
}
/* Atach shared memory to shm pointer */
if((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("Shared memory create failed\n");
exit(1);
}
/* Avoid telling the output process that no more hashes to be printed */
*shm = 's';
return shm;
}
/*
* Basic aproach of semaphore.
* If first character of shared memory is not mofied by output process, I can not write.
*/
int canIWrite(char * shm) {
if(*shm == '*') {
return 1;
}
return 0;
}
/*
* Wait until the output process ends reading and write 0 as first character.
* Output process will know there are no more hashes to be printed.
*/
void writeEndOfSHM(char * shm) {
while(1) {
if(canIWrite(shm)) {
shm[0] = 0;
break;
}
}
}
/*
* Turn str to the specified output <file name>: <hash>
*/
void formatOutput(char * str) {
//printf("%s\n", str);
char aux[MD5_RESPONSE_LENGTH] = {0};
int i = 0, j = 0;
while(*(str+i) != ' ') {
aux[i] = str[i];
i++;
}
aux[i] = 0;
i += 2;
while(*(str+i)) {
str[j++] = str[i++];
}
str[j++] = ':';
str[j++] = ' ';
i = 0;
while(aux[i]) {
str[j++] = aux[i++];
}
str[j] = 0;
//printf("%s\n", str);
}<file_sep>/tests/hash.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/select.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include "queue.h"
#define CHILD_PROCESS_Q 5
#define FILES_AMOUNT 7
void createChildProcesess(int pcPipe[CHILD_PROCESS_Q][2], int cpPipe[CHILD_PROCESS_Q][2]);
void createPipes(int process, int pcPipe[CHILD_PROCESS_Q][2], int cpPipe[CHILD_PROCESS_Q][2]);
void configureChildProcess(int process, int pcPipe[CHILD_PROCESS_Q][2], int cpPipe[CHILD_PROCESS_Q][2]);
T_Queue getFiles();
void sendFiles(T_Queue filesQueue, int pcPipe[CHILD_PROCESS_Q][2]);
void sendFileToChild(int pcPipe[CHILD_PROCESS_Q][2], int process, char fileName[FILENAME_SIZE]);
void sendEndToChilds(int pcPipe[CHILD_PROCESS_Q][2]);
void closePipes(int pipe[CHILD_PROCESS_Q][2], int fd);
void setNonBlockingRead(int pipe[CHILD_PROCESS_Q][2]);
int main(void) {
/* CHILD_PROCESS_Q pipes arrays */
int pcPipe[CHILD_PROCESS_Q][2];
int cpPipe[CHILD_PROCESS_Q][2];
/* Files queue */
T_Queue filesQueue;
/* Create CHILD_PROCESS_Q procecess */
createChildProcesess(pcPipe, cpPipe);
/* Close pipe section not beeing used. */
closePipes(pcPipe,0);
closePipes(cpPipe,1);
/* Get files from input */
filesQueue = getFiles();
/* Send files to child process */
sendFiles(filesQueue, pcPipe);
/* Close pipe after writing */
closePipes(pcPipe,1);
/* Set read pipes as non-blocking */
setNonBlockingRead(cpPipe);
/* Listen to child process */
int files = FILES_AMOUNT;
char ch;
int count = 0;
while(count < files) { // leo hasta llegar al numero de archivos
int i;
for(i = 0; i < 2; i++) { //itero por los pipes buscando cual tiene datos para leer
int resp = read(cpPipe[i][0], &ch, 1);
if(resp < 0) {//da -1 si no tiene nada para leer (habria que verificar error especifico)
continue;
} else if(resp == 0) { //se cerro el pipe del otro lado, lo salteo
break;
} else { //guardo el contenido de lo que leo
printf("From Process %d:\n", i);
putchar(ch);
while(read(cpPipe[i][0], &ch, 1) > 0) { //sigo leyendo hasta el final
putchar(ch);
if(ch == '\n') {
break;
}
}
count++; //aumento el numero de archivos leidos
}
}
}
printf("\nDone!!\n");
return 0;
}
void createChildProcesess(int pcPipe[CHILD_PROCESS_Q][2], int cpPipe[CHILD_PROCESS_Q][2]) {
int process;
for(process = 0; process < CHILD_PROCESS_Q; process++) {
createPipes(process, pcPipe, cpPipe);
/* Create child process */
int pid = fork();
if(pid < 0) {
/* Fork faild! */
perror ("Fork faild");
exit(1);
}
if(pid == 0) {
/* Child process code */
configureChildProcess(process, pcPipe, cpPipe);
/* Run slave process in child process */
execl("./slaveProcess", "slaveProcess", NULL, NULL);
//execl("./tests/slaveTest", "slaveTest", NULL, NULL);
close(1);
exit(0);
}
}
}
void createPipes(int process, int pcPipe[CHILD_PROCESS_Q][2], int cpPipe[CHILD_PROCESS_Q][2]) {
if (pipe(pcPipe[process]) < 0) {
perror("Parent - Child pipe faild");
exit(1);
}
if (pipe(cpPipe[process]) < 0) {
perror("Child - Parent pipe faild");
exit(1);
}
}
void configureChildProcess(int process, int pcPipe[CHILD_PROCESS_Q][2], int cpPipe[CHILD_PROCESS_Q][2]) {
close(1); /* Close stdout */
dup(cpPipe[process][1]); /* Set stdout to write section of pipe */
close(0); /* Close stdin */
dup(pcPipe[process][0]); /* Set stdin to read section of pipe */
close(cpPipe[process][0]); /* Close pipe section not beeing used */
close(cpPipe[process][1]); /* Close pipe section not beeing used */
close(pcPipe[process][0]); /* Close pipe section not beeing used */
close(pcPipe[process][1]); /* Close pipe section not beeing used */
}
T_Queue getFiles() {
T_Queue filesQueue;
filesQueue = newQueue();
filesQueue = offer(filesQueue, "./tests/forkTest.c");
filesQueue = offer(filesQueue, "./tests/Movie.mkv");
filesQueue = offer(filesQueue, "./tests/forkTest.c");
filesQueue = offer(filesQueue, "./tests/forkTest.c");
filesQueue = offer(filesQueue, "./tests/Movie.mkv");
filesQueue = offer(filesQueue, "./tests/forkTest.c");
filesQueue = offer(filesQueue, "./tests/maintest.c");
return filesQueue;
}
void sendFiles(T_Queue filesQueue, int pcPipe[CHILD_PROCESS_Q][2]) {
int count = 0;
while(!isEmpty(filesQueue)) {
char fileName[FILENAME_SIZE]; /* Temporary fileName var */
filesQueue = poll(filesQueue,fileName);
int processNumber = count % CHILD_PROCESS_Q;
count++;
sendFileToChild(pcPipe, processNumber, fileName);
}
sendEndToChilds(pcPipe);
}
void sendFileToChild(int pcPipe[CHILD_PROCESS_Q][2], int process, char fileName[FILENAME_SIZE]) {
write(pcPipe[process][1], fileName, strlen(fileName));
}
void sendEndToChilds(int pcPipe[CHILD_PROCESS_Q][2]) {
int i;
for(i = 0; i < CHILD_PROCESS_Q; i++) {
write(pcPipe[i][1], '\0', 1);
}
}
void closePipes(int pipe[CHILD_PROCESS_Q][2], int fd) {
int process;
for(process = 0; process < CHILD_PROCESS_Q; process++) {
close(pipe[process][fd]);
}
}
void setNonBlockingRead(int pipe[CHILD_PROCESS_Q][2]) {
int process;
for(process = 0; process < CHILD_PROCESS_Q; process++) {
int flags = fcntl(pipe[process][0], F_GETFL, 0);
fcntl(pipe[process][0], F_SETFL, flags | O_NONBLOCK);
}
}
<file_sep>/tests/slaveProcess.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include "queue.h"
int main(void) {
pid_t pid;
//int pcPipe[2]; /* Parent - child pipe */
int cpPipe[2]; /* Child - Parent pipe */
char fileName[FILENAME_SIZE]; /* Temporary fileName var */
/* Create filesQueue */
T_Queue filesQueue;
filesQueue = newQueue();
/*Read filesNames sent by parent*/
char ch;
int pos = 0;
int resp;
do {
resp = read(0,&ch,1);
if(ch == '\n') {
fileName[pos] = 0;
filesQueue = offer(filesQueue, fileName);
pos = 0;
} else if(ch != '\0') {
fileName[pos++] = ch;
}
} while(resp == 1 && ch != '\0');
/*
while(read(0, &ch, 1) == 1) {
if(ch != 0 && ch != '\n') {
fileName[pos++] = ch;
} else if(ch == '\n') { /* Por alguna razon manda un \n y un 0 al final. Solo me importa el 0*/
/*continue;
} else {
fileName[pos] = 0;
filesQueue = offer(filesQueue, fileName);
pos = 0;
}
}*/
//dprintf(1, "hola\n");
/* While filesQueue is not empty get hash of files */
while(!isEmpty(filesQueue)) {
filesQueue = poll(filesQueue,fileName);
/* Create pipes */
/*if (pipe(pcPipe) < 0) {
perror("Parent - Child pipe faild");
exit(1);
}*/
if (pipe(cpPipe) < 0) {
perror("Child - Parent pipe faild");
exit(1);
}
/* Create child process */
pid = fork();
if(pid < 0) {
/* Fork faild! */
perror ("Fork faild");
exit(1);
}
if(pid == 0) {
/* Child process code */
close(1); /* Close stdout */
dup(cpPipe[1]); /* Set stdout to write section of pipe */
//close(0); /* Close stdin */
//dup(pcPipe[0]); /* Set stdin to read section of pipe */
close(cpPipe[0]);
close(cpPipe[1]);
//close(pcPipe[1]);
/* Run md5sum in child process */
execl("/usr/bin/md5sum", "md5sum", fileName, NULL);
//printf("hola\n");
close(1);
exit(0);
} else {
/* Parent process code */
//close(pcPipe[1]); /* Close pipe section not beeing used */
close(cpPipe[1]); /* Close pipe section not beeing used */
/* Write to parent process md5 hash */
int pos = 0;
char msg[100] = {0};
char ch;
while( read(cpPipe[0], &ch, 1) == 1) {
//putchar(ch);
msg[pos++] = ch;
}
msg[pos] = 0;
dprintf(1,"%s",msg);
write(1, '\0',1);
//printf("done %s", msg);
//write(1, msg, strlen(msg)+1);
//putchar('\n');
}
}
return 0;
}<file_sep>/tests/forkTest.c
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int pipes[2];
//create a pipe
if(pipe(pipes) < 0) {
//failure in creating a pipe
perror("pipe");
exit (1);
}
pid_t pid = fork();
if(pid < 0) {
//failure in creating a child
perror ("fork");
exit(2);
}
if(pid == 0) {
// only child process
printf("Im the child process, pid=%d\n",getpid() );
//execl("/Users/martin/Documents/ITBA/SO/prog","prog",NULL);
// execl("./prog","prog",NULL);
char message[64] = "Hola soy el mensaje del child process";
//while(1) {
//Clearing the message
// memset (message, 0, sizeof(message));
// printf ("Enter a message: ");
// scanf ("%s",message);
//Writing message to the pipe
write(pipes[1], message, strlen(message));
//}
exit (0);
} else {
// only parent process
printf("Im the parent process, pid=%d, and the child pid is %d\n",getpid(), pid );
//wait(NULL); //wait until child process is done
//printf("Im done\n");
char message[64];
while (1) {
//Clearing the message buffer
memset (message, 0, sizeof(message));
//Reading message from the pipe
read (pipes[0], message, sizeof(message));
printf("Message entered %s\n",message);
}
exit(0);
}
return 0;
}<file_sep>/tests/selectTest.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/select.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#define FILES_AMOUNT 3
#define CHILD_PROCESS_Q 2
void readData(int cpPipe[2][2]);
void setNonBlockingRead(int cpPipe[2][2]);
void closePipe(int pipe[2], int fd);
int main(void) {
pid_t pid;
int cpPipe[CHILD_PROCESS_Q][2]; /* Child - parent pipe */
int pcPipe[CHILD_PROCESS_Q][2]; /* Parent - child pipe */
int process;
for(process = 0; process < CHILD_PROCESS_Q; process++) {
if (pipe(cpPipe[process]) < 0) {
perror("Child - Parent pipe faild");
exit(1);
}
if (pipe(pcPipe[process]) < 0) {
perror("Parent - Child pipe faild");
exit(1);
}
/* Create child process */
pid = fork();
if(pid < 0) {
/* Fork faild! */
perror ("Fork faild");
exit(1);
}
if(pid == 0) {
/* Child process code */
close(1); /* Close stdout */
dup(cpPipe[process][1]); /* Set stdout to write section of pipe */
close(cpPipe[process][0]);
close(cpPipe[process][1]);
close(0); /* Close stdin */
dup(pcPipe[process][0]);
close(pcPipe[process][0]);
close(pcPipe[process][1]);
execl("./slaveProcess2", "slaveProcess2", NULL, NULL);
//execl("./slaveTest", "slaveTest", NULL, NULL);
printf("fail\n");
if(process == 1) {
//exit(0);
//execl("./slaveTest", "slaveTest", NULL, NULL);
} else {
//execl("/usr/bin/md5sum", "md5sum", "./pipes.c", NULL);
//execl("./slaveTest", "slaveTest", NULL, NULL);
}
close(1);
exit(0);
}
}
/* Parent process code */
closePipe(pcPipe[0],0); // close read end of pipe
closePipe(pcPipe[1],0);
closePipe(cpPipe[1],1);
closePipe(cpPipe[0],1); // close write end of pipes
write(pcPipe[0][1], "./tests/forkTest.c\n", strlen("./tests/forkTest.c\n"));
write(pcPipe[1][1], "./hash.c\n", strlen("./hash.c\n")+1);
write(pcPipe[0][1], "./tests/Movie.mkv\n", strlen("./tests/Movie.mkv\n")+1);
closePipe(pcPipe[1],1);//no quiero ecribir el 1
closePipe(pcPipe[0],1); //ya no quiero enviar mas
setNonBlockingRead(cpPipe);
printf("Getting hash...\n");
readData(cpPipe);
printf("\nDone %d\n", pid);
return 0;
}
void closePipe(int pipe[2], int fd) {
close(pipe[fd]);
}
void setNonBlockingRead(int cpPipe[2][2]) {
int flags = fcntl(cpPipe[0][0], F_GETFL, 0);
fcntl(cpPipe[0][0], F_SETFL, flags | O_NONBLOCK);
flags = fcntl(cpPipe[1][0], F_GETFL, 0);
fcntl(cpPipe[1][0], F_SETFL, flags | O_NONBLOCK);
}
void readData(int cpPipe[2][2]) {
int files = FILES_AMOUNT;
char ch;
int count = 0;
while(count < files) { // leo hasta llegar al numero de archivos
int i;
for(i = 0; i < CHILD_PROCESS_Q; i++) { //itero por los pipes buscando cual tiene datos para leer
int resp = read(cpPipe[i][0], &ch, 1);
if(resp < 0) {//da -1 si no tiene nada para leer (habria que verificar error especifico)
continue;
} else if(resp == 0) { //se cerro el pipe del otro lado, lo salteo
continue;
} else if(ch == '\0') {
continue;
} else { //guardo el contenido de lo que leo
printf("From Process %d:\n", i);
putchar(ch);
while(read(cpPipe[i][0], &ch, 1) > 0 && ch != '\n') { //sigo leyendo hasta el final
putchar(ch);
if(ch == '\n') {
break;
}
}
putchar('\n');
count++; //aumento el numero de archivos leidos
}
}
}
}<file_sep>/tests/printFiles.c
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <libgen.h>
#include <string.h>
int isFile(const char *path);
int isDirectory(const char *path);
void formatFileName(char * input, char output[100]);
int getFiles(int argc, char* argv[]);
int main(int argc, char* argv[]) {
if(getFiles(argc, argv) == 0) {
return 1;
}
return 0;
}
int getFiles(int argc, char* argv[]) {
DIR *mydir;
struct dirent *myfile;
struct stat mystat;
int i;
int valid = 1;
char fileName[100];
for(i = 1; i < argc; i++) {
if(isDirectory(argv[i])) {
mydir = opendir(argv[i]);
while((myfile = readdir(mydir)) != NULL) {
if(!((strcmp(myfile->d_name, ".") == 0) || (strcmp(myfile->d_name, "..") == 0))) {
formatFileName(argv[i], fileName);
printf("%s", fileName);//offer
}
}
closedir(mydir);
} else if(isFile(argv[i])) {
formatFileName(argv[i], fileName);
printf("%s", fileName);//offer
} else {
printf("%s parece que no existe...\n", argv[i]);
valid = 0;
}
}
return valid;
}
int isFile(const char *path) {
struct stat statbuf;
if(stat(path, &statbuf) != 0) {
return 0;
}
return S_ISREG(statbuf.st_mode);
}
int isDirectory(const char *path) {
struct stat statbuf;
if(stat(path, &statbuf) != 0) {
return 0;
}
return S_ISDIR(statbuf.st_mode);
}
void formatFileName(char * input, char output[100]) {
int i = 0;
while(*(input+i)) {
output[i] = input[i++];
}
output[i++] = '\n';
output[i] = 0;
}<file_sep>/tests/shmClient.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 100
int canIRead(char * shm);
int isEndOfConnection(char * shm);
int main(void) {
int shmid;
char * shm;
key_t key;
key = 1211;
if((shmid = shmget(key, SHM_SIZE, 0666)) < 0 ) {
printf("Shared memory failed\n");
exit(1);
}
if((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
printf("Shared memory create failed\n");
exit(1);
}
//aviso que llegue
*shm = '*';
while(!isEndOfConnection(shm)) {
if(canIRead(shm)) {
printf("%s\n", shm);
*shm = '*';
}
}
return 0;
}
int canIRead(char * shm) {
if(*shm != '*') {
return 1;
}
return 0;
}
int isEndOfConnection(char * shm) {
if(*shm == 0) {
return 1;
}
return 0;
}<file_sep>/slaveProcess.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include "queue.h"
#define FILENAME_LENGTH 200
#define MD5_RESPONSE_LENGTH FILENAME_LENGTH + 50
T_Queue getFilesFromParent();
void createPipe(int pipeFd[2]);
pid_t createChildProcess();
void runChildCode(int cpPipe[2], char * fileName);
void configureChildPipes(int cpPipe[2]);
void getMd5Response(int fd, char resp[MD5_RESPONSE_LENGTH]);
void sendToParent(char msg[MD5_RESPONSE_LENGTH]);
int main(void) {
/* Create filesQueue */
T_Queue filesQueue;
/* Wait for parent for files */
filesQueue = getFilesFromParent();
/* Get hash for every file in filesQueue */
while(!isEmpty(filesQueue)) {
/* Get file name to hash into fileName var */
char fileName[FILENAME_LENGTH];
filesQueue = poll(filesQueue, fileName);
pid_t pid;
int cpPipe[2]; /* Child - parent pipe */
/* Create pipe */
createPipe(cpPipe);
/* Fork for md5sum */
pid = createChildProcess();
/* Child process code */
if(pid == 0) {
runChildCode(cpPipe, fileName);
}
/* Parent process code */
/* Configure parent side of pipe. Close write end of pipe. */
close(cpPipe[1]);
/* Wait for md5sum hash */
char md5ResponseBuff[MD5_RESPONSE_LENGTH] = {0};
getMd5Response(cpPipe[0], md5ResponseBuff);
/* Write hash to parent */
sendToParent(md5ResponseBuff);
}
return 0;
}
/*
* Read files from stdin(parent), and save them into a queue.
* Returns the queue.
* Files recived must be separated by '\n' character.
* End of files is sent as '\0'.
*/
T_Queue getFilesFromParent() {
T_Queue q = newQueue();
char fileName[FILENAME_LENGTH] = {0}; /* Buffer for reading chars */
char ch;
int pos = 0;
/* Read one char at the time until end or '\0' is received. Files are separated by '\n' */
while(read(0, &ch, 1) == 1) {
/* End of file received. Add the buffer as string to the queue */
if(ch == '\n') {
fileName[pos] = 0;
q = offer(q, fileName);
pos = 0;
} else {
fileName[pos++] = ch; /* Add character to buffer if not '\n' */
}
/* Break on end of read */
if(ch == '\0') {
break;
}
}
return q;
}
/*
* Create a one-way pipe.
*/
void createPipe(int pipeFd[2]) {
if(pipe(pipeFd) < 0) {
perror("Child - Parent pipe faild");
exit(1);
}
}
/*
* Fork a child process.
* Returns child process pid.
*/
pid_t createChildProcess() {
pid_t pid = fork();
if(pid < 0) {
perror ("Fork faild");
exit(1);
}
return pid;
}
/*
* Code executed by the child process.
* Receives a one-way pipe from child to parent, and the file name to hash.
*/
void runChildCode(int cpPipe[2], char * fileName) {
/* Configure pipe */
configureChildPipes(cpPipe);
/* Run md5sum */
execl("/usr/bin/md5sum", "md5sum", fileName, NULL);
/* Run in case of fail */
close(1);
exit(0);
}
/*
* Configure pipe, so that child process writes as stdout to pipe.
*/
void configureChildPipes(int cpPipe[2]) {
/* Close stdout */
close(1);
/* Set stdout to write section of pipe */
dup(cpPipe[1]);
/* Close unused sections of pipe */
close(cpPipe[0]);
close(cpPipe[1]);
}
/*
* Read file descriptor and set response to resp.
* File descriptor should be the child to parent pipe, so it reads md5sum output.
*/
void getMd5Response(int fd, char resp[MD5_RESPONSE_LENGTH]) {
int pos = 0;
char ch;
while( read(fd, &ch, 1) == 1) {
resp[pos++] = ch;
}
resp[pos] = 0;
}
/*
* Send msg to stdout (as we are in a pipe, stdout is parent)
*/
void sendToParent(char msg[MD5_RESPONSE_LENGTH]) {
/* Printf didn't work :( */
dprintf(1, "%s", msg);
/* Send end of write to parent. */
write(1, '\0', 1);
}<file_sep>/tests/slaveTest.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/select.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
int main(void) {
char c;
int r = 0;
/* do {
r = read(0,&c,1);
write(1, &c, 1);
} while(r == 1 && c != '\0');
*/
int files = 0;
char msg1[100] = {0};
while(read(0,&c,1) == 1) {
//write(1, &c, 1);
msg1[r++] = c;
if(c == '\0') {
break;
}
if(c == '\n') {
files++;
}
}
dprintf(1, "%s", msg1);
dprintf(1, "Termine de leer\n");
for(r=0;r<files;r++) {
pid_t pid;
int cpPipe[2]; /* Child - parent pipe */
if (pipe(cpPipe) < 0) {
perror("Child - Parent pipe faild");
exit(1);
}
/* Create child process */
pid = fork();
if(pid < 0) {
/* Fork faild! */
perror ("Fork faild");
exit(1);
}
if(pid == 0) {
/* Child process code */
close(1); /* Close stdout */
dup(cpPipe[1]); /* Set stdout to write section of pipe */
close(cpPipe[0]);
close(cpPipe[1]);
execl("/usr/bin/md5sum", "md5sum", "./Movie.mkv", NULL);
close(1);
exit(0);
}
/* Parent process code */
close(cpPipe[1]); //close write end of pipe
dprintf(1,"Hashing...\n");
/*int flags = fcntl(cpPipe[0], F_GETFL, 0);
fcntl(cpPipe[0], F_SETFL, flags | O_NONBLOCK);
*/
char msg[100] = {0};
int pos = 0;
char ch;
/*while(1) {
int resp = read(cpPipe[0], &ch, 1);
if(resp < 0) {//da -1 si no tiene nada para leer (habria que verificar error especifico)
continue;
} else if(resp == 0) { //se cerro el pipe del otro lado, lo salteo
break;
} else { //guardo el contenido de lo que leo
msg[pos++] = ch;
//putchar(ch);
while(read(cpPipe[0], &ch, 1) > 0) { //sigo leyendo hasta el final
//putchar(ch);
msg[pos++] = ch;
}
}
}*/
//dprintf(1,"hash\n");
while( read(cpPipe[0], &ch, 1) == 1) {
msg[pos++] = ch;
}
msg[pos] = 0;
dprintf(1, "%s", msg);
write(1, '\0', 1);
//sleep(2);
}
dprintf(1,"done\n");
return 0;
}
<file_sep>/queue.h
#ifndef __QUEUE
#define __QUEUE
#define FILENAME_SIZE 200
typedef struct node * T_Queue;
/* Create a new Queue */
T_Queue newQueue();
/* Add a string to the queue passed by parameters. Returns the new queue. */
T_Queue offer(T_Queue q, const char elem[FILENAME_SIZE]);
/* Remove the first element of the queue. Returns the new queue. The removed item copied to parameter resp */
T_Queue poll(T_Queue q, char resp[FILENAME_SIZE]);
/* Returns 0 if the queue is empty */
int isEmpty(T_Queue q);
/* Returns the queue size */
int size(T_Queue q);
#endif<file_sep>/tests/shmServer.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 100
int canIWrite(char * shm);
int main(void) {
int shmid;
char * shm;
key_t key;
key = 1211;
if((shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666)) < 0 ) {
printf("Shared memory failed\n");
exit(1);
}
if((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
printf("Shared memory create failed\n");
exit(1);
}
int i;
for(i = 0; i < 5; ) {
if(canIWrite(shm)) {
/* Escribo en shm */
shm[0] = 'h';
shm[1] = 'o';
shm[2] = 'l';
shm[3] = 'a';
shm[4] = 0;
//fprintf(shm, "%s\n", "hola");
i++;
}
}
//end of write
while(1) {
if(canIWrite(shm)) {
shm[0] = 0;
break;
}
}
return 0;
}
int canIWrite(char * shm) {
if(*shm == '*') {
return 1;
}
return 0;
}
/*
agrego las respuestas a una lista
cuando pueda escribir escribo la primera
si no puedo escribir sigo
si ya escribi una en main sigo escribiendo
espero hasta que se escriban todas
si no esctibi nada termino el proceso
leeo la respuesta
agrego a una lista
llamo a funcion
funcion(lista):
si la lista no esta vacia
si puedo esctibir
saco de la lista y lo escribo
puedo saber si hay algun cliente?
*/<file_sep>/README.md
# InterProcessComunication
## Introducción
El trabajo práctico consiste en aprender a utilizar los distintos tipos de IPCs presentes en un sistema POSIX. Para ello se implementará un sistema que distribuirá tareas de cálculo pesadas entre varios pares.
## Grupos
Se formarán grupos de hasta tres personas. En caso de quedar grupos de uno o dos integrantes, se resolverá durante la clase de práctica caso por caso.
## Requerimientos
El sistema calcula los hashes MD5 de múltiples archivos de forma distribuida. Para ello cuenta con procesos aplicación, vista, y esclavos
### Proceso Aplicación
* Recibe por línea de comando los archivos a procesar, por ejemplo:
```
$ hash files/*
```
* Arranca los procesos esclavos.
* Envía una cierta cantidad de archivos a procesar *distribuyendo la carga* entre los esclavos por cantidad de archivos.
* Cuando un esclavo se libera, la aplicación le entrega más tareas.
* Espera los cálculos de los esclavos y los agrega a un buffer a medida que llegan, *por orden de llegada*.
* Espera a que aparezca un proceso vista, si lo hace le comparte el buffer de llegada.
* Termina cuando la operación esté completada.
* El resultado, aparezca el proceso de vista o no, lo escribe a un archivo en disco.
### Proceso Vista
* Recibe por línea de comando el PID del proceso aplicación (corren en el mismo sistema).
* Se conecta al proceso cliente, muestra y actualiza en pantalla el contenido del buffer de llegada usando el formato: `<nombre de archivo>: <hash md5>` para cada archivo procesado.
### Proceso Esclavo
* Procesa los pedidos del cliente, recibiendo los archivos y calculando los hashes MD5 uno por uno, utilizando una cola de pedidos.
* Envía los hashes correspondientes una vez que están listos.
* El proceso esclavo puede (y la cátedra sugiere) ejecutar el comando md5sum para calcular los hashes. Queda libre al ingenio del grupo descubrir cómo recolectar el resultado de md5sum desde el esclavo, pero queda **prohibido** volcarlo a un archivo en disco, para luego leerlo desde el esclavo. IPCs y primitivas de sincronización requeridos
* Para conectar el proceso aplicación con sus esclavos deberán utilizar FIFOs, pipes o named pipes.
* Para compartir el buffer del proceso aplicación es necesario usar Shared Memory con Semáforos.
## Entrega
**Fecha:** 05/09/2017
**Entregables:** Mail con un archivo ZIP adjunto con el código fuente y el informe, el mail debe incluir el hash MD5 del archivo.
**Defensa del trabajo práctico:** el mismo día de la entrega.
<file_sep>/tests/maintest.c
#include <stdio.h>
#include "queue.h"
int main(void) {
T_Queue q;
q = newQueue();
q = offer(q, "Hola");
q = offer(q, "Chau");
q = offer(q, "End");
char msg[FILENAME_SIZE];
while(!isEmpty(q)) {
q = poll(q,msg);
printf("%s\n", msg);
}
return 0;
}
<file_sep>/Makefile
#compiler
CC=gcc
CFLAGS=-c -Wall
all: hash slaveProcess hashOutput
hash: hash.o queue.o
$(CC) hash.o queue.o -o hash
hash.o:
$(CC) $(CFLAGS) hash.c
slaveProcess: slaveProcess.o queue.o
$(CC) slaveProcess.o queue.o -o slaveProcess
slaveProcess.o:
$(CC) $(CFLAGS) slaveProcess.c
queue.o:
$(CC) $(CFLAGS) queue.c
hashOutput: hashOutput.o
$(CC) hashOutput.o -o hashOutput
hashOutput.o:
$(CC) $(CFLAGS) hashOutput.c
clean:
rm -rf *.o hash slaveProcess hashOutput hash.txt
<file_sep>/tests/Makefile
#compiler
CC=gcc
CFLAGS=-c -Wall
all: selectTest slaveTest
selectTest: selectTest.o
$(CC) selectTest.o -o selectTest
selectTest.o:
$(CC) $(CFLAGS) selectTest.c
slaveTest: slaveTest.o
$(CC) slaveTest.o -o slaveTest
slaveTest.o:
$(CC) $(CFLAGS) slaveTest.c
clean:
rm -rf *.o selectTest slaveTest
<file_sep>/hashOutput.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define FILENAME_LENGTH 200
#define MD5_RESPONSE_LENGTH FILENAME_LENGTH + 50
void welcomeMsg();
void endMsg();
char * startSHM(char * shm);
int canIRead(char * shm);
int isEndOfConnection(char * shm);
void sendImReady(char * shm);
int main(void) {
char * shm = NULL;
/* Start shared memory. */
shm = startSHM(shm);
welcomeMsg();
/* Read from shared memory until end character received. */
while(!isEndOfConnection(shm)) {
/* Only read if is my turn. */
if(canIRead(shm) && !isEndOfConnection(shm)) {
printf("%s\n", shm);
sendImReady(shm);
}
}
endMsg();
return 0;
}
void welcomeMsg() {
printf("\n --- Welcome to HASH ---\n\n");
printf("Searching for hashes...\n\n");
}
void endMsg() {
printf("\n\nThanks for using --- HASH ---\n\n");
}
/*
* Start shared memory.
*/
char * startSHM(char * shm) {
int shmid;
key_t key;
/* Harcoded key */
key = 1211;
/* Create a shared memory segment with size MD5_RESPONSE_LENGTH */
if((shmid = shmget(key, MD5_RESPONSE_LENGTH, 0666)) < 0 ) {
printf("Shared memory failed\n");
exit(1);
}
/* Atach shared memory to shm pointer */
if((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
printf("Shared memory create failed\n");
exit(1);
}
/* Inform main process that I was created */
sendImReady(shm);
return shm;
}
/*
* Check if I can read.
* I can read when the first character of shm is not '*'
*/
int canIRead(char * shm) {
if(*shm != '*') {
return 1;
}
return 0;
}
/*
* Check for end of connection.
*/
int isEndOfConnection(char * shm) {
if(*shm == 0) {
return 1;
}
return 0;
}
/*
* Inform main process that I'm ready to read.
*/
void sendImReady(char * shm) {
*shm = '*';
}<file_sep>/tests/pipes.c
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include "queue.h"
int main(void) {
pid_t pid;
int pcPipe[2]; /* Parent - child pipe */
int cpPipe[2]; /* Child - parent pipe */
char fileName[FILENAME_SIZE]; /* Temporary fileName var */
/* Create filesQueue */
T_Queue filesQueue;
filesQueue = newQueue();
/* Test files queue */
filesQueue = offer(filesQueue, "./forkTest.c");
filesQueue = offer(filesQueue, "./maintest.c");
filesQueue = offer(filesQueue, "./prog.c");
/**/
/* While filesQueue is not empty get hash of files */
while(!isEmpty(filesQueue)) {
filesQueue = poll(filesQueue,fileName);
/* Create pipes */
if (pipe(pcPipe) < 0) {
perror("Parent - Child pipe faild");
exit(1);
}
if (pipe(cpPipe) < 0) {
perror("Child - Parent pipe faild");
exit(1);
}
/* Create child process */
pid = fork();
if(pid < 0) {
/* Fork faild! */
perror ("Fork faild");
exit(1);
}
if(pid == 0) {
/* Child process code */
close(1); /* Close stdout */
dup(cpPipe[1]); /* Set stdout to write section of pipe */
close(0); /* Close stdin */
dup(pcPipe[0]); /* Set stdin to read section of pipe */
close(cpPipe[0]);
close(pcPipe[1]);
/*printf("Pending %d \n", getpid());
sleep(2);
printf("Pending %d \n", getpid());
printf("Pending %d \n", getpid());
sleep(5);
printf("Pending %d \n", getpid());
sleep(8);
printf("Pending %d \n", getpid());
sleep(5);*/
/* Run md5sum in child process */
execl("/usr/bin/md5sum", "md5sum", fileName, NULL);
exit(0);
} else {
/* Parent process code */
close(pcPipe[1]); // si no los pongo no anda :(
close(cpPipe[1]);
char ch;
printf("Getting hash...\n");
while( read(cpPipe[0], &ch, 1) == 1) {
putchar(ch);
}
printf("Done %d\n", pid);
}
}
return 0;
}<file_sep>/queue.c
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
/* Node struct, contains a string and a pointer to the next node */
typedef struct node {
char name[FILENAME_SIZE];
struct node *next;
} Tnode;
/* Create a new Queue */
T_Queue newQueue() {
return NULL;
}
/* Add a string to the queue passed by parameters. Returns the new queue. */
T_Queue offer(T_Queue q, const char elem[FILENAME_SIZE]) {
if(q == NULL) {
T_Queue aux = malloc(sizeof(Tnode));
int i;
for(i = 0; i < FILENAME_SIZE; i++) {
aux->name[i] = elem[i];
}
aux->next = q;
return aux;
}
q->next = offer(q->next, elem);
return q;
}
/* Remove the first element of the queue. Returns the new queue. The removed item copied to parameter resp */
T_Queue poll(T_Queue q, char resp[FILENAME_SIZE]) {
if (q == NULL) {
return NULL;
}
int i;
for(i = 0; i < FILENAME_SIZE; i++) {
resp[i] = q->name[i];
}
T_Queue aux = q->next;
free(q);
return aux;
}
/* Returns 0 if the queue is empty */
int isEmpty(T_Queue q) {
if(q == NULL) {
return 1;
}
return 0;
}
/* Returns the queue size */
int size(T_Queue q) {
if(q == NULL) {
return 0;
}
return 1 + size(q->next);
} | 365a2f71886f2e0c33913c240f35ef719a707813 | [
"Markdown",
"C",
"Makefile"
]
| 18 | C | tinchovictory/InterProcessComunication | 35017d54343270fc2cad9e8d9d7242d8288a112a | dfa025e0a5ef54d99d3ada240ce7766b481fffbb |
refs/heads/master | <repo_name>abhijit526/-com.proj<file_sep>/src/com/proj/ki/Poiuy.java
package com.proj.ki;
public class Poiuy {
public static void main(String[] args) {
System.out.println("satya.main()");
System.out.println("satya.main()");
System.out.println("Satya.main()");
}
}
| e094771e865f857eee1031939ca416d7aeee2ef3 | [
"Java"
]
| 1 | Java | abhijit526/-com.proj | 55b5372b7c7b306a2a1eb1f45798b6dfba86e72c | 2056161352c020dbd0c474371b29720814667187 |
refs/heads/master | <file_sep>//const express = require('express')
//const app = express()
//app.get('/', (req, res) => res.send('<html><h1>Bonjour!!!</h1></html>'))
//app.listen(3002, () => console.log('Example app listening on port 3002!'))
var express = require('express');
var app = express();
//app.use('/data.json', express.static(__dirname + '/data.json'));
app.use(express.static(__dirname));
app.get ("/", function (req, res) {
res.sendFile (__dirname + "/index.html") ;
//res.end ();*/
});
app.get ("/liste", function (req, res) {
res.sendFile (__dirname + "/data.json") ;
//res.end ();*/
});
app.listen (3002) ;
<file_sep>
$(function () {
$('#btn').click(function () {
$.ajax({
type: 'GET',
url: 'http://localhost:3002/liste',
success: function (data) {
for (var i = 0; i < data.length; i++) {
$('#liste').append('<li class="li">Personnage : ' + data[i].name.first + '<br/> ' + data[i].name.last + '<br/> ' + data[i]._id + '<br/> ' + data[i].index + '</li>');
}
},
error: function (resultat, statut, erreur) {
alert('ERROR 404');
}
});
});
//
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://localhost:3002/liste',
success: function (data) {
for (var i = 0; i < data.length; i++) {
$('#liste').append('<li class="liste_personne">Personnage : ' + data[i].name.first + '<br/> ' + data[i].name.last + '<br/> ' + data[i]._id + '<br/> ' + data[i].index + '</li>');
}
},
error: function (resultat, statut, erreur) {
alert('ERROR 404');
}
});
});
//
});
$(function(){
$('#btn-2').click(function () {
$('.li').hide();
});
});
| 4f08394d3515689af072c02d7d95a8d8345a4796 | [
"JavaScript"
]
| 2 | JavaScript | NovaT974/express | 8d2d3c5d28cea58e2c8f33ad43a08502d711bbf5 | 304c56af881fdcef1f32199db638071e9e8f5ab7 |
refs/heads/master | <repo_name>wandyezj/ArduinoFaceTracker<file_sep>/FaceTrackerBLE/app/src/main/java/io/makeabilitylab/facetrackerble/FaceGraphic.java
/*
* Copyright (C) The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.makeabilitylab.facetrackerble;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import com.google.android.gms.vision.face.Face;
import io.makeabilitylab.facetrackerble.camera.GraphicOverlay;
/**
* Graphic instance for rendering face position, orientation, and landmarks within an associated
* graphic overlay view.
*/
class FaceGraphic extends GraphicOverlay.Graphic {
private static final float FACE_POSITION_RADIUS = 10.0f;
private static final float ID_TEXT_SIZE = 40.0f;
private static final float ID_Y_OFFSET = 50.0f;
private static final float ID_X_OFFSET = -50.0f;
private static final float BOX_STROKE_WIDTH = 5.0f;
private static final int COLOR_CHOICES[] = {
Color.BLUE,
Color.CYAN,
Color.GREEN,
Color.MAGENTA,
Color.RED,
Color.WHITE,
Color.YELLOW
};
private static int mCurrentColorIndex = 0;
private Paint mFacePositionPaint;
private Paint mIdPaint;
private Paint mBoxPaint;
private volatile Face mFace;
private int mFaceId;
private float mFaceHappiness;
FaceGraphic(GraphicOverlay overlay) {
super(overlay);
mCurrentColorIndex = (mCurrentColorIndex + 1) % COLOR_CHOICES.length;
final int selectedColor = COLOR_CHOICES[mCurrentColorIndex];
mFacePositionPaint = new Paint();
mFacePositionPaint.setColor(selectedColor);
mIdPaint = new Paint();
mIdPaint.setColor(selectedColor);
mIdPaint.setTextSize(ID_TEXT_SIZE);
mBoxPaint = new Paint();
mBoxPaint.setColor(selectedColor);
mBoxPaint.setStyle(Paint.Style.STROKE);
mBoxPaint.setStrokeWidth(BOX_STROKE_WIDTH);
}
void setId(int id) {
mFaceId = id;
}
double m_degree = 0.0;
int m_range_cm = 0;
boolean m_alarm_on = true;
float m_smile_mean = 0.0f;
/**
* Updates the face instance from the detection of the most recent frame. Invalidates the
* relevant portions of the overlay to trigger a redraw.
*/
void updateFace(Face face, double degree, int range_cm, boolean alarm_on, float smile_mean) {
Log.i("TAG", "update face");
mFace = face;
m_degree = degree;
m_range_cm = range_cm;
m_alarm_on = alarm_on;
m_smile_mean = smile_mean;
postInvalidate();
}
/**
* Draws the face annotations for position on the supplied canvas.
*/
@Override
public void draw(Canvas canvas) {
Log.i("TAG", "draw");
canvas.drawText("Degree: " + String.format("%.1f", m_degree), 200, 200, mIdPaint);
canvas.drawText("Range cm: " + String.format("%d", m_range_cm), 200, 150, mIdPaint);
canvas.drawText("Alarm: " + (m_alarm_on ? "on" : "OFF"), 200, 100, mIdPaint);
Face face = mFace;
if (face == null) {
return;
}
// Draws a circle at the position of the detected face, with the face's track id below.
float face_center_x = face.getPosition().x + face.getWidth() / 2;
float face_center_y = face.getPosition().y + face.getHeight() / 2;
float x = translateX(face_center_x);
float y = translateY(face_center_y);
canvas.drawCircle(x, y, FACE_POSITION_RADIUS, mFacePositionPaint);
canvas.drawText("id: " + mFaceId, x + ID_X_OFFSET, y + ID_Y_OFFSET, mIdPaint);
canvas.drawText("happiness: " + String.format("%.2f", face.getIsSmilingProbability()), x, y + ID_Y_OFFSET * 4, mIdPaint);
canvas.drawText("mean happiness: " + String.format("%.2f", m_smile_mean), x, y + ID_Y_OFFSET * 5, mIdPaint);
canvas.drawText("right eye: " + String.format("%.2f", face.getIsRightEyeOpenProbability()), x - ID_X_OFFSET * 4, y - ID_Y_OFFSET * 2, mIdPaint);
canvas.drawText("left eye: " + String.format("%.2f", face.getIsLeftEyeOpenProbability()), x + ID_X_OFFSET * 4, y - ID_Y_OFFSET * 2, mIdPaint);
// Show X and Y upper left face box
canvas.drawText("(x,y): " + String.format("(%.1f, %.1f)", face_center_x, face_center_y), x, y, mIdPaint);
// Draws a bounding box around the face.
float xOffset = scaleX(face.getWidth() / 2.0f);
float yOffset = scaleY(face.getHeight() / 2.0f);
float left = x - xOffset;
float top = y - yOffset;
float right = x + xOffset;
float bottom = y + yOffset;
canvas.drawRect(left, top, right, bottom, mBoxPaint);
}
}
<file_sep>/FaceTrackerBLE/app/src/main/java/io/makeabilitylab/facetrackerble/SoundManager.java
package io.makeabilitylab.facetrackerble;
import android.content.Context;
import android.media.MediaPlayer;
public class SoundManager {
private MediaPlayer m_play_smile;
private MediaPlayer m_play_frown;
public SoundManager(Context context) {
m_play_frown = MediaPlayer.create(context, R.raw.frown);
m_play_smile = MediaPlayer.create(context, R.raw.smile);
}
public boolean isPlaying(){
return m_play_smile.isPlaying() || m_play_frown.isPlaying();
}
public void PlaySmile() {
if (!isPlaying()) {
m_play_smile.seekTo(0);
m_play_smile.start();
}
}
public void PlayFrown() {
if (!isPlaying()) {
m_play_frown.seekTo(0);
m_play_frown.start();
}
}
}
<file_sep>/ArduinoHardwareControl/pins.h
// Pin constants for the board
const int pin_led_red = D8;
const int pin_led_green = D9;
const int pin_led_blue = D14;
// Note that tone can only work with: D0, D1, A0, A1, A4, A5, A6, A7, RX, TX
const int pin_piezo = D0;
const int pin_servo = D12;
const int pin_ultrasonic_trigger = D3;
const int pin_ultrasonic_echo = D4;
<file_sep>/FaceTrackerBLE/app/src/main/java/io/makeabilitylab/facetrackerble/MeanFilter.java
package io.makeabilitylab.facetrackerble;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class MeanFilter {
private int m_size;
private ArrayList<Float> m_values = new ArrayList<Float>();
private float m_initial_value = 0.0f;
public MeanFilter(int size) {
init(size, 0.0f);
}
public MeanFilter(int size, float initial_value) {
init(size, initial_value);
}
private void init(int size, float initial_value) {
m_size = size;
m_initial_value = initial_value;
}
public float Mean(){
float total = 0.0f;
for (Float value : m_values) {
total += value;
}
if (m_values.size() == 0) {
return 0.0f;
}
return total / m_values.size();
}
public float Add(float value) {
m_values.add(value);
// not the most efficient
// circular buffer would be better, whatever.
if (m_values.size() > m_size) {
m_values.remove(0);
}
// sum up all elements
return Mean();
}
}
<file_sep>/ArduinoHardwareControl/MulticolorThreePinLed.h
#include "color.h"
// Class to control a three pin multi color cathode LED
// One pin is connected to each leg of the cathode each through a resistor
class MulticolorThreePinLed
{
public:
MulticolorThreePinLed(int pin_out_red, int pin_out_green, int pin_out_blue);
void Setup();
void SetColor(byte red, byte green, byte blue);
void SetColor(color c, shade s = shade::BRIGHT);
void On();
void Off();
void WriteCathodeLed(byte red, byte green, byte blue);
private:
int m_pin_red = 0;
int m_pin_green = 0;
int m_pin_blue = 0;
byte m_output_red = 0;
byte m_output_green = 0;
byte m_output_blue = 0;
bool m_on = false;
};
<file_sep>/ArduinoHardwareControl/ArduinoHardwareControl.ino
#include "RedBearDuoRequiredManual.h"
#include "ble_config.h"
#include "ble_constants.h"
#include "MulticolorThreePinLed.h"
#include "UltrasonicRangeFinder.h"
#include "pitches.h"
#include "pins.h"
//
// Hardware declarations
//
MulticolorThreePinLed output_led(pin_led_red, pin_led_green, pin_led_blue);
Servo servo;
UltrasonicRangeFinder ultrasonic(pin_ultrasonic_trigger, pin_ultrasonic_echo);
//
// Board LED
//
/*
void SetRGB(byte r, byte g, byte b)
{
RGB.color(r, g, b);
}
*/
void setup() {
Serial.begin(9600);
delay(5000);
Serial.println("Begin Setup");
//RGB.control(true);
// put your setup code here, to run once:
output_led.Setup();
ultrasonic.Setup();
pinMode(pin_piezo, OUTPUT);
/*
pinMode(pin_led_red, OUTPUT);
pinMode(pin_led_green, OUTPUT);
pinMode(pin_led_blue, OUTPUT);
*/
servo.attach(pin_servo);
SetupBle();
}
const byte motor_degree_min = 65;
const byte motor_degree_max = 115;
// 0 to 180
byte degree_previous = 90;
void HardwareControlMoveMotorToPosition(byte degree)
{
if (degree == degree_previous)
{
return;
}
degree_previous = degree;
if (degree < motor_degree_min)
{
degree = motor_degree_min;
}
else if (degree > motor_degree_max)
{
degree = motor_degree_max;
}
Serial.print("Motor: ");
Serial.println(degree);
servo.write(degree);
}
void HardwareControlAlarm()
{
tone(pin_piezo, NOTE_A6, 1000);
output_led.On();
output_led.SetColor(color::BLUE);
delay(1000);
output_led.Off();
}
int current_range_centimeters = 400;
void loop()
{
/*
// put your main code here, to run repeatedly:
float range_centimeters = ultrasonic.RangeCentimeters();
// Print out results
if ( range_centimeters > 400 ) {
//Serial.println("Out of range");
} else {
Serial.print(range_centimeters);
Serial.println(" cm");
}
*/
//current_range_centimeters = range_centimeters;
//Serial.println("loop");
/*
analogWrite(pin_led_red, 255);
analogWrite(pin_led_green, 255);
analogWrite(pin_led_blue, 255);
delay(5000);
//output_led.On();
//delay(2000);
*/
// LED
/*
analogWrite(pin_led_red, 0);
analogWrite(pin_led_green, 0);
analogWrite(pin_led_blue, 0);
delay(5000);
//*/
/*
output_led.On();
output_led.SetColor(color::RED);
//output_led.On();
delay(1000);
output_led.SetColor(color::GREEN);
//output_led.On();
delay(1000);
output_led.SetColor(color::BLUE);
delay(1000);
output_led.Off();
delay(1000);
*/
// Sound
/*
tone(pin_piezo, NOTE_A6, 1000);
delay(1000);
//*/
// Servo
/*
servo.write(0);
delay(10000);
servo.write(90);
delay(10000);
servo.write(180);
delay(10000);
//*/
/*
for (int i = 0; i < 256; i++)
{
Serial.println(i);
analogWrite(pin_piezo, i);
delay(100);
analogWrite(pin_piezo, 0);
delay(100);
}
*/
/*
// notes_length
for (int i = 0; i < 1; i++)
{
Serial.println(notes[i]);
}
noTone(pin_piezo);
*/
//analogWrite(pin_led_red,128);
//output_led.On();
//RGB.color(0, 0, 0);
//delay(500);
//output_led.Off();
//delay(500);
}
// Bel handle
/**
* @brief Connect handle.
*
* @param[in] status BLE_STATUS_CONNECTION_ERROR or BLE_STATUS_OK.
* @param[in] handle Connect handle.
*
* @retval None
*/
void bleConnectedCallback(BLEStatus_t status, uint16_t handle) {
switch (status) {
case BLE_STATUS_OK:
Serial.println("BLE device connected!");
//digitalWrite(BLE_DEVICE_CONNECTED_DIGITAL_OUT_PIN, HIGH);
break;
default: break;
}
}
/**
* @brief Disconnect handle.
*
* @param[in] handle Connect handle.
*
* @retval None
*/
void bleDisconnectedCallback(uint16_t handle) {
Serial.println("BLE device disconnected.");
//digitalWrite(BLE_DEVICE_CONNECTED_DIGITAL_OUT_PIN, LOW);
}
/**
* @brief Callback for receiving data from Android (or whatever device you're connected to).
*
* @param[in] value_handle
* @param[in] *buffer The buffer pointer of writting data.
* @param[in] size The length of writting data.
*
* @retval
*/
int bleReceiveDataCallback(uint16_t value_handle, uint8_t *buffer, uint16_t size) {
if (receive_handle == value_handle)
{
memcpy(receive_data, buffer, RECEIVE_MAX_LEN);
///*
Serial.print("Received data: ");
for (uint8_t index = 0; index < RECEIVE_MAX_LEN; index++)
{
Serial.print(receive_data[index]);
Serial.print(" ");
}
Serial.println(" ");
//*/
// process the data.
if (receive_data[0] == 0x01)
{ //receive the face data
// CSE590 Student TODO
// Write code here that processes the FaceTrackerBLE data from Android
// and properly angles the servo + ultrasonic sensor towards the face
// Example servo code here: https://github.com/jonfroehlich/CSE590Sp2018/tree/master/L06-Arduino/RedBearDuoServoSweep
byte motor_position = receive_data[1];
HardwareControlMoveMotorToPosition(motor_position);
if (receive_data[2] > 0 && current_range_centimeters < 50)
{
HardwareControlAlarm();
}
}
}
return 0;
}
/**
* @brief Timer task for sending status change to client.
* @param[in] *ts
* @retval None
*
* Send the data from either analog read or digital read back to
* the connected BLE device (e.g., Android)
*/
static void bleSendDataTimerCallback(btstack_timer_source_t *ts) {
// CSE590 Student TODO
// Write code that uses the ultrasonic sensor and transmits this to Android
// Example ultrasonic code here: https://github.com/jonfroehlich/CSE590Sp2018/tree/master/L06-Arduino/RedBearDuoUltrasonicRangeFinder
// Also need to check if distance measurement < threshold and sound alarm
//Serial.println("BLE SendDataTimeCallback");
float range_centimeters = ultrasonic.RangeCentimeters();
int range_cm = (int) range_centimeters;
current_range_centimeters = range_cm;
Serial.print(range_cm);
Serial.println(" cm");
if (ble.attServerCanSendPacket())
{
send_data[0] = (0x0A);
send_data[1] = highByte(range_cm);
send_data[2] = lowByte(range_cm);
ble.sendNotify(send_handle, send_data, SEND_MAX_LEN);
}
// Restart timer.
ble.setTimer(ts, _sendDataFrequency);
ble.addTimer(ts);
}
<file_sep>/ArduinoHardwareControl/color.cpp
#include "application.h"
#include "color.h"
String color_name[color::COLOR_COUNT] =
{
"off",
"red",
"orange",
"yellow",
"chartreuse",
"green",
"aquamarine",
"cyan",
"azure",
"blue",
"violet",
"magenta",
"rose",
"white"
};
byte color_values[color::COLOR_COUNT][3] =
{
{0, 0, 0}, // off
{255, 0, 0}, // red
{255, 127, 0}, // orange
{255, 255, 0}, // yellow
{127, 255, 0}, // chartreuse
{0, 255, 0}, // green
{0, 255, 127}, // aquamarine
{0, 255, 255}, // cyan
{0, 127, 255}, // azure
{0, 0, 255}, // blue
{127, 0, 255}, // violet
{255, 0, 255}, // magenta
{255, 0, 127}, // rose
{255, 255, 255} // white
};
String shade_name[shade::SHADE_COUNT] =
{
"bright",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"dark"
};
void ColorShade(byte &r, byte &g, byte &b, color c, shade s)
{
r = color_values[c][0];
g = color_values[c][1];
b = color_values[c][2];
// bitshift to adjust brightness
r = r >> s;
g = g >> s;
b = b >> s;
}
<file_sep>/ArduinoHardwareControl/RedBearDuoRequiredManual.h
/*
* IMPORTANT: When working with the RedBear Duo, you must have this line of
* code at the top of your program. The default state is SYSTEM_MODE(AUTOMATIC);
* however, this puts the RedBear Duo in a special cloud-based mode that we
* are not using. For our purposes, set SYSTEM_MODE(SEMI_AUTOMATIC) or
* SYSTEM_MODE(MANUAL). See https://docs.particle.io/reference/firmware/photon/#system-modes
*/
//SYSTEM_MODE(MANUAL);
// using bluetooth
#if defined(ARDUINO)
SYSTEM_MODE(SEMI_AUTOMATIC);
#endif
<file_sep>/ArduinoHardwareControl/color.h
/*
enum color : unsigned int;
enum shade : unsigned int;
void ColorShade(byte &r, byte &g, byte &b, color c, shade s);
*/
//
// Color and shade constants
//
enum color
{
OFF = 0,
RED,
ORANGE,
YELLOW,
CHARTREUSE,
GREEN,
AQUAMARINE,
CYAN,
AZURE,
BLUE,
VIOLET,
MAGENTA,
ROSE,
WHITE,
COLOR_COUNT // not an actual color just used to keep count
};
extern String color_name[color::COLOR_COUNT];
// array of colors that can be output
extern byte color_values[color::COLOR_COUNT][3];
// change brightness
// goes from brightest to dimmest
enum shade
{
BRIGHT = 0,
ONE,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
DARK, // 8, bitshifts to 0
SHADE_COUNT // not an actual shade just used to keep count
};
extern String shade_name[shade::SHADE_COUNT];
void ColorShade(byte &r, byte &g, byte &b, color c, shade s);
<file_sep>/ArduinoHardwareControl/UltrasonicRangeFinder.h
class UltrasonicRangeFinder
{
public:
UltrasonicRangeFinder(int pin_trigger, int pin_echo);
void Setup();
float RangeCentimeters();
private:
int m_pin_trigger = 0;
int m_pin_echo = 0;
}
;
<file_sep>/ArduinoHardwareControl/ble_constants.h
#define RECEIVE_MAX_LEN 5 // TODO: change this based on how much data you are sending from Android
#define SEND_MAX_LEN 3
// Must be an integer between 1 and 9 and and must also be set to len(BLE_SHORT_NAME) + 1
#define BLE_SHORT_NAME_LEN 8
// The number of chars should be BLE_SHORT_NAME_LEN - 1. So, for example, if your BLE_SHORT_NAME was 'J', 'o', 'n'
// then BLE_SHORT_NAME_LEN should be 4. If 'M','a','k','e','L','a','b' then BLE_SHORT_NAME_LEN should be 8
// TODO: you must change this name. Otherwise, you will not be able to differentiate your RedBear Duo BLE
// device from everyone else's device in class.
#define BLE_SHORT_NAME 'M','a','k','e','L','a','b'
//
// Will need to define these
//
// Device connected and disconnected callbacks
void bleConnectedCallback(BLEStatus_t status, uint16_t handle);
void bleDisconnectedCallback(uint16_t handle);
static btstack_timer_source_t send_characteristic;
static void bleSendDataTimerCallback(btstack_timer_source_t *ts); // function declaration for sending data callback
int _sendDataFrequency = 200; // 200ms (how often to read the pins and transmit the data to Android)
//
// Other Ble configurations
//
// UUID is used to find the device by other BLE-abled devices
static uint8_t service1_uuid[16] = { 0x71,0x3d,0x00,0x00,0x50,0x3e,0x4c,0x75,0xba,0x94,0x31,0x48,0xf1,0x8d,0x94,0x1e };
static uint8_t service1_tx_uuid[16] = { 0x71,0x3d,0x00,0x03,0x50,0x3e,0x4c,0x75,0xba,0x94,0x31,0x48,0xf1,0x8d,0x94,0x1e };
static uint8_t service1_rx_uuid[16] = { 0x71,0x3d,0x00,0x02,0x50,0x3e,0x4c,0x75,0xba,0x94,0x31,0x48,0xf1,0x8d,0x94,0x1e };
// Define the receive and send handlers
static uint16_t receive_handle = 0x0000; // recieve
static uint16_t send_handle = 0x0000; // send
static uint8_t receive_data[RECEIVE_MAX_LEN] = { 0x01 };
int bleReceiveDataCallback(uint16_t value_handle, uint8_t *buffer, uint16_t size); // function declaration for receiving data callback
static uint8_t send_data[SEND_MAX_LEN] = { 0x00 };
// Define the configuration data
static uint8_t adv_data[] = {
0x02,
BLE_GAP_AD_TYPE_FLAGS,
BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE,
BLE_SHORT_NAME_LEN,
BLE_GAP_AD_TYPE_SHORT_LOCAL_NAME,
BLE_SHORT_NAME,
0x11,
BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_COMPLETE,
0x1e,0x94,0x8d,0xf1,0x48,0x31,0x94,0xba,0x75,0x4c,0x3e,0x50,0x00,0x00,0x3d,0x71
};
void SetupBle()
{
// Initialize ble_stack.
ble.init();
// Register BLE callback functions
ble.onConnectedCallback(bleConnectedCallback);
ble.onDisconnectedCallback(bleDisconnectedCallback);
//lots of standard initialization hidden in here - see ble_config.cpp
configureBLE();
// Set BLE advertising data
ble.setAdvertisementData(sizeof(adv_data), adv_data);
// Register BLE callback functions
ble.onDataWriteCallback(bleReceiveDataCallback);
// Add user defined service and characteristics
ble.addService(service1_uuid);
receive_handle = ble.addCharacteristicDynamic(service1_tx_uuid, ATT_PROPERTY_NOTIFY|ATT_PROPERTY_WRITE|ATT_PROPERTY_WRITE_WITHOUT_RESPONSE, receive_data, RECEIVE_MAX_LEN);
send_handle = ble.addCharacteristicDynamic(service1_rx_uuid, ATT_PROPERTY_NOTIFY, send_data, SEND_MAX_LEN);
// BLE peripheral starts advertising now.
ble.startAdvertising();
Serial.println("BLE start advertising.");
// Start a task to check status of the pins on your RedBear Duo
// Works by polling every X milliseconds where X is _sendDataFrequency
send_characteristic.process = &bleSendDataTimerCallback;
ble.setTimer(&send_characteristic, _sendDataFrequency);
ble.addTimer(&send_characteristic);
}
<file_sep>/ArduinoHardwareControl/MulticolorThreePinLed.cpp
// need to include application.h in .cpp files
#include "application.h"
#include "MulticolorThreePinLed.h"
MulticolorThreePinLed::MulticolorThreePinLed(int pin_red, int pin_green, int pin_blue) :
m_pin_red(pin_red),
m_pin_green(pin_green),
m_pin_blue(pin_blue)
{
}
void MulticolorThreePinLed::Setup()
{
pinMode(m_pin_red, OUTPUT);
pinMode(m_pin_green, OUTPUT);
pinMode(m_pin_blue, OUTPUT);
Off();
}
void MulticolorThreePinLed::SetColor(color c, shade s)
{
byte r, g, b;
ColorShade(r, g, b, c, s);
SetColor(r, g, b);
}
void MulticolorThreePinLed::SetColor(byte red, byte green, byte blue)
{
// assume that LED is a cathode
m_output_red = red;
m_output_green = green;
m_output_blue = blue;
if (m_on)
{
On();
}
}
void MulticolorThreePinLed::On()
{
m_on = true;
//Serial.println("on");
WriteCathodeLed(m_output_red, m_output_green, m_output_blue);
}
void MulticolorThreePinLed::Off()
{
m_on = false;
//Serial.println("off");
WriteCathodeLed(0, 0, 0);
}
void MulticolorThreePinLed::WriteCathodeLed(byte red, byte green, byte blue)
{
analogWrite(m_pin_red, 255 - red);
analogWrite(m_pin_green, 255 - green);
analogWrite(m_pin_blue, 255 - blue);
}
<file_sep>/ArduinoHardwareControl/UltrasonicRangeFinder.cpp
#include "application.h"
#include "UltrasonicRangeFinder.h"
UltrasonicRangeFinder::UltrasonicRangeFinder(int pin_trigger, int pin_echo) :
m_pin_trigger(pin_trigger),
m_pin_echo(pin_echo)
{
}
void UltrasonicRangeFinder::Setup()
{
pinMode(m_pin_trigger, OUTPUT);
digitalWrite(m_pin_trigger, LOW);
pinMode(m_pin_echo, INPUT);
}
float UltrasonicRangeFinder::RangeCentimeters()
{
unsigned long t1;
unsigned long t2;
unsigned long pulse_width;
float cm;
float inches;
// Hold the trigger pin high for at least 10 us
digitalWrite(m_pin_trigger, HIGH);
delayMicroseconds(10);
digitalWrite(m_pin_trigger, LOW);
// Wait for pulse on echo pin
while ( digitalRead(m_pin_echo) == 0 );
// Measure how long the echo pin was held high (pulse width)
// Note: the micros() counter will overflow after ~70 min
t1 = micros();
while ( digitalRead(m_pin_echo) == 1);
t2 = micros();
pulse_width = t2 - t1;
// Calculate distance in centimeters and inches. The constants
// are found in the datasheet, and calculated from the assumed speed
// of sound in air at sea level (~340 m/s).
// Datasheet: https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf
cm = pulse_width / 58.0;
inches = pulse_width / 148.0;
// The HC-SR04 datasheet recommends waiting at least 60ms before next measurement
// in order to prevent accidentally noise between trigger and echo
// See: https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf
delay(60);
return cm;
}
| 1b2bbf9d3a6346062f41075a7d9e94b3307b9a42 | [
"Java",
"C",
"C++"
]
| 13 | Java | wandyezj/ArduinoFaceTracker | 60f216fd6b6d7a03d3e19bafd12fe387c2fefd08 | 6b58de8ff8dc87ea22a0f958e218dc4faf164cf2 |
refs/heads/master | <repo_name>TuomasMoilanen/Esports-Site<file_sep>/antin koodi/tournament page/tournament_script.js
function hideShow(el_id){
clearStages();
var el=document.getElementById(el_id);
if(el_id.style.display!="none"){
el_id.style.display="none";
}else{
el_id.style.display="";
}
}
function toggleWeeks(el_id){
clearStages();
clearWeeks();
var el=document.getElementById(el_id);
el_id.style.display="";
}
function clearStages() {
var x = document.getElementsByClassName("stages");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
}
function clearWeeks() {
var x = document.getElementsByClassName("weeks");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
}
| e6e1f88a375ebef82106f4419cac86e40f5e281d | [
"JavaScript"
]
| 1 | JavaScript | TuomasMoilanen/Esports-Site | 32bd275e0076a7fc4dabf98422161cae59bb7081 | 8389c869f51f66de701f3d9ce131554c097996bd |
refs/heads/master | <repo_name>danielrsouza/calculadoraCerveja<file_sep>/app/src/main/java/com/example/calculadoraDeCerveja/BeerItemAdapter.kt
package com.example.calculadoraDeCerveja
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class BeerItemAdapter(private val context: Context, private val beerList: List<BeerItemModel>) :RecyclerView.Adapter<BeerItemAdapter.ViewHolder>(){
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var beerMarca : TextView = view.findViewById(R.id.marca)
var beerValor : TextView = view.findViewById(R.id.valor)
var beerTamanho : TextView = view.findViewById(R.id.tamanho)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.beer_item, parent, false)
return ViewHolder(itemView)
}
override fun getItemCount(): Int {
return beerList.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val beerItem = beerList[position]
holder.beerMarca.setText("Marca: "+beerItem.beerMarca)
holder.beerValor.setText("R$ "+beerItem.beerValor.toString())
holder.beerTamanho.setText("Tamanho: "+beerItem.beerTamanho.toString() + " ML")
}
}<file_sep>/app/src/main/java/com/example/calculadoraDeCerveja/Beer.kt
package com.example.calculadoraDeCerveja
class Beer(id: Int? = null, marcaBeer: String, valorBeer: Double, tamanhoBeer: Int) {
var marca = marcaBeer
var valor = valorBeer
var tamanho = tamanhoBeer
}<file_sep>/app/src/main/java/com/example/calculadoraDeCerveja/DBHelper.kt
package com.example.calculadoraDeCerveja
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
private val DB_NAME = "beer_db"
class DBHelper (context: Context): SQLiteOpenHelper(context, DB_NAME, null, 1) {
val itensList: List<BeerItemModel>
get(){
val beerItens = ArrayList<BeerItemModel>()
val selectQuery = "SELECT * FROM " + BeerItemModel.BEER_LIST_NAME
val db = this.writableDatabase
val cursor = db.rawQuery(selectQuery, null)
if (cursor.moveToFirst()) {
do{
val beerItem = BeerItemModel()
beerItem.beerId = cursor.getInt(cursor.getColumnIndex(BeerItemModel.BEER_ID_COLUMN))
beerItem.beerMarca = cursor.getString(cursor.getColumnIndex(BeerItemModel.BEER_MARCA_COLUMN))
beerItem.beerValor = cursor.getDouble(cursor.getColumnIndex(BeerItemModel.BEER_VALOR_COLUMN))
beerItem.beerTamanho = cursor.getInt(cursor.getColumnIndex(BeerItemModel.BEER_TAMANHO_COLUMN))
beerItens.add(beerItem)
} while (cursor.moveToNext())
}
db.close()
return beerItens
}
override fun onCreate(db: SQLiteDatabase) {
db.execSQL(BeerItemModel.CREATE_TABLE)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("DROP TABLE IF EXISTS " + BeerItemModel.BEER_LIST_NAME)
onCreate(db)
}
fun insertBeerItem(beer: Beer): Long {
val db = this.writableDatabase
val values = ContentValues()
values.put(BeerItemModel.BEER_MARCA_COLUMN, beer.marca)
values.put(BeerItemModel.BEER_VALOR_COLUMN, beer.valor)
values.put(BeerItemModel.BEER_TAMANHO_COLUMN, beer.tamanho)
val item = db.insert(BeerItemModel.BEER_LIST_NAME, null, values)
db.close()
return item
}
fun getBeerItem(item: Long) : BeerItemModel{
val db = readableDatabase
val cursor = db.query(BeerItemModel.BEER_LIST_NAME, arrayOf(BeerItemModel.BEER_ID_COLUMN,
BeerItemModel.BEER_MARCA_COLUMN, BeerItemModel.BEER_VALOR_COLUMN, BeerItemModel.BEER_TAMANHO_COLUMN
), BeerItemModel.BEER_ID_COLUMN + "=?", arrayOf(item.toString()), null, null, null, null)
cursor?.moveToFirst()
val beer = Beer(
cursor!!.getInt(cursor.getColumnIndex(BeerItemModel.BEER_ID_COLUMN)),
cursor.getString(cursor.getColumnIndex(BeerItemModel.BEER_MARCA_COLUMN)),
cursor.getDouble(cursor.getColumnIndex(BeerItemModel.BEER_VALOR_COLUMN)),
cursor.getInt(cursor.getColumnIndex(BeerItemModel.BEER_TAMANHO_COLUMN))
)
val beerItem = BeerItemModel(
beer
)
cursor.close()
return beerItem
}
fun deleteBeerItem(beerItemModel: BeerItemModel) {
val db = writableDatabase
db.delete(BeerItemModel.BEER_LIST_NAME, BeerItemModel.BEER_ID_COLUMN + " = ?",
arrayOf(beerItemModel.beerId.toString()))
db.close()
}
fun deleteAllBeer()
{
val db = writableDatabase
db.delete(BeerItemModel.BEER_LIST_NAME, BeerItemModel.BEER_ID_COLUMN + " > ?",
arrayOf("0"))
db.close()
}
fun updateBeerItem(beerItemModel: BeerItemModel): Int {
val db = this.writableDatabase
val values = ContentValues()
values.put(BeerItemModel.BEER_MARCA_COLUMN, beerItemModel.beerMarca)
values.put(BeerItemModel.BEER_VALOR_COLUMN, beerItemModel.beerValor)
values.put(BeerItemModel.BEER_TAMANHO_COLUMN, beerItemModel.beerTamanho)
return db.update(BeerItemModel.BEER_LIST_NAME, values, BeerItemModel.BEER_ID_COLUMN + " = ?",
arrayOf(beerItemModel.beerId.toString()))
}
}<file_sep>/app/src/main/java/com/example/calculadoraDeCerveja/BeerItemModel.kt
package com.example.calculadoraDeCerveja
class BeerItemModel {
var beerId: Int = 0;
var beerMarca: String? = null
var beerValor: Double = 0.0
var beerTamanho: Int = 0
constructor()
constructor(beer: Beer) {
this.beerMarca = beer.marca
this.beerValor = beer.valor
this.beerTamanho = beer.tamanho
}
companion object{
val BEER_LIST_NAME = "beer_list"
val BEER_ID_COLUMN = "id"
val BEER_MARCA_COLUMN = "marca"
val BEER_VALOR_COLUMN = "valor"
val BEER_TAMANHO_COLUMN = "tamanho"
val CREATE_TABLE = (
"CREATE TABLE "
+ BEER_LIST_NAME + "("
+ BEER_ID_COLUMN + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ BEER_MARCA_COLUMN + " TEXT,"
+ BEER_VALOR_COLUMN + " DOUBLE,"
+ BEER_TAMANHO_COLUMN + " INTEGER"
+ ")" )
}
}<file_sep>/app/src/main/java/com/example/calculadoraDeCerveja/MainActivity.kt
package com.example.calculadoraDeCerveja
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private var coordinatorLayout: CoordinatorLayout? = null
private var recyclerView: RecyclerView? = null
private var db: DBHelper? = null
private var beersList = ArrayList<BeerItemModel>()
private var adapter : BeerItemAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById<View>(R.id.toolbar) as Toolbar
toolbar.setTitleTextColor(Color.WHITE);
setSupportActionBar(toolbar);
controle()
calculoCerveja(beersList)
}
// Controla o que vai aparecer
private fun controle() {
coordinatorLayout = findViewById(R.id.layout_main)
recyclerView = findViewById(R.id.recycler_main)
db = DBHelper(this)
val fab = findViewById<View>(R.id.fab) as FloatingActionButton
fab.setOnClickListener {
showDialog(false, null, -1)
}
beersList.addAll(db!!.itensList)
adapter = BeerItemAdapter(this, beersList)
val layoutManager = LinearLayoutManager(applicationContext)
recyclerView!!.layoutManager = layoutManager
recyclerView!!.itemAnimator = DefaultItemAnimator()
recyclerView!!.adapter = adapter
//Funcao de clique longo
recyclerView!!.addOnItemTouchListener(
ItemLongPressListener(
this,
recyclerView!!,
object : ItemLongPressListener.ClickListener {
override fun onClick(view: View, position: Int) {}
override fun onLongClick(view: View?, position: Int) {
showActionsDialog(position)
}
}
))
calculoCerveja(beersList)
}
// Mostra as ações ao ter um clique longo
private fun showActionsDialog(position: Int) {
val options = arrayOf<CharSequence>(getString(R.string.editar),
getString(R.string.excluir), getString(R.string.excluirTudo))
val builder = AlertDialog.Builder(this)
builder.setTitle(getString(R.string.tituloOpcao))
builder.setItems(options){
dialog, itemIndex ->
when(itemIndex) {
0 -> showDialog(true, beersList[position], position)
1 -> deleteBeerItem(position)
2 -> deleteAllItens()
else -> Toast.makeText(applicationContext, getString(R.string.toastError), Toast.LENGTH_SHORT).show()
}
}
builder.show()
}
// Delete uma cerveja
private fun deleteBeerItem(position: Int) {
db!!.deleteBeerItem(beersList[position])
beersList.removeAt(position)
adapter!!.notifyItemRemoved(position)
calculoCerveja(beersList)
}
// Deleta todas as cervejas
private fun deleteAllItens() {
db!!.deleteAllBeer()
beersList.removeAll(beersList)
adapter!!.notifyDataSetChanged()
calculoCerveja(beersList)
}
// Funcao que cria o dialog para inserir uma beer
private fun showDialog(isUpdate: Boolean, beerItemModel: BeerItemModel?, position: Int) {
val layoutInflaterAndroid = LayoutInflater.from(applicationContext)
val view = layoutInflaterAndroid.inflate(R.layout.beer_dialog, null)
val userInput = AlertDialog.Builder(this@MainActivity)
userInput.setView(view)
val titulo = view.findViewById<TextView>(R.id.titulo)
val marca = view.findViewById<EditText>(R.id.editTextMarca);
val valor = view.findViewById<EditText>(R.id.editTextValor);
val tamanho = view.findViewById<EditText>(R.id.editTextMedida);
titulo.text = if (!isUpdate) getString(R.string.adiciona) else getString(R.string.editar)
//Evita clicarmos fora e fechar o dialog
userInput.setCancelable(false)
.setPositiveButton(if(isUpdate) getString(R.string.atualizar) else getString(R.string.salvar)) {dialogBox, id->}
.setNegativeButton(getString(R.string.cancelar)){dialogBox, id->dialogBox.cancel()}
val alertDialog = userInput.create()
alertDialog.show()
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(View.OnClickListener {
if (TextUtils.isEmpty(marca.text.toString())){
Toast.makeText(this@MainActivity, getString(R.string.toastMarca), Toast.LENGTH_SHORT).show()
return@OnClickListener
} else if (TextUtils.isEmpty(valor.text.toString())) {
Toast.makeText(this@MainActivity, "O valor não pode ser vazio", Toast.LENGTH_SHORT).show()
return@OnClickListener
} else if (TextUtils.isEmpty(tamanho.text.toString())) {
Toast.makeText(this@MainActivity, "O tamanho não pode ser vazio", Toast.LENGTH_SHORT).show()
return@OnClickListener
}else {
alertDialog.dismiss()
}
var beer = Beer(null, marca.text.toString(), valor.text.toString().toDouble(), tamanho.text.toString().toInt())
createBeerItem(beer)
})
calculoCerveja(beersList)
}
// Função que cria um Beer Item
private fun createBeerItem(beer:Beer) {
val item = db!!.insertBeerItem(beer)
val novoItem = db!!.getBeerItem(item)
if (novoItem != null) {
beersList.add(0, novoItem)
adapter!!.notifyDataSetChanged()
}
}
// Lógica de calculo da cerveja mais em conta
private fun calculoCerveja(beerList: ArrayList<BeerItemModel>) {
var melhorPreco = 999.0
if (beersList.size == 0) {
marcaEmConta.text = ""
precoEmConta.text = ""
tamanhoEmConta.text = ""
diferenca.text = ""
}
for( beer in beerList) {
val mediaPreco = (beer.beerValor/beer.beerTamanho) * 1000
melhorPreco = mediaPreco
marcaEmConta.text = "Marca: " + beer.beerMarca
precoEmConta.text = "Preço: R$ " + beer.beerValor.toString()
tamanhoEmConta.text = "Tamanho: " + beer.beerTamanho.toString() + " ML"
diferenca.text = "Preço do Litro: " + "%.2f".format(melhorPreco.toString().toDouble()) + " L"
if (mediaPreco < melhorPreco) {
melhorPreco = mediaPreco
marcaEmConta.text = "Marca: " + beer.beerMarca
precoEmConta.text = "Preço: R$ " + beer.beerValor.toString()
tamanhoEmConta.text = "Tamanho: " + beer.beerTamanho.toString() + " ML"
diferenca.text = "Preço do Litro: " + "%.2f".format(melhorPreco.toString().toDouble()) + " L"
}
}
}
private fun setSupportActionBar(toolbar: Toolbar) {}
}
| 3080c2ec9951ec3fa5ba51cc08a52041819308c2 | [
"Kotlin"
]
| 5 | Kotlin | danielrsouza/calculadoraCerveja | bf3d2cd381b7a959a26bda33a6e19ce9c6f0e190 | 30de49a31d5142cea542e5ebc750b4e9933686df |
refs/heads/master | <repo_name>DSBro/TS3-banlist<file_sep>/app/sqlite.php
<?php
class SQLite_core{
public function __construct()
{
$this->positioncontrol = 1;
}
public function SQLite3_Create_File(){
$this->SQLite3_File = new PDO('sqlite:../app/data/data.sqlite3');
$this->SQLite3_File->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
public function SQLite3_Create_Table(){
$this->SQLite3_File->exec(
"CREATE TABLE IF NOT EXISTS TS3DATA(
id INTEGER PRIMARY KEY,
banid INTEGER,
ip TEXT,
name TEXT,
uid TEXT,
lastnickname TEXT,
created TEXT,
duration TEXT,
invokername TEXT,
invokercldbid INTEGER,
invokeruid TEXT,
reason TEXT,
enforcements INTEGER)");
}
public function SQLite3_Delete_Table(){
$this->SQLite3_File_Delete = $this->SQLite3_File->query('DROP TABLE TS3DATA');
}
public function SQLite3_Count_ServerClients($data){
$this->countserverbans = cout($data);
}
public function SQLite3_Count_FileClients(){
$this->SQLite3_File_Query_Result = $this->SQLite3_File->query('SELECT * FROM TS3DATA');
$rows = $this->SQLite3_File_Query_Result->fetchAll();
$this->countfilebans = count($rows);
}
public function SQLite3_Save_New_Client($data){
$this->SQLite3_File_Query_Control_Result = $this->SQLite3_File->query('SELECT banid FROM TS3DATA');
$FILEDATA=$this->SQLite3_File_Query_Control_Result->fetchAll();
$SERVERDATA=$data;
$this->SQLite3_Count_ServerClients($data);
/*for($x=0;$x!=$this->countserverbans;$x++){
if($FILEDATA[$x][0]){
}else{
Přidáme nový záznam
}
}*/
}
public function SQLite3_Save_Data($data){
$this->SQLite3_Count_FileClients();
if(!$this->countfilebans == 0){
}else{
$this->SQLite3_Delete_Table();
$this->SQLite3_Create_Table();
$this->SQLite3_Data_Save_First($data);
}
}
public function SQLite3_Data_Save_First($data){
$this->insert = "INSERT INTO TS3DATA (banid, ip, name, uid, lastnickname, created, duration, invokername, invokercldbid, invokeruid, reason, enforcements) VALUES (:banid, :ip, :name, :uid, :lastnickname, :created, :duration, :invokername, :invokercldbid, :invokeruid, :reason, :enforcements)";
$this->prepare = $this->SQLite3_File->prepare($this->insert);
$this->prepare->bindParam(':banid', $banid);
$this->prepare->bindParam(':ip', $ip);
$this->prepare->bindParam(':name', $name);
$this->prepare->bindParam(':uid', $uid);
$this->prepare->bindParam(':lastnickname', $lastnickname);
$this->prepare->bindParam(':created', $created);
$this->prepare->bindParam(':duration', $duration);
$this->prepare->bindParam(':invokername', $invokername);
$this->prepare->bindParam(':invokercldbid', $invokercldbid);
$this->prepare->bindParam(':invokeruid', $invokeruid);
$this->prepare->bindParam(':reason', $reason);
$this->prepare->bindParam(':enforcements', $enforcements);
foreach ($data as $datainsert) {
$banid = $datainsert['banid'];
$ip = $datainsert['ip'];
$name = $datainsert['name'];
$uid = $datainsert['uid'];
$lastnickname = $datainsert['lastnickname'];
$created = $datainsert['created'];
$duration = $datainsert['duration'];
$invokername = $datainsert['invokername'];
$invokercldbid = $datainsert['invokercldbid'];
$invokeruid = $datainsert['invokeruid'];
$reason = $datainsert['reason'];
$enforcement = $datainsert['enforcements'];
$this->prepare->execute();
}
}
public function SQLite3_View_Data(){
echo "<font class=numberofbans><center>Bans: ".$this->countfilebans."</center></font><br>";
$this->SQLite3_File_Query_Result = $this->SQLite3_File->query('SELECT * FROM TS3DATA');
foreach ($this->SQLite3_File_Query_Result as $dataview){
if (empty($dataview['reason'])) {
$reason = "The reason was not given";
} else {
$reason = $dataview['reason'];
}
if (empty($dataview['uid'])) {
} else {
$uid = $dataview['uid'];
}
if (empty($dataview['ip'])) {
} else {
$ip = $dataview['ip'];
}
if ($dataview['lastnickname']==":null") {
$nickname = "Asshole";
} else {
$nickname = $dataview['lastnickname'];
}
if ($dataview['duration'] == 0) {
$expires = "Permanent";
$stav = "<font color='red'>Banned</font>";
} else {
$expires = date('d-m-Y H:i:s', $dataview['created'] + $dataview['duration']);
if(date('d-m-Y H:i:s') > $expires){
$stav = "<font color='green'>Unbanned</font>";
}else{
$stav = "<font color='red'>Banned</font>";
}
}
echo '<tr id=row>';
echo '<td>' . $dataview['banid'] . '</td>';
echo '<td>' . $dataview['lastnickname'] . '</td>';
if(empty($ip)){
echo '<td>' . $uid . '</td>';
}else{
echo '<td>' . $ip . '/' . $uid . '</td>';
}
echo '<td>' . $expires . '</td>';
echo '<td>' . $dataview['invokername'] . '</td>';
echo '<td>' . $reason . '</td>';
echo '<td>' . $stav . '</td>';
echo '</tr>';
}
}
}
?>
<file_sep>/app/controller.php
<?php
/**
* Created by PhpStorm.
* User: zdene
* Date: 23.02.2018
* Time: 12:00
*/
require_once ("core.php");
class TeamSpeak3_Controller{
public $TeamSpeak3_Core;
public function __construct()
{
}
public function TeamSpeak3_Banlist_Controller(){
$this->TeamSpeak3_Core = new TeamSpeak3_Core();
$this->TeamSpeak3_Core->TeamSpeak3_Core_Banlist();
}
}
?><file_sep>/README.md
# TeamSpeak3_Banlist
## 01.09.2018 NEW FIXED AND OPTIMIZED VERSION!
Teamspeak3 Banlist with Administration in TeamSpeak 3 PHP Framework.
Graphically Designed by [DAWE Graphics](https://github.com/DV2013DAWE).
### Tutorial
* Install SQLite3
Debian/Ubuntu:
`apt-get install php-sqlite3`
Fedora:
`dnf install php-sqlite3`
ArchLinux:
`pacman -S php-sqlite3`
Windows:
[How To Download & Install ](http://www.sqlitetutorial.net/download-install-sqlite)
* Edit the data in */cfg/config.ini*
* Import files with folders into your web server's storage
* Folder *cfg* , *app* and *lib* must be placed under the folder in which the banlist. For example, the site (www/) will be in */var/www/banlist/* so the contents of the *cfg* must be in the */var/www/cfg/* (Safety reasons!)
* Grant permissions
`chgrp www-data app/data`
`chmod g+w app/data`
***
### Next release
* Banlist administration
* Delete/Add bans
* More information for each record
* I recommend using a newer version! [All Version](https://github.com/ArrayMy/TeamSpeak3_Banlist/releases)
***
### Display

<file_sep>/cfg/config.ini
teamspeak_ip = "IP"
teamspeak_port = "PORT"
teamspeak_server_port = "SPORT"
serverquery_username = username
serverquery_password = <PASSWORD>
<file_sep>/app/core.php
<?php
require_once("_DIR_ . \"/../../lib/libraries/TeamSpeak3/TeamSpeak3.php");
require_once("serverquery.php");
require_once("sqlite.php");
class TeamSpeak3_Core
{
public $TeamSpeak3_ServerQuery;
public $ServerQuery_BanList_data;
public $data;
public function __construct(){}
public function TeamSpeak3_Core_Save(){
$Sqlite = new SQLite_core();
$Sqlite->SQLite3_Create_File();
$Sqlite->SQLite3_Create_Table();
$Sqlite->SQLite3_Save_Data();
}
public function TeamSpeak3_Core_Banlist(){
$TeamSpeak3_ServerQuery_check = new ServerQuery();
$TeamSpeak3_ServerQuery_check->ServerQuery_Connect();
$TeamSpeak3_ServerQuery_check->ServerQuery_Banlist();
$Sqlite = new SQLite_core();
$Sqlite->SQLite3_Create_File();
$Sqlite->SQLite3_Create_Table();
$Sqlite->SQLite3_Save_Data($TeamSpeak3_ServerQuery_check->data);
$Sqlite->SQLite3_View_Data();
}
}
?><file_sep>/www/index.php
<?php
require_once("_DIR_ . \"/../../app/controller.php");
?>
<html>
<head>
<meta charset=UTF8>
<title>BANLIST</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link href="https://fonts.googleapis.com/css?family=Barlow" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Anton" rel="stylesheet">
<link rel="icon" type="image/png" href="css/favicon.png" />
<script src="js/jquery-3.3.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<center><br><h1>Banlist</h1></center>
<table>
<tr class="prvni">
<th>ID</th>
<th>Nickname</th>
<th>IP/UID</th>
<th>Duration</th>
<th>Admin</th>
<th>Reason</th>
<th>Status</th>
</tr>
<?php
$controller = new TeamSpeak3_Controller();
$controller->TeamSpeak3_Banlist_Controller();
?>
</body>
<footer>
Graphically Designed by
<a class="dave" href=https://github.com/DV2013DAWE> DAWE Graphics</a><br>
Developed by
<a class="dave" href=https://github.com/ArrayMy>ArrayMy</a><br>
</footer>
</html>
| 0c43a0fdbec341b4e77206be64f4767438b73d37 | [
"Markdown",
"PHP",
"INI"
]
| 6 | PHP | DSBro/TS3-banlist | 4b9f6f1254228dc00ef9a7d030b2898af1af1ca6 | cee49286f8effc95e3228100eccec18d336a0a4f |
refs/heads/master | <file_sep>import React from 'react';
import { NavLink } from 'react-router-dom';
class ThemeSection extends React.Component {
constructor(props) {
super(props);
const pathToAssets = require.context(`../../assets/images/`, true);
this.sectionStyle = {
backgroundImage: `url(${pathToAssets(`./${this.props.image}`)})`
}
}
handleClick() {
}
render() {
return (
<React.Fragment>
{/* <NavLink to={`/quizz/${this.props.id}`}> */}
<section className='section-theme' id={`theme-${this.props.id}`} onClick={() => this.handleClick()} data-scroll data-scroll-call="anim-background">
<div className='section-theme__background-wrapper js-background-wrapper' style={this.sectionStyle}></div>
<h1 className="section-theme__title" data-scroll data-scroll-speed="1" data-scroll-call="anim-title">
{this.props.title}
</h1>
</section>
{/* </NavLink> */}
</React.Fragment>
)
}
}
export default ThemeSection;
<file_sep>import React, {useEffect} from 'react';
import { NavLink, Redirect } from 'react-router-dom';
import {Context} from '../provider/Provider';
import DifficultyComponent from '../components/DifficultyComponent';
import TimeModule from '../modules/TimerModule';
import AnimOpacity from '../modules/AnimOpacity';
import { TweenLite, Power3 } from 'gsap';
let timeModule;
const DURATIONMAX = 20;
const Quizz = (props) => {
const context = React.useContext(Context);
const id = props.match.params.quizzId;
const pathToAssets = require.context(`../../assets/images/`, true);
const [questionId, setQuestionId] = React.useState(0);
const [duration, setDuration] = React.useState(0);
const [points, setPoints] = React.useState([]);
const [allowRedirect, setAllowRedirect] = React.useState(false);
const currentTheme = context.state.currentTheme;
const currentThemeQuestion = context.state.currentThemeQuestions;
const difficulty = context.state.difficulty;
let interval;
let style = {};
if (currentTheme) {
style = {
backgroundImage: `url(${pathToAssets(`./${currentTheme.image}`)})`,
}
}
const updateTime = () => {
interval = setInterval(() => {
setDuration(duration => duration + 1);
}, 1000);
}
useEffect(() => {
if (!context.state.difficulty) return;
context.dispatch({type: 'getCurrentTheme', id});
context.dispatch({type: 'getCurrentThemeQuestions', id});
let header = document.querySelector('.js-header-quizz');
new AnimOpacity(document.querySelectorAll('.js-opacity')).transitionIn();
TweenLite.to(header, 1, { height: '35%', ease: Power3.easeInOut });
setTimeout(() => {
timeModule = new TimeModule(DURATIONMAX);
updateTime();
}, 1000);
return () => context.dispatch({type: 'resetDifficulty'})
}, [context.state.difficulty]);
useEffect(() => {
if (duration !== DURATIONMAX) return;
verifyResponse('');
nextQuestion();
}, [duration]);
useEffect(() => {
if (points.length !== 10) return;
context.dispatch({type: 'setScore', id, points});
clearInterval(interval);
setPoints([]);
let header = document.querySelector('.js-header-quizz');
new AnimOpacity(document.querySelectorAll('.js-opacity')).transitionOut();
TweenLite.to(header, 1, { height: '100%', ease: Power3.easeInOut });
setTimeout(() => {
setAllowRedirect(true);
}, 1000);
}, [points.length]);
const verifyResponse = (response) => {
if (response === currentThemeQuestion.quizz[difficulty][questionId].réponse) {
setPoints(points => { points.push(1); return points });
} else {
setPoints(points => { points.push(0); return points });
}
}
const nextQuestion = () => {
setDuration(0);
timeModule.restart();
if (currentTheme && questionId >= currentThemeQuestion.quizz[difficulty].length - 1) return;
setQuestionId(questionId => questionId + 1);
}
const handleResponse = (e) => {
verifyResponse(e.target.innerHTML);
nextQuestion();
e.preventDefault();
}
return (
<section className="page-quizz">
{context.state.difficulty ? (
<React.Fragment>
<header className="header-quizz js-header-quizz" style={currentTheme && style}>
<h1 className="header-quizz__heading js-opacity">Question {currentThemeQuestion && currentThemeQuestion.quizz[difficulty][questionId].id}</h1>
</header>
<section className="section-question js-opacity">
<div className="section-question__timer js-timer">{duration}</div>
<h2 className="section-question__subheading">{currentTheme && currentTheme.title}</h2>
<div className="section-question__question">
<p>{currentThemeQuestion && currentThemeQuestion.quizz[difficulty][questionId].question}</p>
</div>
<ul className="section-question__list-response">
{currentThemeQuestion && currentThemeQuestion.quizz[difficulty][questionId].propositions.map((response, index) => <li onClick={handleResponse} className="section-question__list-response-item" key={index}>{response}</li>)}
</ul>
<div className="section-question__progress">
{currentThemeQuestion && currentThemeQuestion.quizz[difficulty][questionId].id}/10 - {difficulty}
</div>
<NavLink to={`/`}>
<button className="section-question__leave-button">Quitter</button>
</NavLink>
{allowRedirect && <Redirect to={`/quizz/${id}/results`} />}
</section>
</React.Fragment>
) : (
<DifficultyComponent id={id} title={currentTheme && currentTheme.title}/>
)}
</section>
)
}
export default Quizz;
<file_sep>import React, {useEffect} from 'react';
import { NavLink } from 'react-router-dom';
import {Context} from '../provider/Provider';
import AnimOpacity from '../modules/AnimOpacity';
import AnimTitlesModule from '../modules/AnimTitlesModule';
import { TweenLite, Power3 } from 'gsap';
const Results = (props) => {
const context = React.useContext(Context);
const id = props.match.params.quizzId;
const pathToAssets = require.context(`../../assets/images/`, true);
const currentQuestion = context.state.currentTheme;
let style = {};
if (currentQuestion) {
style = {
backgroundImage: `url(${pathToAssets(`./${currentQuestion.image}`)})`,
}
}
useEffect(() => {
context.dispatch({type: 'getCurrentTheme', id});
context.dispatch({type: 'resetDifficulty'});
let header = document.querySelector('.js-header-results');
let animTitles = new AnimTitlesModule(document.querySelectorAll('.js-anim-title'));
new AnimOpacity(document.querySelectorAll('.js-opacity')).transitionIn();
TweenLite.to(header, 1, { height: '35%', ease: Power3.easeInOut });
setTimeout(() => {
animTitles.transitionIn();
}, 700);
return () => context.dispatch({type: 'resetTheme'});
}, [id]);
return (
<section className="page-results">
<header className="header-results js-header-results" style={style}>
<h1 className="header-results__heading js-opacity">Resultat</h1>
</header>
<section className="section-results js-opacity">
<h2 className="section-results__subheading js-anim-title">{currentQuestion && currentQuestion.title}</h2>
<div className="section-results__results js-anim-title">
<p>{context.state.score.filter(score => score === 1).length}/10</p>
</div>
<NavLink to='/' className="section-results__leave-button">Quitter</NavLink>
<NavLink to={`/quizz/${(parseInt(id) + 1) % 8 }`} className="section-results__next-button">Quizz suivant</NavLink>
</section>
</section>
)
}
export default Results;<file_sep>import {themeData} from '../../assets/data/themeData.js';
import breakingBad from '../../assets/data/breakingBad';
import fifthElement from '../../assets/data/fifthElement';
import gameOfThrones from '../../assets/data/gameOfThrones';
import hungerGames from '../../assets/data/hungerGames';
import jurassicPark from '../../assets/data/jurassicPark';
import marvel from '../../assets/data/marvel';
import princessesDisney from '../../assets/data/princessesDisney';
import starWars from '../../assets/data/starWars';
export const initialState = {
themeList : themeData,
username : null,
difficulty : null,
currentTheme : null,
currentThemeQuestions : null,
score : {}
};
export const Reducer = (state, action) => {
switch (action.type) {
case 'setUsername':
return {...state, username : action.username}
case 'setDifficulty':
return {...state, difficulty : action.difficulty}
case 'resetDifficulty':
return {...state, difficulty : null}
case 'getCurrentTheme':
return {...state, currentTheme : state.themeList.find(theme => theme.id === action.id)}
case 'getCurrentThemeQuestions':
switch (state.currentTheme.json) {
case 'breaking-bad':
return {...state, currentThemeQuestions : breakingBad}
case 'fifth-element':
return {...state, currentThemeQuestions : fifthElement}
case 'game-of-thrones':
return {...state, currentThemeQuestions : gameOfThrones}
case 'hunger-games':
return {...state, currentThemeQuestions : hungerGames}
case 'jurassic-park':
return {...state, currentThemeQuestions : jurassicPark}
case 'marvel':
return {...state, currentThemeQuestions : marvel}
case 'princesses-disney':
return {...state, currentThemeQuestions : princessesDisney}
case 'star-wars':
return {...state, currentThemeQuestions : starWars}
default:
console.log('Sorry, not founded');
};
break;
case 'resetTheme':
return {...state, currentTheme : null};
case 'setScore':
return {...state, score : action.points}
default:
return state;
}
}
<file_sep>import LocomotiveScroll from 'locomotive-scroll';
import AnimTitleModule from './AnimTitleModule';
import AnimBackgroundModule from './AnimBackgroundModule';
class SmoothScrollModule {
constructor() {
this.ui = {
animTitle: document.querySelectorAll('[data-scroll-call="anim-title"]'),
animBackground: document.querySelectorAll('[data-scroll-call="anim-background"]'),
}
this.components = {
animTitle: [],
animBackground: [],
}
this.setup();
}
setup() {
this.setupComponents();
// this.setupSmoothScroll();
// this.setupEventListeners();
}
setupComponents() {
for (let i = 0; i < this.ui.animBackground.length; i++) {
this.components.animBackground.push(new AnimBackgroundModule(this.ui.animBackground[i]));
}
}
setupSmoothScroll(el) {
this.scroll = new LocomotiveScroll({
el: el,
smooth: true,
getDirection: true,
getSpeed: true
});
this.setupEventListeners();
}
setupEventListeners() {
this.scroll.on('scroll', (e) => this.onScrollHandler(e));
this.scroll.on('call', (e, state, object) => this.onCallHandler(e, state, object));
}
onScrollHandler(e) {
}
onCallHandler(e, state, object) {
if (e === 'anim-title') {
let animTitle = new AnimTitleModule(object.el);
this.components.animTitle.push(animTitle);
}
}
scrollTo(target) {
let el = document.querySelector(target);
this.scroll.scrollTo(target);
}
reset() {
this.scroll.init();
this.scroll.start();
}
}
export default SmoothScrollModule;
<file_sep>import { TimelineLite, Power3, TweenLite } from 'gsap';
class AnimTitlesModule {
constructor(els) {
this.els = els;
this.ui = {};
this.setup();
}
setup() {
this.setupSplitText();
this.setupStartingPositions();
}
setupStartingPositions() {
TweenLite.set(this.ui.spans, { y: 100 });
}
setupSplitText() {
this.ui.spans = [];
for (let i = 0; i < this.els.length; i++) {
this.els[i].style.overflow = 'hidden';
let content = this.els[i].innerHTML;
this.els[i].innerHTML = '';
let span = document.createElement('span');
this.ui.spans.push(span);
span.style.display = 'block';
span.innerHTML = content;
this.els[i].appendChild(span);
}
}
setupTween() {
this.timeline = new TimelineLite();
this.timeline.staggerFromTo(this.ui.spans, 1, { y: 100 }, { y: 0, ease: Power3.easeInOut }, 0.1);
}
transitionIn() {
this.timeline = new TimelineLite();
this.timeline.staggerFromTo(this.ui.spans, 1, { y: 100 }, { y: 0, ease: Power3.easeInOut }, 0.1);
}
transitionOut() {
this.timeline = new TimelineLite();
this.timeline.staggerFromTo(this.ui.spans, 1, { y: 0 }, { y: -100, ease: Power3.easeInOut }, 0.1);
}
}
export default AnimTitlesModule;
<file_sep>import React from 'react';
import { TweenLite } from 'gsap';
class CursorComponent extends React.Component {
constructor(props) {
super(props);
this.mousemoveHandler = this.mousemoveHandler.bind(this);
this.state = {
mouseX: 0,
mouseY: 0,
};
this.tweenObj = {
opacity: 0
}
this.setup();
}
setup() {
this.setupEventListeners();
}
setupEventListeners() {
window.addEventListener('mousemove', this.mousemoveHandler)
}
removeEventListerners() {
window.removeEventListener('mousemove', this.mousemoveHandler)
}
mousemoveHandler(e) {
TweenLite.to(this.tweenObj, .5, { opacity: 1 });
this.setState({
mouseX: e.clientX,
mouseY: e.clientY,
opacity: this.tweenObj.opacity
});
}
componentWillUnmount = () => {
this.removeEventListerners();
}
render() {
const style = {
transform: `translate(${this.state.mouseX}px, ${this.state.mouseY}px)`,
opacity: this.state.opacity
}
return (
<div className="cursor-container" data-scroll data-scroll-sticky data-scroll-target=".js-scroll-container">
<div className="cursor" style={style}>
Jouer
</div>
</div>
)
}
}
export default CursorComponent;
<file_sep>import React from 'react';
import {Reducer, initialState} from '../reducer/Reducer';
const Context = React.createContext(initialState);
const Provider = ({children}) => {
const [state, dispatch] = React.useReducer(Reducer, initialState)
return (
<Context.Provider value={{state : state, dispatch: dispatch}}>
{children}
</Context.Provider>
);
}
export {Context, Provider};
<file_sep>export const themeData = [
{
"id": "0",
"title": "Breaking Bad",
"image": "breakingBad_background.jpg",
"json": "breaking-bad"
},
{
"id": "1",
"title": "Game of Thrones",
"image": "gameOfThrones_background.jpg",
"json": "game-of-thrones"
},
{
"id": "2",
"title": "Star Wars",
"image": "starWars_background.jpg",
"json": "star-wars"
},
{
"id": "3",
"title": "Jurassic Park",
"image": "jurassicPark_background.jpg",
"json": "jurassic-park"
},
{
"id": "4",
"title": "Hunger Games",
"image": "hungerGames_background.jpg",
"json": "hunger-games"
},
{
"id": "5",
"title": "Films Marvel",
"image": "marvel_background.jpg",
"json": "marvel"
},
{
"id": "6",
"title": "Le cinquième élément",
"image": "fifthElement_background.jpg",
"json": "fifth-element"
},
{
"id": "7",
"title": "Princesses Disney",
"image": "princessesDisney_background.jpg",
"json": "princesses-disney"
}
]
<file_sep>import { TimelineLite, Linear } from 'gsap';
class TimeModule {
constructor(duration) {
this.duration = duration;
this.el = document.querySelector('.js-timer');
this.setup();
}
setup() {
this.startTime = Date.now();
this.setupTween();
}
setupTween() {
this.timeline = new TimelineLite({ ease: Linear.easeNone });
this.timeline.fromTo(this.el, this.duration, { scaleX: 0 }, { scaleX: 1 });
}
restart() {
this.timeline.restart();
}
}
export default TimeModule; | 36034f5ea89b9aa54b420ec5328739653c840ac8 | [
"JavaScript"
]
| 10 | JavaScript | leochocolat/QuizzReact | e7ec1168866d38ee3d31d12e930488857c094f4a | f0874ebbbcd67dd02b03964f5ca1c95150a548bb |
refs/heads/master | <repo_name>zflagg/FlaggCh5<file_sep>/CompareDriver.java
public class CompareDriver
{
public static void main(String[] args) {
String st1 = new String("hi");
String st2 = new String("bye");
Integer int1 = new Integer(1);
Integer int2 = new Integer(2);
System.out.println(Compare1.largest(st1,st2));
System.out.println(Compare3.largest(st1, st2));
System.out.println(Compare2.largest(int1, int2));
System.out.println(Compare3.largest(st1, int2));
}
}
<file_sep>/Compare1.java
public class Compare1 {
private String first, second;
private int len1, len2;
public static String largest(String str1, String str2) {
if(str1.compareTo(str2)>0) {
return str1;
}
else {
return str2;
}
}
} | f84e89722fce4e131fd2780846c4fb4203cac51b | [
"Java"
]
| 2 | Java | zflagg/FlaggCh5 | f1ecce15d27e050160c91775a643b2cf764b3d9e | 964c1f9f70468e028cdab9f63e7f824807916d15 |
refs/heads/master | <repo_name>MemeAr/DHT11<file_sep>/connBdd.php
<?php
require_once 'config.inc.php';
try {
$bdd = new PDO('mysql:host='.$host.'; dbname='.$dbname, $username, $password);
echo "<p>bien connecté a ".$host."</p>";
}
catch(PDOException $pe){
die('<p>Could not connect to the database $dbname : '.$pe->getMessage().'</p>');
}
$requete = $bdd->prepare('INSERT INTO data(temp, humidity, date) VALUES ('')');<file_sep>/index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="1">
<meta charset="utf-8">
<title>Temperature</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<h1>Température</h1>
<?php
$donnees = file_get_contents('data.json');
$info = json_decode($donnees);
$bargraph_height = 161 + $info->temperature * 4;
$bargraph_top = 315 - $info->temperature * 4;
$filename = 'data.txt'; {
echo "La météo à été mise à jour le : " . date("d-m-Y H:i:s.", filectime($filename));
}
?>
<p>Il fait actuellement <?php echo($info -> temperature);?>°C et le taux d'humidité est de <?php echo($info -> humidite);?>%.</p>
<div id="thermometer">
<div id="bargraph" style=<?php echo "\"height:".$bargraph_height."px; top:".$bargraph_top."px;\"";?>></div>
</div>
</body>
</html> | 6f10dde41d53d76bba894c39d956d4e8dbec768b | [
"PHP"
]
| 2 | PHP | MemeAr/DHT11 | 2bbb62d1e35335d4faa320322a28d61853693a00 | 62bd92cba87e5bf6f7df3e340a6ce564f14fa400 |
refs/heads/master | <repo_name>jabzzy/tests<file_sep>/js/presentation.js
(function ($) {
$.fn.prsnttn = function (options) {
var settings = {
itemSelector: '.item',
currentItemSelector: '.current-item',
closeSelector: '.close',
useNavLinks: true,
navNextHtml: '→',
navPrevHtml: '←',
navNextClass: 'nav-next',
navPrevClass: 'nav-prev',
useMouseScrollNav: true,
hiddenClass: 'hidden'
},
DOMDocument = document;
if (options) {
$.extend(settings, options);
}
// private settings
settings.currentItemClass = settings.currentItemSelector.substr(1, settings.currentItemSelector.length);
settings.keyCodes = {
forward: [
32, // space
39, // right arrow
38, // up arrow
34, // page down
68, // 'd'
87 // 'w'
],
backward: [
8, // backspace
37, // left arrow
40, // down arrow
33, // page up
83, // 's'
65 // 'a'
],
fullscreen: [
13, // enter
70 // f
]
};
function _switchItem($items, itemsLength, direction) {
direction = direction || 'forward';
var $current = $items.filter(settings.currentItemSelector);
$current.removeClass(settings.currentItemClass).addClass(settings.hiddenClass);
if (direction === 'backward') {
if ($items.index($current) === 0) { // first item
$items.last().addClass(settings.currentItemClass).removeClass(settings.hiddenClass);
} else { // navigating normally
$current.prev().removeClass(settings.hiddenClass).addClass(settings.currentItemClass);
}
} else {
if ($items.index($current) === itemsLength - 1) { // last item
$items.eq(0).addClass(settings.currentItemClass).removeClass(settings.hiddenClass);
} else { // navigating normally
$current.next().removeClass(settings.hiddenClass).addClass(settings.currentItemClass);
}
}
}
function _goFullScreen(self) {
if ('requestFullScreen' in self) {
self.requestFullScreen();
} else if ('mozRequestFullScreen' in self) {
self.mozRequestFullScreen();
} else if ('webkitRequestFullScreen' in self) {
self.webkitRequestFullScreen();
}
}
function _cancelFullScreen() {
if ('cancelFullScreen' in DOMDocument) {
DOMDocument.cancelFullScreen();
} else if ('mozCancelFullScreen' in DOMDocument) {
DOMDocument.mozCancelFullScreen();
} else if ('webkitCancelFullScreen' in DOMDocument) {
DOMDocument.webkitCancelFullScreen();
}
}
return this.each(function () {
var self = this,
$this = $(this),
$items = $this.children(settings.itemSelector),
itemsLength = $items.length,
$navNext = $('<a href="#" />').addClass(settings.navNextClass).html(settings.navNextHtml),
$navPrev = $('<a href="#" />').addClass(settings.navPrevClass).html(settings.navPrevHtml);
// initial setup
$items.filter(':not(:eq(0))').addClass(settings.hiddenClass);
$items.eq(0).addClass(settings.currentItemClass);
// links navigation
if (settings.useNavLinks) {
$this.append($navNext);
$this.append($navPrev);
$navNext.click(function () {
_switchItem($items, itemsLength);
return false;
});
$navPrev.click(function () {
_switchItem($items, itemsLength, 'backward');
return false;
});
}
// mouse scrolling navigation
if (settings.useMouseScrollNav) {
$(DOMDocument).on('DOMMouseScroll mousewheel', function (e) {
e.preventDefault();
var evt = e.originalEvent;
// scrolling up
if ((evt.wheelDelta && evt.wheelDelta >= 120) || (evt.detail && evt.detail <= -1)) {
_switchItem($items, itemsLength, 'backward');
} else if ((evt.wheelDelta && evt.wheelDelta <= -120) || (evt.detail && evt.detail >= 1)) {
_switchItem($items, itemsLength);
}
});
}
// keys navigation
$('body').on({
keydown: function (e) {
if (settings.keyCodes.forward.indexOf(e.keyCode) !== -1) {
_switchItem($items, itemsLength);
return false;
} else if (settings.keyCodes.backward.indexOf(e.keyCode) !== -1) {
_switchItem($items, itemsLength, 'backward');
return false;
} else if (settings.keyCodes.fullscreen.indexOf(e.keyCode) !== -1) {
_goFullScreen(self);
}
}
});
$(settings.closeSelector).click(function () {
_cancelFullScreen();
});
});
};
})(jQuery);
$(function () {
$('.p').prsnttn();
}); | b082636f0714bcc777103e4c2cd5cfd5562f5dc3 | [
"JavaScript"
]
| 1 | JavaScript | jabzzy/tests | b986459de218e20223f381025b13d66b9a977636 | 454dda393caf896c0a78c103dc7fe6a8d893f4ed |
refs/heads/master | <file_sep>(function() {
const AUTH_SERVER = "https://mini-auth-2019.herokuapp.com";
let AUTH_RESPONSE;
function auth(username, password) {
return axios.post(`${AUTH_SERVER}/auth`, {
username: username,
password: <PASSWORD>
});
}
function isLoggedIn() {
return AUTH_RESPONSE && AUTH_RESPONSE.authorization;
}
$(function() {
$("[data-js-id=login]").on("click", function() {
let username = $("#usernameInput").val();
let password = $("#passwordInput").val();
auth(username, password).then(function(response) {
AUTH_RESPONSE = response.data;
$("#login-modal").modal('hide');
});
});
$("#login-modal").on('hide.bs.modal', function(e) {
if (AUTH_RESPONSE) {
$("#session").text(JSON.stringify(AUTH_RESPONSE, null, 4));
}
})
});
})();
| bccd9e90c7f99eb36d5a97a4c34ed36d3b3578b1 | [
"JavaScript"
]
| 1 | JavaScript | behrangsa/spring-ipsum-website | 5e7c08189360f80f7729aeebfad1c1e9a8de593e | 21d46d389dbfa954855327d9ce8514deb703fc0b |
refs/heads/master | <file_sep><?php
class Product extends CI_Model {
public function get_all_products(){
$query = "SELECT id, name, description, price FROM products";
return $this->db->query($query)->result_array();
}
public function get_product($id){
$query = "SELECT id, name, description, price FROM products WHERE id = ?";
return $this->db->query($query, $id)->row_array();
}
public function add_product($name, $description, $price){
$query = "INSERT INTO products(name, description, price, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW())";
$values = array($name, $description, $price);
$this->db->query($query, $values);
}
public function delete($product){
$query = "DELETE FROM products WHERE id = ?";
$this->db->query($query, $product);
}
public function update($id, $name, $description, $price){
$query = "UPDATE products SET name = ?, description = ?, price = ? WHERE id = ?";
$values = array($name, $description, $price, $id);
$this->db->query($query, $values);
}
}
?><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Products Listing</title>
</head>
<body>
<h1>Products</h1>
<a href="/products/view_cart">Your Cart (<?=$this->session->userdata('cart_count')?>)</a>
<table>
<th>Description</th>
<th>Price</th>
<th>Qty.</th>
<?php
foreach($products as $product){ ?>
<tr>
<td><?=$product['description']?></td>
<td>$<?=$product['price']?></td>
<td><input type="number" name="quantity" form="buy<?=$product['id']?>" value="1" min="1"></td>
<td>
<form id="buy<?=$product['id']?>" action="/products/add/<?=$product['id']?>" method="get">
<input type="submit" value="Buy">
</form>
</td>
</tr>
<?php } ?>
</table>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Product extends CI_Model {
public function get_all(){
$query = ("SELECT * FROM products");
return $this->db->query($query)->result_array();
}
public function get_product($id){
$query = ("SELECT * FROM products WHERE id = ?");
return $this->db->query($query, $id)->row_array();
}
}
?><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
<head>
<title>Update Product</title>
</head>
<body>
<h1>Edit Product <?=$id?></h1>
<p style="color: red;">
<?php if(!empty($this->session->flashdata('message'))){
echo $this->session->flashdata('message');
} ?>
</p>
<form action="/products/update" method="post">
<input type="hidden" name="id" value="<?=$id?>">
<p>Name: <input id="name" type="text" name="name" value="<?=$name?>"></p>
<p>Description: <input id="description" type="text" name="description" value="<?=$description?>"></p>
<p>Price: <input id="price" type="text" name="price" value="<?=$price?>"></p>
<input type="submit" value="Update">
</form>
<a href="/products/show/<?=$id?>">Show</a>
<a href="/">Back</a>
</body>
</html><file_sep><?php
session_start();
$email = $_POST["email"];
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$password = $_POST["<PASSWORD>"];
$confirm_password = $_POST["confirm_password"];
$birth_date = $_POST["birth_date"];
$errors = array();
$highlights = array();
foreach($_POST as $key => $value){
if(empty($value)){
$errors[] = "<p>".ucfirst($key)." cannot be empty.</p>";
}
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "<p>You did not enter a valid email address</p>";
$highlights[] = "email";
}
if(preg_match('/[0-9]/',$first_name)){
$errors[] = "<p>Your first name cannot contain numbers.</p>";
$highlights[] = "first_name";
}
if(preg_match('/[0-9]/',$last_name)){
$errors[] = "<p>Your last name cannot contain numbers.</p>";
$highlights[] = "last_name";
}
if(strlen($password) <= 6 && strlen($password) > 0){
$errors[] = "<p>Your password is too short</p>";
$highlights[] = "password";
}
if($password !== $confirm_password){
$highlights[] = "confirm_password";
$errors[] = "<p>Your passwords do not match</p>";
}
if(preg_match('/\s/', $first_name)){
$highlights[] = "first_name";
$errors[] = "<p>Your first name cannot be more than one word and cannot have any space after it.</p>";
}
if(preg_match('/\s/', $last_name)){
$highlights[] = "last_name";
$errors[] = "<p>Your first name cannot be more than one word and cannot have any space after it.</p>";
}
if($_FILES["profile_picture"]){
move_uploaded_file($_FILES["profile_picture"]["tmp_name"], "C:/Users/john/Desktop/Wamp Directory/uploads/profile_picture");
}
$_SESSION['errors'] = $errors;
//var_dump($errors);
//var_dump($_SESSION['errors']);
header("LOCATION: registration.php");
?><file_sep><?php
class Node {
public function __construct($val){
$this->value = $val;
$this->next = null;
}
}
class SinglyLinkedList{
public function __construct(){
$this->head = null;
$this->tail = null;
$this->count = 0;
}
public function add($val){
if ($this->count == 0){
$node = new Node($val);
$this->head = $node;
$this->tail = $node;
$this->count++;
}
else {
$node = new Node($val);
$this->tail->next = $node;
$this->tail = $node;
$this->count++;
}
if($this->find($val) == $val){
return true;
}
//return true if added correctly
}
public function remove($value){
$current = $this->head;
$previous = $this->head;
while($current->value != $value){
if($current->next == null){
return false;
}
else{
$previous = $current;
$current = $current->next;
}
}
$previous->next = $current->next;
return true;
//return true if correctly removed
//return false if value was never found
}
public function insert($valueAfter, $newValue){
$current = $this->head;
$newNode = new Node($newValue);
while($current->value != $valueAfter){
if($current->next == null){
$this->add($newNode);
return;
}
else{
$current = $current->next;
}
}
$temp = $current->next;
$current->next = $newNode;
$newNode->next = $temp;
return true;
//return true if successfully inserted after the valueAfter
//if value is never found add the new value to the end of the linked list
}
public function printList(){
$current = $this->head;
for($i=1; $i<=$this->count; $i++){
echo $current->value."<br>";
$current = $current->next;
}
//echo all values in the linked list
}
public function find($value){
$current = $this->head;
while($current->value != $value){
if($current->next == null){
return false;
}
else{
$current = $current->next;
}
}
return $current->value;
//return node if value is found
//return false if not found
}
public function isEmpty(){
if($this->count = 0){
return true;
}
else {
return false;
}
//return true if the linked list is empty
//return false if linked list has nodes
}
}
$list = new SinglyLinkedList();
$list->add("John");
$list->add("Todd");
$list->add("Tim");
$list->add("Pat");
$list->add("Joey");
$list->add("Lewis");
$list->add("Michael");
$list->insert("Todd", "Elena");
$list->printList();
?><file_sep><?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
<link rel="stylesheet" href="registration.css">
</head>
<body>
<form enctype="multipart/form-data" action="process_account.php" method="post">
<h1>Register!</h1>
<?php
//var_dump($_SESSION['errors']);
if (isset($_SESSION['errors'])){
foreach($_SESSION['errors'] as $error){
echo $error;
}
}
else {
echo "Your registration has been submitted.";
}
?>
<input name="email" type="email" placeholder="Email">
<input name="first_name" type="text" placeholder="First Name">
<input name="last_name" type="text" placeholder="Last Name">
<input name="password" type="<PASSWORD>" placeholder="<PASSWORD>">
<input name="confirm_password" type="<PASSWORD>" placeholder="<PASSWORD>">
<input name="birth_date" type="date" placeholder="Birth Date">
<input class="file" name="profile_picture" type="file" placeholder="Profile Picture" accept="image/*">
<input type="submit" value="Register">
</form>
</body>
</html><file_sep><?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<titl>Registration</title>
</head>
<body>
<?php
if(isset($_SESSION["errors"])){
echo $_SESSION["errors"];
}
?>
<form action="process_email.php" method="post">
<input type="email" name="email">
<input type="submit" value="submit">
</form>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
<head>
<title>Product Details</title>
</head>
<body>
<h1>Product <?=$id?></h1>
<p>Name: <?=$name?></p>
<p>Description: <?=$description?></p>
<p>Price: <?=$price?></p>
<a href="/products/edit/<?=$id?>">Edit</a>
<a href="/">Back</a>
</body>
</html><file_sep><?php
session_start();
session_destroy;
$errors = array();
if(empty($_POST['user_name'])){
$errors[] = "You must enter your name!";
};
if(empty($_POST['quote'])){
$errors[] = "You must enter a quote!";
};
if(!empty($errors)){
$_SESSION['errors'] = $errors;
header("LOCATION: index.php");
die();
}
else {
require_once("connection.php");
run_mysql_query("INSERT INTO quotes (user, quote, created_at) VALUES ('".$_POST['user_name']."', '".$_POST['quote']."', NOW())");
header("LOCATION: main.php");
};
?><file_sep><?php
session_start();
date_default_timezone_set("America/Los_Angeles");
if(!isset($_SESSION['activities'])){
$_SESSION['activities'] = array();
}
if($_POST["destroy"]){
session_destroy();
}
switch ($_POST["location"]) {
case "farm":
$rand1= rand(10, 20);
$_SESSION["gold_count"] = $_SESSION["gold_count"] + $rand1;
array_push($_SESSION["activities"], "You entered a farm and earned $rand1 golds(".date("F d, Y h:i a").")
");
break;
case "cave":
$rand2 = rand(5, 10);
$_SESSION["gold_count"] = $_SESSION["gold_count"] + $rand2;
array_push($_SESSION["activities"], "You entered a cave and earned $rand2 golds(".date("F d, Y h:i a").")
");
break;
case "house":
$rand3 = rand(2, 5);
$_SESSION["gold_count"] = $_SESSION["gold_count"] + $rand3;
array_push($_SESSION["activities"], "You entered a house and earned $rand3 golds(".date("F d, Y h:i a").")
");
break;
case "casino":
$rand4 = rand(-50, 50);
$_SESSION["gold_count"] = $_SESSION["gold_count"] + $rand4;
$rand4 < 0?$action = "lost":$action = "earned";
if ($action == "lost"){$rand4 = abs($rand4);}
array_push($_SESSION["activities"], "You entered a casino and $action $rand4 golds(".date("F d, Y h:i a").")
");
break;
}
header('LOCATION: NinjaGold.php');
exit();
?><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
<head>
<title>Survey Form</title>
</head>
<body>
<form action="/surveys/process_form" method="post">
<p>Your Name:
<input type="text" name="name">
</p>
<p>Dojo Location:
<select name="location">
<option value="Seattle">Seattle</option>
<option value="San Jose">San Jose</option>
<option value="Los Angeles">Los Angeles</option>
</select>
</p>
<p>Favorite Language:
<select name="language">
<option value="Javascript">Javascript</option>
<option value="PHP">PHP</option>
<option value="Ruby">Ruby</option>
</select>
</p>
<p>Comment (optional):</p>
<textarea name="comment"></textarea>
<input type="submit" value="Submit">
</form>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<title>Courses</title>
</head>
<body>
<h1>Add a new course</h1>
<form action="/courses/add" method="post">
<p style="color: red;">
<?php if(!empty($this->session->flashdata('message'))){
echo $this->session->flashdata('message');
} ?>
</p>
<p>Name: <input type="text" name="name" required></p>
<p>Description: <input type="text" name="description"></p>
<input class="btn btn-success" type="submit" value="Add">
</form>
<h1>Courses</h1>
<table class="table">
<thead>
<th>Course Name</th>
<th>Description</th>
<th>Date Added</th>
<th>Actions</th>
</thead>
<tbody>
<?php
foreach ($courses as $course){ ?>
<tr>
<td><?= $course['name'] ?></td>
<td><?= $course['description'] ?></td>
<td><?= $course['created_at'] ?></td>
<td><a href='/courses/destroy/<?= $course['id'] ?>'>Delete</a></td>
</tr>
<?php } ?>
</tbody>
</table>
</body>
</html><file_sep><?php
session_start();
require_once("new-connection.php");
//if user is registering
if($_POST['action'] == 'register'){
$email = $_POST["email"];
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$password = $_POST["password"];
$confirm_password = $_POST["confirm_password"];
$errors = array();
foreach($_POST as $key => $value){
if(empty($value)){
$errors[] = "<p>".ucfirst($key)." cannot be empty.</p>";
}
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "<p>You did not enter a valid email address</p>";
}
if(preg_match('/[0-9]/',$first_name)){
$errors[] = "<p>Your first name cannot contain numbers.</p>";
}
if(preg_match('/[0-9]/',$last_name)){
$errors[] = "<p>Your last name cannot contain numbers.</p>";
}
if(strlen($password) <= 6 && strlen($password) > 0){
$errors[] = "<p>Your password is too short</p>";
}
if($password !== $confirm_password){
$errors[] = "<p>Your passwords do not match</p>";
}
if(preg_match('/\s/', $first_name)){
$errors[] = "<p>Your first name cannot be more than one word and cannot have any space after it.</p>";
}
if(preg_match('/\s/', $last_name)){
$errors[] = "<p>Your first name cannot be more than one word and cannot have any space after it.</p>";
}
if(!empty($errors)){
$_SESSION['errors'] = $errors;
header("LOCATION: index.php");
exit();
}
else {
$query = "INSERT INTO users (email, first_name, last_name, password, created_at) VALUES ('".escape_this_string($email)."', '".escape_this_string($first_name)."', '".escape_this_string($last_name)."', '".escape_this_string($password)."', NOW())";
$_SESSION['user_id'] = run_mysql_query($query);
$_SESSION['status'] = "logged_in";
header("LOCATION: home.php");
exit();
}
}
//if user is Logging in
if($_POST['action'] == 'login'){
$errors = array();
if(empty($_POST['email'])){
$errors[] = "Email cannot be left blank";
}
if(empty($_POST['password'])){
$errors[] = "Password cannot be left blank";
}
if(!empty($errors)){
$_SESSION['log_errors'] = $errors;
header("LOCATION: index.php");
exit();
}
else{
$query = "SELECT id FROM users WHERE email = '".escape_this_string($_POST['email'])."' && password = '".escape_this_string($_POST['password'])."'";
$logged_in = fetch_record($query);
//var_dump($logged_in);
if(!empty($logged_in)){
$_SESSION['status'] = 'logged_in';
$_SESSION['user_id'] = $logged_in['id'];
header("LOCATION: home.php");
exit();
}
else{
$errors[] = "Your email or password is incorrect.";
$_SESSION['log_errors'] = $errors;
header("LOCATION: index.php");
exit();
}
}
}
//if user is posting a message
if($_POST['action'] == 'post_message'){
$query = "INSERT INTO messages (user_id, message, created_at, updated_at) VALUES ('".escape_this_string($_SESSION['user_id'])."', '".escape_this_string($_POST['message'])."', NOW(), NOW())";
run_mysql_query($query);
header("LOCATION: home.php");
exit();
}
//if user is posting a comment
if($_POST['action'] == 'post_comment'){
$query = "INSERT INTO comments (message_id, user_id, comment, created_at, updated_at) VALUES ('".escape_this_string($_POST['message_id'])."','".escape_this_string($_POST['user_id'])."', '".escape_this_string($_POST['comment'])."', NOW(), NOW())";
run_mysql_query($query);
header("LOCATION: home.php");
exit();
}
//if user is logging off
if($_POST['action'] == 'logoff') {
header("LOCATION: index.php");
session_destroy();
exit();
}
//if user is deleting his message
if($_POST['action'] == 'delete'){
$query = "DELETE FROM messages WHERE id = ".escape_this_string($_POST['message_id']);
run_mysql_query($query);
header("LOCATION: home.php");
exit();
}
?><file_sep><?php
class User extends CI_Model{
public function get_user($id){
$query = "SELECT first_name, last_name, email FROM users WHERE id = ?";
return $this->db->query($query, $id)->row_array();
}
public function login_user($email, $password){
$query = "SELECT email, first_name, last_name FROM users WHERE email = ? && password = ?";
$values = array($email, $password);
return $this->db->query($query, $values)->row_array();
}
public function register_user($email, $first_name, $last_name, $password){
$query = "INSERT INTO users (email, first_name, last_name, password, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())";
$values = array($email, $first_name, $last_name, $password);
$this->db->query($query, $values);
$query = "SELECT first_name, last_name, email FROM users WHERE email = ?";
return $this->db->query($query, $email)->row_array();
}
}
?><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
<head>
<title>Result</title>
</head>
<body>
<?php
echo "session counter is" . $this->session->userdata('count');
$this->session->set_userdata('count', rand(20,50));
echo "changed session counter to be" . $this->session->userdata('count');
?>
<p>Random Word (attempt #<?=$this->session->userdata('count')?>)</p>
<div class="word">
<h1><?=?></h1>
</div>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome <?=$this->session->userdata('user')['first_name']?></h1>
<a href="/users/logoff">Log Off</a>
<h2>User Information</h2>
<p>First Name: <?=$this->session->userdata('user')['first_name']?></p>
<p>Last Name: <?=$this->session->userdata('user')['last_name']?></p>
<p>Email: <?=$this->session->userdata('user')['email']?></p>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
<head>
<title>Random Word</title>
</head>
<body>
<p>Random Word (attempt #<?=$this->session->userdata('count')?>)</p>
<div class="word">
<h1><?php if(!empty($rand)){echo $rand;}?></h1>
</div>
<form action="/random/process_rand" method="post">
<input type="submit" value="Generate">
</form>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Products extends CI_Controller {
public function index(){
$this->load->model('product');
$products = $this->product->get_all_products();
//var_dump($products);
$this->load->view('products', ['products' => $products]);
}
public function new_product(){
$this->load->view('new_product');
}
public function create(){
$this->load->model('product');
$this->product->add_product($this->input->post('name'), $this->input->post('description'), $this->input->post('price'));
redirect("/");
}
public function destroy($id){
$this->load->model('product');
$this->product->delete($id);
redirect("/");
}
public function show($id){
$this->load->model('product');
$product = $this->product->get_product($id);
$this->load->view('show', $product);
}
public function edit($id){
$this->load->model('product');
$product = $this->product->get_product($id);
$this->load->view('edit', $product);
}
public function update(){
$this->load->model('product');
$this->product->update($this->input->post("id"), $this->input->post("name"), $this->input->post("description"), $this->input->post("price"));
redirect("/");
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Courses extends CI_Controller {
public function index(){
$this->load->model('course');
$courses = $this->course->get_all_courses();
$this->load->view('courses', ['courses' => $courses]);
}
public function add(){
if(strlen($this->input->post('name')) >= 15){
$this->load->model('course');
$this->course->add_course($this->input->post('name'), $this->input->post('description'));
}
else{
$this->session->set_flashdata("message", "The course name must be at least 15 characters!");
}
redirect("/");
}
public function destroy(){
$this->load->view('destroy');
}
public function delete(){
$this->load->model('course');
$this->course->delete($this->input->post('course_name'));
redirect("/");
}
}
<file_sep><?php
//session_start();
//require_once("new-connection.php");
//$emails = fetch_all("SELECT email as 'Email', created_at as '' FROM emails");
//print_r($emails);
?>
<!DOCTYPE html>
<html>
<head>
<title>Success Page</title>
</head>
<body>
<h1>Welcome to the site</h1>
<form action="process.php">
<input type="submit" value="Log Off">
</form>
</body>
</html>
<!--<!DOCTYPE html>
<html>
<head>
<title>Quoting Dojo</title>
</head>
<body>
<h1>Welcome to Quoting Dojo</h1>
//<?php
// session_start();
// if(!empty($_SESSION['errors'])){
// foreach($_SESSION['errors'] as $error){
// echo $error."<br/>";
// }
// }
//?>
<form action="process.php" method="post">
<p>Your name:
<input type="text" name="user_name">
</p>
<p>Your quote"
<textarea name="quote"></textarea>
</p>
<input type="submit" value="Add my quote!">
</form>
<form action="main.php" method="post">
<input type="submit" value="Skip to quotes!">
</form>
</body>
</html>--><file_sep><!DOCTYPE html>
<html>
<head>
<title>Pokedex</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
.container {
left: 0px;
top: 0px;
width: 50%;
height: 100%;
overflow: scroll;
position: fixed;
}
.info {
padding: 20px;
position: fixed;
right: 5%;
top: 10%;
width: 40%;
height: 80%;
border: solid thick red;
}
.image:hover {
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<?php
for ($i = 1; $i <= 151; $i++){
echo "<img class='image' src='http://pokeapi.co/media/img/$i.png' id='$i'>";
} ?>
</div>
<div class="info"></div>
<script>
$('img').click(function(){
var id = $(this).attr('id');
var url = "http://pokeapi.co/api/v1/pokemon/"+id;
console.log (url);
$.get(url, function(output){
var html_str = "<h2>"+output.name+"</h2>";
html_str += "<img src='http://pokeapi.co/media/img/"+id+".png'>";
html_str += "<h4>Types</h4><ul>";
for (var i=0; i<output.types.length; i++){
html_str += "<li>"+output.types[i].name+"</li>";
}
html_str += "<h4>Height</h4><p>"+output.height+"</p>";
html_str += "<h4>Weight</h4><p>"+output.weight+"</p>";
$('.info').html(html_str);
});
});
</script>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Products extends CI_Controller {
public function index(){
//Set up the cart session data as an associative array with product ids as keys and quantities ordered as values
if(empty($this->session->userdata('cart'))){
$this->session->set_userdata('cart', array());
}
//Set up the cart_count session variable
if(empty($this->session->userdata('cart_count'))){
$this->session->set_userdata('cart_count', 0);
}
//Grab all products and load the main page
$this->load->model('product');
$products = $this->product->get_all();
$this->load->view('listings', ['products' => $products]);
}
//add an item to cart
public function add($id){
//set the item id in the cart session and add the inputed quantity
$cart = $this->session->userdata('cart');
$cart[$id] += $this->input->get('quantity');
$this->session->set_userdata('cart', $cart);
//increase the cart count
$count = $this->session->userdata('cart_count') + $this->input->get('quantity');
$this->session->set_userdata('cart_count', $count);
//go back to the main page
redirect("/");
}
//go to checkout page
public function view_cart(){
//check if there is anything in the cart
if($this->session->userdata('cart_count') > 0){
//grab the product information from the db using the the item ids stored in cart session
$this->load->model('product');
$products = array();
foreach($this->session->userdata('cart') as $key => $value){
//check if the id key has a quantity greater than 0
if ($value > 0){
//push product info into a variable
$products[] = $this->product->get_product($key);
}
}
//load the checkout page and pass in the products in the cart
$this->load->view('checkout', ['products' => $products]);
}
//if the cart is empty
else {
redirect ("/");
}
}
//delete item from cart
public function delete($id){
$cart = $this->session->userdata('cart');
$this->session->set_userdata('cart_count', $this->session->userdata('cart_count') - $cart[$id]);
$cart[$id] = 0;
$this->session->set_userdata('cart', $cart);
redirect("/products/view_cart");
}
//destroy the session
public function order(){
$this->session->sess_destroy();
redirect("/");
}
}
?><file_sep><?php
require_once("connection.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>Quoting Dojo</title>
<style>
h1 {
text-align: center;
font-size: 40px;
}
.quote {
height: auto;
width: 80%;
margin-left: 10%;
border-bottom: solid thick black;
}
.quote p {
margin-left: 100px;
}
</style>
</head>
<body>
<h1>Here are the awesome quotes!</h1>
<?php
$array = fetch_all("SELECT quote, user, created_at FROM quotes");
//var_dump($array);
foreach($array as $entry){?>
<div class="quote">
<h4><?=$entry["quote"];?></h4>
<p>- <?=$entry["user"];?> at <?=$entry["created_at"];?></p>
</div>
<?php } ?>
</body>
</html><file_sep><?php
session_start();
require_once("new-connection.php");
if(!isset($_SESSION['status'])){
header("LOCATION: index.php");
die();
}
$array_of_ids = fetch_all("SELECT id FROM messages WHERE created_at >=NOW() - INTERVAL 30 MINUTE AND user_id = '".$_SESSION['user_id']."'");
$ids = array();
foreach($array_of_ids as $array){
array_push($ids, $array['id']);
}
$messages = fetch_all("SELECT messages.id, messages.user_id, messages.message, messages.created_at, users.first_name, users.last_name FROM messages LEFT JOIN users ON messages.user_id = users.id ORDER BY messages.id DESC");
$user_name = fetch_record("SELECT first_name, last_name FROM users WHERE id = ".$_SESSION['user_id']);
$name = $user_name['first_name']." ".$user_name['last_name'];
//print_r($emails);
?>
<!DOCTYPE html>
<html>
<head>
<title>The Wall</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="background"></div>
<div class="header">
<h1>Coding Dojo Wall!</h1>
<h3 class="head">Welcome, <span><?=$name;?></span></h3>
<form class="head" action="process.php" method="post">
<input type="hidden" name="action" value="logoff">
<input type="submit" value="Log Off">
</form>
</div>
<div class="wrapper">
<form action="process.php" method="post" class="post_message">
<input type="hidden" name="action" value="post_message">
<h2>Post a Message:</h2>
<textarea name="message"></textarea>
<input type="submit" value="Post Message">
</form>
<?php
foreach ($messages as $message){ ?>
<div class="message">
<h4><span><?=$message['first_name']?> <?=$message['last_name']?></span>- <?=$message['created_at']?></h1>
<p><?=$message['message']?></p>
<?php
if($message['user_id'] == $_SESSION['user_id']&& in_array($message['id'], $ids)){?>
<form class="delete" action="process.php" method="post">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="message_id" value="<?=$message['id'];?>">
<input type="submit" value="Delete Message!">
</form>
<?php } ?>
<?php
$comments = fetch_all("SELECT comments.comment, users.first_name, users.last_name, comments.created_at FROM comments LEFT JOIN users ON comments.user_id = users.id WHERE comments.message_id = ".$message['id']);
foreach ($comments as $comment){ ?>
<div class="comment">
<h4><span><?=$comment['first_name']?> <?=$comment['last_name']?></span>- <?=$comment['created_at']?></h1>
<p><?=$comment['comment']?></p>
</div>
<?php } ?>
<form class="comment" action="process.php" method="post">
<input type="hidden" name="action" value="post_comment">
<h5>Post a Comment:</h5>
<textarea name="comment"></textarea>
<input type="hidden" name="user_id" value="<?=$_SESSION['user_id']?>">
<input type="hidden" name="message_id" value="<?=$message['id']?>">
<input type="submit" value="Post Comment">
</form>
</div>
<?php } ?>
</div>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
padding: 10px;
}
table{
border: solid thin black;
width: 100%;
border-collapse: collapse;
}
thead {
background: silver;
}
th, td {
text-align: center;
width: 16.66%;
border: solid thin black;
border-collapse: collapse;
}
</style>
<title>Courses</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('a').click(function(){
$(this).closest('form').submit();
});
})
</script>
</head>
<body>
<h1>Courses</h1>
<table>
<thead>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Actions</th>
</thead>
<?php
foreach ($products as $product){
echo "<tr>";
foreach ($product as $row){
echo "<td>$row</td>";
}?>
<td>
<a href="/products/show/<?=$product['id']?>">View Details</a>
<a href="/products/edit/<?=$product['id']?>">Edit Product</a>
<a href="/products/destroy/<?=$product['id']?>"><button>Remove</button></a>
</td>
</tr>
<?php } ?>
</table>
<a href="/products/new_product">Add a new product.</a>
</body>
</html><file_sep><?php
session_start();
require_once("new-connection.php");
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$_SESSION['errors'] = "<p>You did not enter a valid email address</p>";
header("LOCATION: index.php");
exit();
}
else {
$email = $_POST["email"];
$_SESSION['email'] = $email;
$new_email = run_mysql_query("INSERT INTO emails (email, created_at, updated_at) VALUES ('$email', NOW(), NOW())");
header ("LOCATION: success.php");
die();
}
?><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cart/Checkout</title>
</head>
<body>
<h1>Checkout</h1>
<table>
<th>Qty.</th>
<th>Description</th>
<th>Price</th>
<?php
foreach($products as $item){
$id = $item['id'];?>
<tr>
<td><?=$this->session->userdata("cart")[$id]?></td>
<td><?=$item['description']?></td>
<td>$<?=$item['price']?></td>
<td><a href="/products/delete/<?=$item['id']?>">Delete</a></td>
</tr>
<?php } ?>
</table>
<h4>Total:
<?php
$total = 0;
foreach($products as $item){
$id = $item['id'];
$total += $item['price'] * $this->session->userdata("cart")[$id];
}
echo $total;
?></h4>
<h3>Billing Info</h3>
<form action="/products/order" method="post">
<p><input type="text" name="name" placeholder="Name"></p>
<p><input type="text" name="address" placeholder="Address"></p>
<p><input type="number" name="card" placeholder="Card Number"></p>
<input type="submit" value="Order">
</form>
</body>
</html><file_sep><?php
session_start();
require_once("new-connection.php");
$emails = fetch_all("SELECT email as 'Email', created_at as '' FROM emails");
//print_r($emails);
?>
<!DOCTYPE html>
<html>
<head>
<title>Success Page</title>
<style>
.emails{
width: 550px;
margin-left: 50px;
}
.emails p {
color: blue;
}
.emails span{
margin-left: 20px
}
</style>
</head>
<body>
<div class="success">
<h1>The email address you entered (<?=$_SESSION['email'];?>) is a Valid email address! Thank you!</h1>
</div>
<h1>Email Addresses Entered:</h1>
<div class="emails"><?php
for($i=0; $i<count($emails); $i++){
echo "<p>Email: ".$emails[$i]['Email']."<span>".$emails[$i]['']."</span></p>";
}
?></div>
</body>
</html><file_sep><?php
session_start();
require_once("new-connection.php");
//if user is registering
if($_POST['action'] == 'register'){
$email = $_POST["email"];
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$password = $_POST["password"];
$confirm_password = $_POST["confirm_password"];
$errors = array();
foreach($_POST as $key => $value){
if(empty($value)){
$errors[] = "<p>".ucfirst($key)." cannot be empty.</p>";
}
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "<p>You did not enter a valid email address</p>";
}
if(preg_match('/[0-9]/',$first_name)){
$errors[] = "<p>Your first name cannot contain numbers.</p>";
}
if(preg_match('/[0-9]/',$last_name)){
$errors[] = "<p>Your last name cannot contain numbers.</p>";
}
if(strlen($password) <= 6 && strlen($password) > 0){
$errors[] = "<p>Your password is too short</p>";
}
if($password !== $confirm_password){
$errors[] = "<p>Your passwords do not match</p>";
}
if(preg_match('/\s/', $first_name)){
$errors[] = "<p>Your first name cannot be more than one word and cannot have any space after it.</p>";
}
if(preg_match('/\s/', $last_name)){
$errors[] = "<p>Your first name cannot be more than one word and cannot have any space after it.</p>";
}
if(!empty($errors)){
$_SESSION['errors'] = $errors;
header("LOCATION: index.php");
exit();
}
else {
run_mysql_query("INSERT INTO users (email, first_name, last_name, password, created_at) VALUES ('".$email."', '".$first_name."', '".$last_name."', '".$password."', NOW())");
$_SESSION['status'] = "logged_in";
header("LOCATION: home.php");
exit();
}
}
//if user is Logging in
elseif($_POST['action'] == 'login'){
$errors = array();
if(empty($_POST['email'])){
$errors[] = "Email cannot be left blank";
}
if(empty($_POST['password'])){
$errors[] = "Password cannot be left blank";
}
if(!empty($errors)){
$_SESSION['log_errors'] = $errors;
header("LOACTION: index.php");
exit();
}
else{
$logged_in = fetch_record("SELECT * FROM users WHERE email = '".$_POST['email']."' && password = '".$_POST['password']."'");
var_dump($logged_in);
if(!empty($logged_in)){
$_SESSION['status'] = 'logged_in';
header("LOCATION: home.php");
exit();
}
else{
$errors[] = "Your email or password is incorrect.";
$_SESSION['log_errors'] = $errors;
//header("LOCATION: index.php");
exit();
}
}
}
//if user is logging off
else {
session_destroy();
header("LOCATION: index.php");
}
?>
//<?php
// session_start();
// session_destroy;
// $errors = array();
// if(empty($_POST['user_name'])){
// $errors[] = "You must enter your name!";
// };
// if(empty($_POST['quote'])){
// $errors[] = "You must enter a quote!";
// };
// if(!empty($errors)){
// $_SESSION['errors'] = $errors;
// header("LOCATION: index.php");
// die();
// }
// else {
// require_once("connection.php");
// run_mysql_query("INSERT INTO quotes (user, quote, created_at) VALUES ('".$_POST['user_name']."', '".$_POST['quote']."', NOW())");
// header("LOCATION: main.php");
// };
//?><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
<head>
<title>Create a new product</title>
</head>
<body>
<h1>Add a new product</h1>
<form action="/products/create" method="post">
<p style="color: red;">
<?php if(!empty($this->session->flashdata('message'))){
echo $this->session->flashdata('message');
} ?>
</p>
<p>Name: <input type="text" name="name" required></p>
<p>Description: <input type="text" name="description"></p>
<p>Price: <input type="text" name="price"></p>
<input style="background: green; color: white; border: solid thin black;" type="submit" value="Create">
</form>
<a href="/">Go Back</a>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
<head>
<title>Delete Course</title>
</head>
<body>
<h1>Are you sure you want to delete the following course?</h1>
<p>Name: <?=$this->input->post('course_name')?></p>
<p>Description: <?=$this->input->post('description')?></p>
<form action="/">
<input type="submit" value="No">
</form>
<form action="/courses/delete" method="post">
<input type="hidden" name="course_name" value="<?=$this->input->post('course_name')?>">
<input type="submit" value="Yes! I want to delete this">
</form>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
<title>Time Display</title>
<style>
body {
text-align: center;
}
.firstbox {
width: 200px;
border: solid thin black;
}
.secbox {
width: 200px;
margin-top: 30px;
border: solid thick black;
}
</style>
</head>
<body>
<div align="center" class="wrapper">
<div class="firstbox">
<p>The current time and date</p>
</div>
<div class="secbox">
<h1><?=$time?></h1>
</div>
</div>
</body>
</html><file_sep><?php
session_start();
if(isset($_SESSION['status'])){
header("LOCATION: home.php");
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Registration/Login</title>
</head>
<body>
<?php
if(isset($_SESSION["log_errors"])){
foreach($_SESSION["log_errors"] as $error){
echo $error;
}
}
?>
<div class="login">
<h2>Login</h2>
<form action="process.php" method="post">
<input type="hidden" name="action" value="login">
<p>Email:
<input type="email" name="email"></p>
<p>Password:
<input type="<PASSWORD>" name="<PASSWORD>"></p>
<input type="submit" value="Log In">
</form>
</div>
<?php
if(isset($_SESSION["errors"])){
foreach($_SESSION['errors'] as $error){
echo $error."<br/>";
}
}
?>
<div class="register">
<h2>Register</h2>
<form action="process.php" method="post">
<input type="hidden" name="action" value="register">
<p>Email:
<input type="email" name="email"></p>
<p>First Name:
<input type="text" name="first_name"></p>
<p>Last Name:
<input type="text" name="last_name"></p>
<p>Password:
<input type="<PASSWORD>" name="<PASSWORD>"></p>
<p>Confirm Password:
<input type="<PASSWORD>" name="confirm_password"></p>
<input type="submit" value="Register">
</form>
</div>
</body>
</html><file_sep><?php
class Course extends CI_Model {
public function get_all_courses(){
$query = "SELECT id, name, description, created_at FROM courses";
return $this->db->query($query)->result_array();
}
public function add_course($name, $description){
$query = "INSERT INTO courses(name, description, created_at) VALUES (?, ?, NOW())";
$values = array($name, $description);
$this->db->query($query, $values);
}
public function delete($course){
$query = "DELETE FROM courses WHERE name = ?";
$this->db->query($query, $course);
}
}
?><file_sep><?php
class Deck {
public function Shuffle(){
$this->cards = range(1, 52);
shuffle($this->cards);
}
public function Reset(){
$this->cards = range(1, 52);
}
public function Deal(){
$card = $this->cards[0];
unset($this->cards[0]);
$this->cards = array_values($this->cards);
return "<img src='card (".$card.").png' alt='Card'>";
}
}
class Player {
public $hand = array();
public function __construct($name){
$this->name = $name;
}
public function TakeCard($deck){
//deals a card and places it in the players hand
array_push($this->hand, $deck1->Deal());
}
}
$deck1 = new Deck();
new Player("John");
new Player("Todd");
new Player("Paul");
new Player("Dillon");
//for($i=0; $i<=51; $i++){
// echo "<img class='card' src='card (".$this->cards[$i].").png' alt='Card'>";
//}
?><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
<head>
<title>Result</title>
</head>
<body>
<div class="thanks">
<p>Thanks for submitting this form! You have submitted this form <?=$this->session->userdata('count')?> times now.</p>
</div>
<div class="info">
<h1>Submitted Information</h1>
<p>Your Name: <?=$this->input->post('name')?></p>
<p>Dojo Location: <?=$this->input->post('location')?></p>
<p>Favorite Language: <?=$this->input->post('language')?></p>
<p>Comment:</p><?=$this->input->post('comment')?>
<form action="index">
<input type="submit" value="Go Back">
</form>
</div>
</body>
</html><file_sep><?php
session_start();
if (!isset($_SESSION['gold_count'])){
$_SESSION['gold_count'] = 0;
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="ninja_style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#text').scrollTop($('#text')[0].scrollHeight);
});
</script>
</head>
<body>
<div class="wrapper">
<div class="gold_count">
<h1>Your Gold:</h1>
<input value="<?=$_SESSION['gold_count']?>"/>
</div>
<div class="places_container">
<div class="farm">
<h1>Farm</h1>
<h2>(earns 10-20 golds)</h2>
<form action="process_gold.php" method="post">
<input type="hidden" name="location" value="farm"/>
<input type="submit" value="Find Gold!"/>
</form>
</div>
<div class="cave">
<h1>Cave</h1>
<h2>(earns 5-10 golds)</h2>
<form action="process_gold.php" method="post">
<input type="hidden" name="location" value="cave"/>
<input type="submit" value="Find Gold!"/>
</form>
</div>
<div class="house">
<h1>House</h1>
<h2>(earns 2-5 golds)</h2>
<form action="process_gold.php" method="post">
<input type="hidden" name="location" value="house"/>
<input type="submit" value="Find Gold!"/>
</form>
</div>
<div class="casino">
<h1>Casino!</h1>
<h2>(earns/takes 0-50 golds)</h2>
<form action="process_gold.php" method="post">
<input type="hidden" name="location" value="casino"/>
<input type="submit" value="Find Gold!"/>
</form>
</div>
</div>
<div class="activities">
<h3>Activities:</h3>
<textarea id="text"><?php if(isset($_SESSION['activities'])&&!empty($_SESSION['activities'])){
foreach($_SESSION['activities'] as $activity) {
echo $activity;
}
} ?></textarea>
</div>
<form class="kill" action="process_gold.php" method="post"><input type="submit" name="destroy" value="Resart the Game"></form>
</div>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html>
<head>
<title>Login/Registration</title>
<style>
input {
display: block;
margin-bottom: 10px;
}
</style>
</head>
<body>
<h1>Login</h1>
<?=$this->session->flashdata('errors')?>
<form action="/users/login" method="post">
<input type="email" name="email" placeholder="Email" required>
<input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" required>
<input type="submit" value="Login">
</form>
<h1>Register</h1>
<?=validation_errors()?>
<form action="/users/register" method="post">
<input type="text" name="first_name" placeholder="First Name" required>
<input type="text" name="last_name" placeholder="Last Name" required>
<input type="email" name="email" placeholder="Email" required>
<input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" required>
<input type="<PASSWORD>" name="<PASSWORD>" placeholder="<PASSWORD>" required>
<input type="submit" value="Register">
</form>
</body>
</html> | 5e73719836cb8f1a0d07d2d3eae44eaeafd96a80 | [
"PHP"
]
| 39 | PHP | johnwalz97/LAMP-stack-projects | 3931beb1fd0ddc282bdddc448081c071aa34d9e7 | c52bc0a728a50f7513ffe390d9b58706cff99164 |
refs/heads/master | <repo_name>Multoryan/react-todo<file_sep>/src/reducers/index.js
import { combineReducers } from 'redux'
import { todos } from './todos'
// Главный reducer, примерно тоже, что и index.js во Vuex,
// собирает модули воедино
export const rootReducer = combineReducers({
todos
})<file_sep>/src/actions/todosActions.js
export const ADD_TODO = 'ADD_TODO'
export const REMOVE_TODO = 'REMOVE_TODO'
export const CHANGE_TODO = 'CHANGE_TODO'
export const CHANGE_FILTER = 'CHANGE_FILTER'
// Действие добавления нового дела
export function addTodo(todo) {
return {
type: ADD_TODO,
todo
}
}
// Удаление дела
export function removeTodo(id) {
return {
type: REMOVE_TODO,
id
}
}
// Изменение дела
export function changeTodo(todo) {
return {
type: CHANGE_TODO,
todo
}
}
// Изменение фильтра
export function changeFilter(id) {
return {
type: CHANGE_FILTER,
id
}
}<file_sep>/src/components/TodoFilters.js
import React from 'react'
import PropTypes from 'prop-types'
export class TodoFilters extends React.Component {
changeFilter = id => {
this.props.changeFilters(id)
}
renderFilters = () => {
return this.props.list.map(filter => {
const isActive = this.props.filter === filter.id && 'active'
return (
<button key={filter.id}
className={`ui button ${isActive || ''}`}
onClick={(e) => this.changeFilter(filter.id)}>
{ filter.title }
</button>
)
})
}
render() {
return (
<div className="ui buttons">
{ this.renderFilters() }
</div>
)
}
}
TodoFilters.propTypes = {
changeFilters: PropTypes.func.isRequired,
list: PropTypes.array.isRequired,
filter: PropTypes.number.isRequired
}
<file_sep>/src/reducers/todos.js
import { ADD_TODO, REMOVE_TODO, CHANGE_TODO, CHANGE_FILTER } from '../actions/todosActions'
const initialState = {
todos: [],
currentFilter: 3,
}
function getId(state) {
return state.todos.reduce((maxId, todo) => {
return Math.max(todo.id, maxId)
}, -1) + 1
}
export function todos(state = initialState, action) {
switch (action.type) {
// Добавление нового дела
case ADD_TODO:
return Object.assign({}, state, {
todos: [{
date: action.todo.date,
title: action.todo.title,
isComplete: false,
id: getId(state)
}, ...state.todos]
})
// Удаление дела
case REMOVE_TODO:
return Object.assign({}, state, {
todos: state.todos.filter(todo => todo.id !== action.id)
})
// Изменение дела
case CHANGE_TODO:
return Object.assign({}, state, {
todos: state.todos.map(todo => todo.id === action.todo.id ? action.todo : todo)
})
// Изменение фильтра
case CHANGE_FILTER:
return {...state, currentFilter: action.id}
default: return state
}
}
<file_sep>/src/utils/filters.js
export const filters = [
{
id: 1,
title: 'Не завершенные',
filterFunc: todo => !todo.isComplete
},
{
id: 2,
title: 'Завершенные',
filterFunc: todo => todo.isComplete
},
{
id: 3,
title: 'Все',
filterFunc: todo => todo
},
{
id: 4,
title: 'С указанной датой',
filterFunc: todo => todo.date
},
{
id: 5,
title: 'Без привязки к дате',
filterFunc: todo => !todo.date
},
{
id: 6,
title: 'Просроченные',
filterFunc: todo => todo.date && !todo.isComplete && (new Date(todo.date) < new Date())
}
]<file_sep>/README.md
Only for code review
<file_sep>/src/containers/PageTodos.js
import React from 'react'
import { connect } from 'react-redux'
import { removeTodo, changeTodo, changeFilter } from '../actions/todosActions'
import { TodoView } from '../components/TodoView'
import { TodoFilters } from '../components/TodoFilters'
import { filters } from '../utils/filters'
import { Link } from 'react-router-dom'
class PageTodos extends React.Component {
render() {
const { removeTodo, changeTodo, todos, changeFilter, currentFilter } = this.props
// Фильтрация
const needFilter = filters.find(filter => filter.id === currentFilter)
let todosGetter = todos.filter(todo => needFilter.filterFunc(todo))
// Сортировка
todosGetter = todosGetter.sort((prev, next) => new Date(prev.date || 0) - new Date(next.date || 0))
return (
<div className="ui grid container">
<div className="ten column centered row">
<TodoFilters
filter={ currentFilter }
list={ filters }
changeFilters={ changeFilter }
/>
</div>
<div className="ten column centered row">
<TodoView
todos={ todosGetter }
changeTodo={ changeTodo }
removeTodo={ removeTodo }
/>
</div>
<div className="ten column centered row">
<Link to="/add">Добавить</Link>
</div>
</div>
)
}
}
const mapStateToProps = store => ({
todos: store.todos.todos,
currentFilter: store.todos.currentFilter,
})
const mapStateToActions = dispatch => ({
removeTodo: id => dispatch(removeTodo(id)),
changeTodo: todo => dispatch(changeTodo(todo)),
changeFilter: id => dispatch(changeFilter(id))
})
export default connect(mapStateToProps, mapStateToActions)(PageTodos)<file_sep>/src/containers/PageAddTodos.js
import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../actions/todosActions'
import { TodoAdd } from '../components/TodoAdd'
import { Link } from 'react-router-dom'
class PageAddTodos extends React.Component {
addTodoWithRedirect = todo => {
const { addTodo, history } = this.props
addTodo(todo)
history.goBack()
}
render() {
return (
<div className="eight column centered row">
<TodoAdd
addTodo={this.addTodoWithRedirect}
/>
<div className="ten column centered row">
<button className="ui button">
<Link to="/">Назад</Link>
</button>
</div>
</div>
)
}
}
const mapStateToActions = dispatch => ({
addTodo: todo => dispatch(addTodo(todo)),
})
export default connect(null, mapStateToActions)(PageAddTodos)<file_sep>/src/components/TodoView.js
import React from 'react'
import PropTypes from 'prop-types'
export class TodoView extends React.Component {
constructor(props) {
super(props)
this.state = {
editableId: null,
oldValue: null,
oldDate: null,
newValue: null,
newDate: null
}
}
toggleComplete = (todo) => {
const { changeTodo } = this.props
changeTodo({
...todo,
isComplete: !todo.isComplete
})
}
remove = id => {
const { removeTodo } = this.props
removeTodo(id)
}
setEdit = todo => {
this.setState({
editableId: todo.id,
oldValue: todo.title,
oldDate: todo.date,
newValue: todo.title,
newDate: todo.date
})
}
saveEdit = todo => {
const { changeTodo } = this.props
if (!this.state.newValue) {
return null
}
changeTodo({
...todo,
title: this.state.newValue,
date: this.state.newDate
})
this.resetEdit()
}
resetEdit = () => {
this.setState({
editableId: null,
oldValue: null,
oldDate: null,
newValue: null,
newDate: null
})
}
renderEditButtons = (todo) => {
if (this.state.editableId === null) {
return (
<button onClick={(e) => this.setEdit(todo)}>Edit</button>
)
}
if (todo.id === this.state.editableId) {
return (
<div>
<button onClick={this.resetEdit}>Cancel</button>
<button onClick={(e) => this.saveEdit(todo)}>Save</button>
</div>
)
}
}
change = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
classFailed = todo => {
if (todo.date && !todo.isComplete && (new Date(todo.date) < new Date())) {
return 'todo--failed'
}
}
generateList = () => {
const { todos } = this.props
const list = todos.map(todo => {
const classFailed = todo.date && !todo.isComplete && (new Date(todo.date) < new Date()) && 'red'
const isDisabled = this.state.editableId !== todo.id
const valueDate = isDisabled ? todo.date : this.state.newDate
const valueTitle = isDisabled ? todo.title : this.state.newValue
return (
<div key={ todo.id } className={`ui centered card ${classFailed || ''}`}>
<div className="ui input">
<input type="date"
disabled={ isDisabled }
value={ valueDate }
name="newDate"
onChange={(e) => this.change(e)}/>
</div>
<div className="ui input">
<input type="text"
disabled={ isDisabled }
value={ valueTitle }
name="newValue"
onChange={(e) => this.change(e)}/>
</div>
<div className="ui input">
<input type="checkbox"
checked={ todo.isComplete }
onChange={(e) => this.toggleComplete(todo, e)} />
</div>
<button onClick={(e) => this.remove(todo.id, e)}>X</button>
{ this.renderEditButtons(todo) }
</div>
)
})
return list.length ? list : 'Нет задач'
}
render() {
return (
<React.Fragment>
{ this.generateList() }
</React.Fragment>
)
}
}
TodoView.propTypes = {
todos: PropTypes.array.isRequired,
changeTodo: PropTypes.func.isRequired,
removeTodo: PropTypes.func.isRequired
} | 86b77cfa8a39d7d8d8021df4090585bcf90ccfc4 | [
"JavaScript",
"Markdown"
]
| 9 | JavaScript | Multoryan/react-todo | 4dcb5b8fc6f9cafd35ab6aad25fd2a036ea98d92 | f3cfd0fa5fc805be1577f54c082a2af7ea3930c6 |
refs/heads/master | <file_sep>package cn.saymagic.befit.controller;
import cn.saymagic.befit.bo.ApkWrapper;
import cn.saymagic.befit.service.IApkService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.model.FileInfo;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by saymagic on 16/3/13.
*/
@Controller
@RequestMapping("/api/v1/")
public class ApkController {
private static Logger log = LoggerFactory.getLogger(ApkController.class);
@Value("${rootPath}")
private String rootPath;
@Value("${defaultName}")
private String defaultName;
private int maxSize = 1024 * 1024 * 30;
private IApkService apkService;
@Autowired
public void setApkService(IApkService apkService) {
this.apkService = apkService;
}
@ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception exception) {
Map map = new HashMap();
handleExceptions(map, exception);
return new ModelAndView(new MappingJackson2JsonView(), map);
}
@RequestMapping(value = "/put", method = {RequestMethod.POST, RequestMethod.PUT})
public
@ResponseBody
ModelAndView doUploadFile(@RequestParam("file") MultipartFile file, @RequestParam("name") String name) throws IOException {
Map map = new HashMap();
if (file == null || file.isEmpty()) {
map.put("code", 400);
map.put("error", "file is empty");
return new ModelAndView(new MappingJackson2JsonView(), map);
}else if (file.getSize() > maxSize) {
map.put("code", 400);
map.put("error", "file is too large");
return new ModelAndView(new MappingJackson2JsonView(), map);
}
try {
Response response = apkService.put(file, name);
if (response == null) {
map.put("code", 500);
map.put("error", "unknow");
} else {
if (response.isOK()) {
map.put("code", 200);
} else {
map.put("code", response.statusCode);
map.put("error", response.bodyString());
}
}
} catch (Exception e) {
handleExceptions(map, e);
}
return new ModelAndView(new MappingJackson2JsonView(), map);
}
@RequestMapping(value = "/delete/{name}", method = RequestMethod.DELETE)
public
@ResponseBody
ModelAndView doDeleteApk(@PathVariable("name") String name) {
Map map = new HashMap();
try {
apkService.delete(name);
map.put("code", 200);
} catch (Exception e) {
handleExceptions(map, e);
}
return new ModelAndView(new MappingJackson2JsonView(), map);
}
@RequestMapping(value = "/get/{name}", method = RequestMethod.GET)
public
@ResponseBody
ModelAndView getApkInfo(@PathVariable String name) {
Map map = new HashMap();
ApkWrapper apk = null;
try {
apk = apkService.get(name);
map.put("code", 200);
map.put("data", apk);
} catch (Exception e) {
handleExceptions(map, e);
}
ModelAndView modelView = new ModelAndView(new MappingJackson2JsonView(), map);
return modelView;
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public
@ResponseBody
ModelAndView getAllApkInfos() {
Map map = new HashMap();
List<FileInfo> infos = null;
try {
infos = apkService.list();
map.put("code", 200);
map.put("data", infos);
} catch (Exception e) {
handleExceptions(map, e);
}
ModelAndView modelView = new ModelAndView(new MappingJackson2JsonView(), map);
return modelView;
}
private void handleExceptions(Map map, Exception e) {
if (e instanceof QiniuException) {
QiniuException qe = (QiniuException) e;
map.put("code", qe.response.statusCode);
map.put("error", qe.response.error);
} else {
map.put("code", 500);
map.put("error", e.toString());
}
}
}
<file_sep>rootPath=/Users/lanyy/Documents/workspace/Intellij/befit/
defaultName=master
qiniu.accesskey=<KEY>
qiniu.secretkey=<KEY>
qiniu.bucketname=befit
qiniu.baseDownloadUrl=http://7xrzo6.com1.z0.glb.clouddn.com/<file_sep>package cn.saymagic.befit.helper;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.storage.model.FileListing;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Created by saymagic on 16/3/17.
*/
@Service("qiniuHelper")
public class QiniuHelper {
@Value("${qiniu.accesskey}")
private String accessKey;
@Value("${qiniu.secretkey}")
private String secretKey;
@Value("${qiniu.bucketname}")
private String bucketName;
@Value("${qiniu.baseDownloadUrl}")
private String baseDownloadUrl;
private ConcurrentHashMap<String, FileInfo> fileInfohMap;
private Auth auth ;
private UploadManager uploadManager ;
private BucketManager bucketManager;
public String getUpToken(){
return auth.uploadToken(bucketName);
}
public Response upload(byte[] data, String name) throws QiniuException {
initIfNeeded();
Response response = uploadManager.put(data, name, getUpToken());
fileInfohMap.put(name + ".apk", get(name));
return response;
}
public FileInfo get(String name) throws QiniuException {
initIfNeeded();
if (fileInfohMap.contains(name)) {
return fileInfohMap.get(name);
}
return bucketManager.stat(bucketName, name);
}
public void delete(String name) throws QiniuException {
initIfNeeded();
bucketManager.delete(bucketName, name);
}
public List<FileInfo> list() throws QiniuException {
initIfNeeded();
FileListing list = bucketManager.listFiles(bucketName, "", "", 1000, "");
if (list != null) {
return Arrays.asList(list.items);
}
return new ArrayList<FileInfo>();
}
public String getDownloadUrl(String name) {
initIfNeeded();
return baseDownloadUrl + name;
}
private void initIfNeeded() {
if (auth == null || uploadManager == null ) {
auth = Auth.create(accessKey, secretKey);
uploadManager = new UploadManager();
bucketManager = new BucketManager(auth);
if (fileInfohMap == null) {
try {
initFileInfoMap();
} catch (QiniuException e) {
fileInfohMap = new ConcurrentHashMap<String, FileInfo>();
}
}
}
}
private void initFileInfoMap() throws QiniuException {
fileInfohMap = new ConcurrentHashMap<String, FileInfo>(list()
.stream()
.collect(Collectors.toMap(infoKey -> infoKey.key, infoValue -> infoValue)));
}
}
<file_sep>package cn.saymagic.befit.bo;
import net.erdfelt.android.apk.AndroidApk;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.zip.ZipException;
/**
* Created by saymagic on 16/3/13.
*/
public class ApkWrapper {
private double mApkSize;
private String mQrlink;
private String mName;
private long mUpdateTime;
private String mVersionCode;
private String mVersionName;
private String mMinVersion;
private String mTargetVersion;
private String mPackageName;
//Warnning: maybe block.
public ApkWrapper(AndroidApk mBaseApk) throws IOException, NullPointerException, IllegalArgumentException {
Objects.requireNonNull(mBaseApk);
mVersionCode = mBaseApk.getAppVersionCode();
mMinVersion = mBaseApk.getMinSdkVersion();
mVersionName = mBaseApk.getAppVersion();
mPackageName = mBaseApk.getPackageName();
mTargetVersion = mBaseApk.getTargetSdkVersion();
}
public double getmApkSize() {
return mApkSize;
}
public void setmApkSize(double mApkSize) {
this.mApkSize = mApkSize;
}
public String getmQrlink() {
return mQrlink;
}
public void setmQrlink(String mQrlink) {
this.mQrlink = mQrlink;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public long getmUpdateTime() {
return mUpdateTime;
}
public void setmUpdateTime(long mUpdateTime) {
this.mUpdateTime = mUpdateTime;
}
public String getmVersionCode() {
return mVersionCode;
}
public void setmVersionCode(String mVersionCode) {
this.mVersionCode = mVersionCode;
}
public String getmVersionName() {
return mVersionName;
}
public void setmVersionName(String mVersionName) {
this.mVersionName = mVersionName;
}
public String getmMinVersion() {
return mMinVersion;
}
public void setmMinVersion(String mMinVersion) {
this.mMinVersion = mMinVersion;
}
public String getmTargetVersion() {
return mTargetVersion;
}
public void setmTargetVersion(String mTargetVersion) {
this.mTargetVersion = mTargetVersion;
}
public String getmPackageName() {
return mPackageName;
}
public void setmPackageName(String mPackageName) {
this.mPackageName = mPackageName;
}
}
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.saymagic</groupId>
<artifactId>befit</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>befit</name>
<url>http://maven.apache.org</url>
<properties>
<commons-lang.version>2.6</commons-lang.version>
<slf4j.version>1.7.6</slf4j.version>
<spring.version>4.1.3.RELEASE</spring.version>
<jackson.version>2.5.4</jackson.version>
<erdfelt.version>1.1</erdfelt.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>${spring.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons-lang.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>net.erdfelt.android</groupId>
<artifactId>apk-parser</artifactId>
<version>${erdfelt.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.9.RELEASE</version>
</dependency>
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.2.2.v20140723</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals><goal>copy</goal></goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-runner</artifactId>
<version>7.4.5.v20110725</version>
<destFileName>jetty-runner.jar</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
| 5b65cad732acc8e0b977835e691ba4117c15dc38 | [
"Java",
"Maven POM",
"INI"
]
| 5 | Java | saymagic/befit | 164c0c58e9c57fee8667ae8cf3e90e812dd4b9a2 | b457bda80c6c71060de8e27b47e950917a660f72 |
refs/heads/main | <file_sep>// SLIDER
$(document).ready( function () {
// Al click del maouse passo all'img successiva
$('.next').click( function () {
nextPrevImg('next');
});
// Al click del maouse torno all'img precedente
$('.prev').click( function () {
nextPrevImg('prev');
});
});
/*
FUNZIONI:
per scorrere le immagini avanti e indietro
*/
function nextPrevImg(direction) {
var imgActive = $('.images img.active');
var circleActive = $('.nav i.active');
var imgFirst = $('.images img.first');
var circleFirst = $('.nav i.first');
var imgLast = $('.images img.last');
var circleLast = $('.nav i.last');
// Reset per togliere la classe 'active' ai precedenti
imgActive.removeClass('active');
circleActive.removeClass('active');
// Direzione --> NEXT
if(direction === 'next') {
if(imgActive.hasClass('last') ) {
imgFirst.addClass('active');
circleFirst.addClass('active');
}
else {
imgActive.next('img').addClass('active');
circleActive.next('i').addClass('active');
}
}
// Direzione <-- PREV
else if (direction === 'prev') {
if(imgActive.hasClass('first') ) {
imgLast.addClass('active');
circleLast.addClass('active');
}
else {
imgActive.prev('img').addClass('active');
circleActive.prev('i').addClass('active');
}
}
}
| 5f6beff921c3df1c4bfae1dd42c5b7e3bcd483fe | [
"JavaScript"
]
| 1 | JavaScript | cherubina-pantano/js-jq-carousel | 569c22611524e158603c80ddeb272379d2bb2a23 | 88d4e211a1bb21d957b6d6acb80cb57fa2a4a35c |
refs/heads/master | <file_sep>package logicsim.gates;
import logicsim.*;
import processing.core.*;
import static logicsim.wiretypes.BasicWire.*;
public class LampGate extends Gate {
private boolean b;
public LampGate(float x, float y, int rot, String name) {
super(ONE_WIRE, NOTHING, x, y, rot, new PVector[]{new PVector(-20, 0)}, new PVector[0]);
this.name = name;
}
public static GateHandler handler() {
return s -> {
String[] a = s.nextLine().split(" ");
String name = s.nextLine();
return new LampGate(Float.parseFloat(a[0]), Float.parseFloat(a[1]), Integer.parseInt(a[2]), name);
};
}
@Override
public void process() {
BasicConnection ca = (BasicConnection) is[0];
b = ca.b;
}
@Override
public void draw(PGraphics g) {
g.ellipseMode(g.RADIUS);
g.strokeWeight(3);
if (selected) {
g.noStroke();
g.fill(Main.SELECTED);
g.ellipse(0, 0, 25, 25);
}
g.fill(b? Main.ON_LAMP : Main.OFF_LAMP);
g.stroke(Main.CIRCUIT_BORDERS);
g.ellipse(0, 0, 20, 20);
drawIO(g);
}
@Override
public Gate cloneCircuit(float x, float y) {
return new LampGate(x, y, rot, name);
}
public String def(float xoff, float yoff) {
return "LampGate\n" + (x-xoff) + " " + (y-yoff) + " " + rot + "\n" + name;
}
@Override
public Connection giveConnection() {
return is[0];
}
}
<file_sep>package logicsim.gates;
import logicsim.*;
import processing.core.*;
import static logicsim.wiretypes.BasicWire.*;
public class SwitchGate extends Gate {
public SwitchGate(float x, float y, int rot, String name) {
super(NOTHING, ONE_WIRE, x, y, rot, new PVector[0], new PVector[]{new PVector(45, 0)});
this.name = name;
}
public static GateHandler handler() {
return s -> {
String[] a = s.nextLine().split(" ");
String name = s.nextLine();
return new SwitchGate(Float.parseFloat(a[0]), Float.parseFloat(a[1]), Integer.parseInt(a[2]), name);
};
}
@Override
public void process() {
BasicConnection oc = (BasicConnection) os[0];
oc.set(on);
}
private boolean on;
@Override
public void click() {
on = !on;
warn();
}
@Override
public Gate cloneCircuit(float x, float y) {
return new SwitchGate(x, y, rot, name);
}
@Override
public void draw(PGraphics g) {
g.rectMode(g.RADIUS);
if (selected) {
g.noStroke();
g.fill(Main.SELECTED);
g.rect(0, 0, 30, 37);
}
g.stroke(Main.CIRCUIT_BORDERS);
g.fill(Main.CIRCUIT_COLOR);
g.strokeWeight(3);
g.line(25, 0, 45, 0);
g.rect(0, 0, 25, 32);
g.strokeWeight(1.5f);
g.fill(on? Main.ON_LAMP : Main.OFF_LAMP);
g.rect(0, 0, 17, 22);
g.fill(Main.CIRCUIT_COLOR);
g.rectMode(g.CORNERS);
int bi = on? -1 : 1;
float yp0 = 19 * bi;
float yp = -14 * bi;
float yp2 = -14.5f * bi;
float yp3 = -18 * bi;
g.rect(-12, 0, 12, yp0);
g.strokeCap(g.SQUARE);
g.beginShape();
g.vertex(15.2f, yp2);
g.vertex(14, yp3);
g.vertex(-14, yp3);
g.vertex(-15.2f, yp2);
g.endShape();
g.quad(-12, 0, 12, 0, +15, yp, -15, yp);
// g.quad(x-15, yp, x+15, yp, x+14, yp2, x-14, yp2);
drawIO(g);
}
@Override
public boolean in(float mx, float my) {
return Math.abs(mx-x) < 25 && Math.abs(my-y) < 32;
}
public String def(float xoff, float yoff) {
return "SwitchGate\n" + (x-xoff) + " " + (y-yoff) + " " + rot + "\n" + name;
}
@Override
public void forwardConnection(Connection c) {
boolean n = ((BasicConnection) c).b;
if (n != on) {
on = n;
warn();
}
}
}
<file_sep>package logicsim;
import logicsim.gui.Drawable;
import processing.core.*;
import java.util.*;
public abstract class Circuit extends Drawable {
public ArrayList<Gate> gates;
Circuit(int x, int y, int w, int h) {
super(x, y, w, h);
gates = new ArrayList<>();
}
void add(Gate... gates) {
Collections.addAll(this.gates, gates);
}
int pmx, pmy;
float offX, offY;
float scale = 1; // 2 = 1/4th seen from before
@Override
protected void mouseWheel(int i) {
double sc = i==1? .8 : 1/.8;
double pS = scale;
scale*= sc;
double scaleChange = 1/scale - 1/pS;
offX -= (Main.mX * scaleChange);
offY -= (Main.mY * scaleChange);
}
void drawHeld(PGraphics g) {
if (held == null) return;
g.pushMatrix();
g.translate(-offX * scale, -offY * scale);
g.scale(scale);
g.translate(held.x, held.y);
held.draw(g);
g.popMatrix();
}
public void draw(PGraphics g) {
g.pushMatrix();
if (mmpressed) {
offX += (pmx-Main.mX) / scale;
offY += (pmy-Main.mY) / scale;
}
g.translate(-offX * scale, -offY * scale);
g.scale(scale);
if (held != null) {
if (t == HoldType.gate) {
float dx = (Main.mX-pmx) / scale;
float dy = (Main.mY-pmy) / scale;
if (!held.selected) {
// if(!selected.isEmpty()) unselectAll();
held.x+= dx;
held.y+= dy;
} else {
for (Gate cg : selected) {
cg.x+= dx;
cg.y+= dy;
}
}
}
}
for (Gate gate : gates) gate.drawConnections(g);
for (Gate cg : gates) {
g.pushMatrix();
g.translate(cg.x, cg.y);
g.rotate(cg.rot * PConstants.HALF_PI);
cg.draw(g);
g.popMatrix();
}
if (t == HoldType.select) {
g.noStroke();
g.fill(Main.SELECTED);
g.rectMode(g.CORNERS);
g.rect(selectX, selectY, fX(Main.mX), fY(Main.mY));
}
if (held != null) {
if (t == HoldType.out) {
PVector p = held.opsr[heldPos];
g.stroke(Main.CIRCUIT_BORDERS);
g.line(fX(Main.mX), fY(Main.mY), p.x+held.x, p.y+held.y);
}
if (t == HoldType.in) {
PVector p = held.ipsr[heldPos];
g.stroke(Main.CIRCUIT_BORDERS);
g.line(fX(Main.mX), fY(Main.mY), p.x+held.x, p.y+held.y);
}
}
pmx = Main.mX;
pmy = Main.mY;
g.popMatrix();
}
void unselectAll() {
while (!selected.isEmpty()) unselect(selected.get(0));
}
boolean lmpressed = false;
boolean mmpressed;
Gate held;
public float fX(float mX) {
return mX/scale + offX;
}
public float fY(float mY) {
return mY/scale + offY;
}
private Gate clicked;
@Override
public void rightPressedI() {
float mX = fX(Main.mX);
float mY = fY(Main.mY);
for (int i = gates.size()-1; i>=0; i--) {
Gate g = gates.get(i);
if (g.in(mX, mY)) {
clicked = g;
g.click();
break;
}
}
}
@Override
public void rightReleasedI() {
if (clicked != null) {
clicked.unclick();
clicked = null;
}
}
void removeSelected() {
while(!selected.isEmpty()) {
Gate g = selected.get(0);
unselect(g);
g.delete();
gates.remove(g);
}
}
ArrayList<Gate> selected = new ArrayList<>();
@Override
public void simpleClickI() {
float mX = fX(Main.mX);
float mY = fY(Main.mY);
for (int i = gates.size()-1; i>=0; i--) {
Gate g = gates.get(i);
if (g.in(mX, mY)) {
// g.click(); // uncomment to have left click click things
if (selected.contains(g)) unselect(g);
else {
if (!Main.shiftPressed) unselectAll();
select(g);
}
break;
}
}
}
private void select(Gate g) {
selected.add(g);
g.selected = true;
}
private void unselect(Gate g) {
selected.remove(g);
g.selected = false;
}
@Override
public void middlePressedI() {
mmpressed = true;
}
@Override
public void middleReleasedI() {
mmpressed = false;
}
public void importStr(Scanner sc, float x, float y) throws LoadException {
try {
unselectAll();
HashMap<Integer, Gate> m = new HashMap<>();
String key = sc.nextLine();
if (!key.equals("G")) throw new LoadException("Not a gate list!");
int gam = Integer.parseInt(sc.nextLine());
for (int i = 0; i < gam; i++) {
String name = sc.nextLine();
if (!Main.handlers.containsKey(name)) throw new LoadException("No gate "+name+" found in the library");
// System.out.println(name);
Gate g = Main.handlers.get(name).createFrom(sc);
// System.out.println("done");
m.put(i, g);
g.x+= x;
g.y+= y;
gates.add(g);
select(g);
}
int cam = Integer.parseInt(sc.nextLine());
for (int i = 0; i < cam; i++) {
String[] ln = sc.nextLine().split(" ");
Gate og = m.get(Integer.parseInt(ln[0])); // outputting gate
int oi = Integer.parseInt(ln[1]);
Gate ig = m.get(Integer.parseInt(ln[2]));
int ii = Integer.parseInt(ln[3]);
ig.setInput(ii, og.os[oi]);
}
} catch (NumberFormatException e) {
e.printStackTrace();
throw new LoadException("badly formatted input");
}
}
public static String exportStr(ArrayList<Gate> gs) { // outputs a trailing newline
HashMap<Gate, Integer> m = new HashMap<>();
StringBuilder o = new StringBuilder("G\n" + gs.size() + "\n");
float lx = Float.POSITIVE_INFINITY, ly = Float.POSITIVE_INFINITY, bx = Float.NEGATIVE_INFINITY, by = Float.NEGATIVE_INFINITY;
for (Gate g : gs) {
if (g.x < lx) lx = g.x;
if (g.y < ly) ly = g.y;
if (g.x > bx) bx = g.x;
if (g.y > by) by = g.y;
}
for (int i = 0; i < gs.size(); i++) {
Gate g = gs.get(i);
o.append(g.def((lx+bx) / 2, (ly+by)/2)).append("\n");
m.put(g, i);
}
StringBuilder cs = new StringBuilder();
int ctr = 0;
for (Gate g : gs) {
Connection[] is = g.is;
for (int i = 0; i < is.length; i++) {
Connection c = is[i];
if (m.containsKey(c.in)) {
cs.append(m.get(c.in)).append(" ").append(c.ip).append(" ").append(m.get(g)).append(" ").append(i).append("\n");
ctr++;
}
}
}
o.append(ctr).append("\n");
o.append(cs);
return o.toString();
}
public Circuit readOnlyCopy(PGraphics g) {
Circuit n = new ROCircuit();
try {
n.importStr(new Scanner(exportStr(gates)), 0, 0);
} catch (LoadException e) {
e.printStackTrace();
throw new IllegalStateException("Circuit::readOnlyCopy failed to export & import");
}
return n;
}
enum HoldType {
gate, in, out, select
}
private float selectX, selectY;
HoldType t;
private int heldPos;
@Override
protected void leftPressedI() {
float mX = fX(Main.mX);
float mY = fY(Main.mY);
lmpressed = true;
for (int i = gates.size()-1; i>=0; i--) {
Gate g = gates.get(i);
if (g.inIn(mX, mY) != -1) {
held = g;
heldPos = g.inIn(mX, mY);
t = HoldType.in;
return;
}
if (g.outIn(mX, mY) != -1) {
held = g;
heldPos = g.outIn(mX, mY);
t = HoldType.out;
return;
}
if (g.in(mX, mY)) {
held = g;
t = HoldType.gate;
return;
}
}
selectX = mX;
selectY = mY;
t = HoldType.select;
}
@Override
public void leftReleasedI() {
// unselectAll();
float mX = fX(Main.mX);
float mY = fY(Main.mY);
if (t == HoldType.out) {
WireType type = held.ots[heldPos];
for (int i = gates.size()-1; i>=0; i--) {
Gate g = gates.get(i);
if (g.inIn(mX, mY) != -1) {
int p = g.inIn(mX, mY);
if (type.equals(g.its[p]))
g.setInput(p, held.os[heldPos]);
g.warn();
held.warn();
break;
}
}
}
if (t == HoldType.in) {
WireType type = held.its[heldPos];
boolean found = false;
for (int i = gates.size()-1; i>=0; i--) {
Gate g = gates.get(i);
if (g.outIn(mX, mY) != -1) {
int p = g.outIn(mX, mY);
if (type.equals(g.ots[p]))
held.setInput(heldPos, g.os[p]);
g.warn();
held.warn();
found = true;
break;
}
}
if (!found) {
int i = 0;
for (Connection c : held.is) if (c == held.is[heldPos]) i++;
if (i == 1) held.is[heldPos].removeWarnable(held);
held.is[heldPos] = held.its[heldPos].noConnection();
held.is[heldPos].addWarnable(held);
held.warn();
}
}
if (t == HoldType.gate) {
if (Main.mX < 200) {
held.delete();
gates.remove(held);
}
}
if (t == HoldType.select) {
unselectAll();
float lx = Math.min(selectX, mX);
float bx = Math.max(selectX, mX);
float ly = Math.min(selectY, mY);
float by = Math.max(selectY, mY);
for (int i = gates.size()-1; i>=0; i--) {
Gate g = gates.get(i);
if (g.x>lx && g.x<bx && g.y>ly && g.y<by) {
select(g);
}
}
}
lmpressed = false;
held = null;
t = null;
heldPos = -1;
}
}<file_sep>package logicsim.gui;
import logicsim.Main;
import processing.core.PGraphics;
import processing.event.KeyEvent;
import java.util.ArrayList;
public abstract class Drawable {
protected static Drawable focused;
protected final int x;
protected final int y;
public final int w;
public final int h;
protected Drawable(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
sub = new ArrayList<>();
}
ArrayList<Drawable> sub;
public final void drawAll(PGraphics g) {
draw(g);
for (int i = sub.size()-1; i >= 0; i--) {
sub.get(i).drawAll(g);
}
}
protected abstract void draw(PGraphics g);
protected void leftPressedI() { }
protected void leftReleasedI() { }
protected void rightPressedI() { }
protected void rightReleasedI() { }
protected void middlePressedI() { }
protected void middleReleasedI() { }
protected void simpleClickI() { }
public final void simpleClick (){ for(Drawable d:sub) if(d.in(Main.mX,Main.mY)) { d.simpleClick (); return; } focused = this; simpleClickI (); }
public final void leftPressed (){ for(Drawable d:sub) if(d.in(Main.mX,Main.mY)) { d.leftPressed (); return; } focused = this; leftPressedI (); }
public final void rightPressed (){ for(Drawable d:sub) if(d.in(Main.mX,Main.mY)) { d.rightPressed (); return; } focused = this; rightPressedI (); }
public final void middlePressed (){ for(Drawable d:sub) if(d.in(Main.mX,Main.mY)) { d.middlePressed (); return; } focused = this; middlePressedI(); }
public final void leftReleased (){ focused.leftReleasedI (); }
public final void rightReleased (){ focused.rightReleasedI (); }
public final void middleReleased (){ focused.middleReleasedI(); }
public boolean in(int ix, int iy) {
return ix > x && iy > y && ix < x+w && iy < y+h;
}
public void add(Drawable d) {
sub.add(0, d);
}
protected void remove(Drawable d) {
sub.remove(d);
d.stopSelection();
}
private boolean stopSelection() {
if (focused == this) {
focused = null;
return true;
}
for (Drawable d : sub) {
if (d.stopSelection()) return true;
}
return false;
}
protected void key(char key, int keyCode, KeyEvent e) { }
public static void keyD(char key, int keyCode, KeyEvent e) {
if (focused != null) focused.key(key, keyCode, e);
}
protected void mouseWheel(int c) { }
public static void mouseWheelD(int c) {
if (focused != null) focused.mouseWheel(c);
}
}
<file_sep># Another logic circuit simulator
Very much based on [logic.ly](https://logic.ly).
## Mouse things:
- left - select/deselect things
- middle - zoom, move around
- right - click buttons & switches
## Keyboard things:
- ctrl+C, ctrl+V - does what you think (yes, the I/O format is just fancy text); Currently the only way to save things (warning: you'll also want to save `l` too if you've got ICs)
- p - clears the update queue
- q/e - rotate a thing
- i - create an integrated circuit from the selection (the input/output fields are space-separated lists in top-to-bottom drawing order). The names of the pins are the settable names clicking the I/O objects one-by-one
- l - copy all the ICs to clipboard
- delete - deletes selected things
- ctrl+I - import integrated circuits
## To run,
1. `./build`
2. `./run`<file_sep>package logicsim.gates;
import logicsim.*;
import processing.core.*;
import static logicsim.wiretypes.BasicWire.*;
public class NandGate extends Gate {
public NandGate(float x, float y, int rot) {
super(TWO_WIRES, ONE_WIRE, x, y, rot,
new PVector[]{new PVector(-35, 10), new PVector(-35, -10)},
new PVector[]{new PVector(40, 0)}
);
}
public static GateHandler handler() {
return s -> {
String[] a = s.nextLine().split(" ");
return new NandGate(Float.parseFloat(a[0]), Float.parseFloat(a[1]), Integer.parseInt(a[2]));
};
}
@Override
public void process() {
BasicConnection ca = (BasicConnection) is[0];
BasicConnection cb = (BasicConnection) is[1];
BasicConnection oc = (BasicConnection) os[0];
boolean a = (ca).b;
boolean b = cb.b;
oc.set(!(a & b));
}
@Override
public void draw(PGraphics g) {
g.ellipseMode(g.RADIUS);
g.strokeWeight(3);
if (selected) {
g.noStroke();
g.fill(Main.SELECTED);
g.beginShape();
g.vertex(-0, +25);
g.vertex(-25, +25);
g.vertex(-25, -25);
g.vertex(-0, -25);
for(int i = 0; i < 31; i++) {
double r = i/30d * Math.PI;
g.vertex((float) Math.sin(r) * 25, (float) Math.cos(r) * 25);
}
g.endShape(PConstants.CLOSE);
}
g.fill(Main.CIRCUIT_COLOR);
g.stroke(Main.CIRCUIT_BORDERS);
g.line( 20, 0, 40, 0); // output line
g.line(-20, 10, -35, 10); // input lines
g.line(-20, -10, -35, -10); // input lines
g.ellipse(24, 0, 4, 4); // invert
g.ellipse(0, 0, 20, 20); // elliptical body
g.beginShape(); // rectangular body
g.vertex( 0, 20);
g.vertex(-20, 20);
g.vertex(-20, -20);
g.vertex( 0, -20);
g.endShape();
drawIO(g);
}
@Override
public boolean in(float mx, float my) {
mx-=x;
my-=y;
return mx*mx + my*my <= 20*20 || my>0 && my<20 && Math.abs(mx)<20;
}
@Override
public Gate cloneCircuit(float x, float y) {
return new NandGate(x, y, rot);
}
}
<file_sep>#!/bin/bash
rm -f sim.jar
rm -rf src/build/sim
cd src
mkdir -p build
javac -cp .:../lib/* -Xmaxerrs 1000 -d ./build $(find logicsim -name '*.java')<file_sep>package logicsim.gates;
import logicsim.*;
import processing.awt.PGraphicsJava2D;
import processing.core.*;
import java.awt.*;
import static logicsim.wiretypes.BasicWire.BasicConnection;
public class CustomGate extends Gate {
public final CustomGateFactory f;
private Gate[] igs;
private Gate[] ogs;
private ROCircuit c;
private int width;
private int height;
public CustomGate(WireType[] its, WireType[] ots, float x, float y, int rot, CustomGateFactory f, PVector[] ips, PVector[] ops, int width, int height) {
super(its, ots, x, y, rot, ips, ops);
this.width = width;
this.height = height;
this.f = f;
refresh();
}
private void refresh() {
c = f.c.readOnlyCopy(Main.instance.g);
c.calculateEdges();
igs = new Gate[its.length];
for (int i = 0; i < f.ins.length; i++) {
String name = f.ins[i];
for (Gate g : c.gates)
if (name.equals(g.name)) {
igs[i] = g;
break;
}
if (igs[i] == null) throw new Error("No input labeled "+name+" found");
}
ogs = new Gate[ots.length];
for (int i = 0; i < f.ons.length; i++) {
String name = f.ons[i];
for (Gate g : c.gates)
if (name.equals(g.name)) {
ogs[i] = g;
assert g instanceof LampGate;
g.is[0].addWarnable(this);
break;
}
if (ogs[i] == null) throw new Error("No output labeled "+name+" found");
}
}
public static GateHandler handler() {
return s -> {
String name = s.nextLine();
if (!Main.gateLibrary.containsKey(name)) throw new LoadException("IC "+name+" unknown");
String[] a = s.nextLine().split(" ");
CustomGateFactory f = Main.gateLibrary.get(name);
return f.create(Float.parseFloat(a[0]), Float.parseFloat(a[1]), Integer.parseInt(a[2]));
};
}
@Override
public void process() {
for (int i = 0; i < igs.length; i++) {
Gate g = igs[i];
// System.out.println(i+"--"+g+"--"+ Arrays.toString(is));
g.forwardConnection(is[i]);
}
for (int i = 0; i < ogs.length; i++) {
Gate g = ogs[i];
BasicConnection c = (BasicConnection) g.giveConnection();
BasicConnection oc = (BasicConnection) os[i];
oc.set(c.b);
}
}
@Override
public Gate cloneCircuit(float x, float y) {
return new CustomGate(its, ots, x, y, rot, f, ips, ops, width, height);
}
@Override
public void draw(PGraphics g) {
float change;
if (g instanceof PGraphicsJava2D) {
g.pushMatrix();
// g.translate(x, y);
g.scale(.05f);
Graphics2D i = ((PGraphicsJava2D) g).g2;
float[] pts = new float[]{c.lx, c.ly, c.bx, c.by, 0, 0, 10, 0};
float[] opts = new float[8];
i.getTransform().transform(pts, 0, opts, 0, 4);
if (opts[0] > opts[2]) {
float t = opts[0];
opts[0] = opts[2];
opts[2] = t;
}
if (opts[1] > opts[3]) {
float t = opts[1];
opts[1] = opts[3];
opts[3] = t;
}
float lX = Math.max(opts[0], 0);
float rX = Math.min(opts[2], g.width);
float bY = Math.max(opts[1], 0);
float tY = Math.min(opts[3], g.height);
float t = Math.abs(opts[6] - opts[4] + opts[7]-opts[5]);
if (rX > lX && tY > bY) {
change = PApplet.constrain(PApplet.map(t, 1, 5, 0, 1), 0, 1);
} else {
change = 0;
}
// System.out.println(t+" "+change);
g.popMatrix();
} else change = 0; // :(
g.rectMode(g.RADIUS);
if (selected) {
g.noStroke();
g.fill(Main.SELECTED);
g.rect(0, 0, width+5, height+5);
}
g.stroke(Main.CIRCUIT_BORDERS);
int rgb = Main.instance.lerpColor(Main.CIRCUIT_COLOR, Main.BG, change);
g.fill(rgb);
g.strokeWeight(3);
g.rect(0, 0, width, height); // main rect
int mask = ((int) (255-change*255) << 24);
if (change > 0) { // update inner circuit
Main.ctr++;
g.pushMatrix();
// g.translate(x, y);
g.scale(.05f);
c.draw(g);
g.popMatrix();
g.rectMode(g.RADIUS);
g.fill(rgb&0xffffff | mask);
g.strokeWeight(3);
g.rect(0, 0, width, height); // main rect
}
g.textSize(10);
g.textAlign(g.LEFT, g.CENTER);
int textcol = Main.TEXT_COLOR & 0xffffff | mask;
g.stroke(Main.CIRCUIT_BORDERS);
for (int i = 0; i < its.length; i++) {
float cy = (i - its.length / 2f + .5f) * 20;
g.line(-width, cy, -width - 20, cy);
}
for (int i = 0; i < ots.length; i++) {
float cy = (i - ots.length / 2f + .5f) * 20;
g.line(width, cy, width + 20, cy);
}
g.fill(textcol);
if (textcol < 0 || textcol > 255) {
for (int i = 0; i < its.length; i++) {
float cy = (i - its.length / 2f + .5f) * 20;
g.text(f.ins[i], -width + 2, cy - 1);
}
g.textAlign(g.RIGHT, g.CENTER);
for (int i = 0; i < ots.length; i++) {
float cy = (i - ots.length / 2f + .5f) * 20;
g.text(f.ons[i], width - 2, cy - 1);
}
}
g.pushMatrix();
g.rotate(PConstants.HALF_PI);
g.textAlign(PConstants.CENTER, PConstants.CENTER);
g.fill(textcol==0? 0x00ffffff : textcol);
g.text(f.name, 0, 0);
g.popMatrix();
drawIO(g);
}
@Override
public boolean in(float mx, float my) {
return Math.abs(mx-x) < 20 && Math.abs(my-y) < height;
}
@Override
public String def(float xoff, float yoff) {
String[] ss = getClass().getName().split("\\.");
return ss[ss.length-1] + "\n" + f.name + "\n" + (x-xoff)+" "+(y-yoff)+" "+rot;
}
}
<file_sep>#!/bin/bash
cd src/build
java -cp ../../lib/*:. logicsim.Main
cd ..
cd ..<file_sep>package logicsim.gui;
import logicsim.*;
import processing.core.*;
public class Menu extends Drawable {
public final GateTF tf;
public Menu(int x, int y, int w, int h) {
super(x, y, w, h);
tf = new GateTF(x+20, y+60, w-40, Main.TEXTFIELD_HEIGHT);
add(tf);
}
@Override
protected void draw(PGraphics g) {
g.rectMode(PConstants.CORNER);
g.strokeWeight(3);
g.stroke(Main.MENU_STROKE);
g.fill(Main.MENUBG);
g.rect(x, y, w, h);
g.textSize(20);
g.textAlign(PConstants.LEFT, PConstants.CENTER);
g.fill(Main.TEXT_COLOR);
g.text("I/O name", x+20, y+30);
}
public void bind(Gate g) {
tf.bind(g);
}
public static class GateTF extends TextField {
public Gate g;
GateTF(int x, int y, int w, int h) {
super(x, y, w, h);
}
void bind(Gate g) {
this.g = g;
text = g.name;
}
@Override
protected void updated() {
g.name = text;
}
}
}
<file_sep>package logicsim.gates;
import logicsim.*;
import processing.core.*;
import static logicsim.wiretypes.BasicWire.*;
public class LatchGate extends Gate {
public LatchGate(float x, float y, int rot) {
this(x, y, rot, false);
}
private boolean on;
private LatchGate(float x, float y, int rot, boolean on) {
super(TWO_WIRES, ONE_WIRE, x, y, rot,
new PVector[]{new PVector(-40, -10), new PVector(-40, 10)},
new PVector[]{new PVector(40, 0)}
);
this.on = on;
if (on) warn();
}
public static GateHandler handler() {
return s -> {
String[] a = s.nextLine().split(" ");
String on = s.nextLine();
return new LatchGate(Float.parseFloat(a[0]), Float.parseFloat(a[1]), Integer.parseInt(a[2]), on.equals("1"));
};
}
@Override
public void process() {
BasicConnection oc = (BasicConnection) os[0];
boolean a = ((BasicConnection) is[0]).b;
boolean b = ((BasicConnection) is[1]).b;
if (b) on = a;
oc.set(on);
}
@Override
public Gate cloneCircuit(float x, float y) {
return new LatchGate(x, y, rot, on);
}
@Override
public String def(float xoff, float yoff) {
return "LatchGate\n"+(x-xoff)+" "+(y-yoff)+" "+rot+"\n"+(on?"1":"0");
}
@Override
public void draw(PGraphics g) {
g.stroke(Main.CIRCUIT_BORDERS);
g.fill(Main.CIRCUIT_COLOR);
g.strokeWeight(3);
g.rectMode(g.RADIUS);
g.rect(0, 0, 20, 20);
g.line(20, 0, 40, 0);
g.line(-20, 10, -40, 10);
g.line(-20, -10, -40, -10);
g.fill(Main.TEXT_COLOR);
g.textAlign(g.LEFT, g.CENTER);
g.textSize(10);
g.text("I", -18, -10);
g.text("save", -18, 10);
drawIO(g);
}
}
<file_sep>package logicsim;
import logicsim.gui.Drawable;
import processing.core.*;
public class SelectionCircuit extends Circuit {
public SelectionCircuit(int x, int y, int w, int h) {
super(x, y, w, h);
}
@Override
public void draw(PGraphics g) {
g.noStroke();
g.fill(Main.SELBG);
g.rectMode(g.CORNER);
g.rect(x, y, w, h);
g.pushMatrix();
if (mmpressed) {
offX += (pmx-Main.mX) / scale;
offY += (pmy-Main.mY) / scale;
}
g.translate(-offX * scale, -offY * scale);
g.scale(scale);
for (Gate cg : gates) {
g.pushMatrix();
g.translate(cg.x, cg.y);
g.rotate(cg.rot * PConstants.HALF_PI);
cg.draw(g);
g.popMatrix();
}
g.popMatrix();
pmx = Main.mX;
pmy = Main.mY;
}
@Override
protected void leftPressedI() {
float mX = fX(Main.mX);
float mY = fY(Main.mY);
EditableCircuit mb = Main.mainBoard;
for (Gate g : gates) {
if (g.in(mX, mY)) {
Gate n = g.cloneCircuit(mb.fX(Main.mX), mb.fY(Main.mY));
mb.add(n);
mb.held = n;
mb.t = HoldType.gate;
mb.lmpressed = true;
Drawable.focused = mb;
}
}
lmpressed = true;
}
@Override
public void rightPressedI() { }
@Override
public void rightReleasedI() { }
@Override
public void leftReleasedI() { }
@Override
public void simpleClickI() { }
}
| 42fe8a7894b4b578172866dd85e441e34ca80a9b | [
"Markdown",
"Java",
"Shell"
]
| 12 | Java | dzaima/logicsim | c1726c7485e05ce73d226a35ce3c41f8c6690dff | ced8889c11660e483ea3ae23ca599e493edc5ad5 |
refs/heads/master | <repo_name>15151873042/boot-all<file_sep>/boot-web/src/main/java/com/hp/servlet/MyServletContextListener.java
package com.hp.servlet;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class MyServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("ServletContext初始化");
}
}
<file_sep>/boot-web/src/main/java/com/hp/servlet/ServleltConfig.java
package com.hp.servlet;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServleltConfig {
@Bean
public ServletListenerRegistrationBean<ServletContextListener> myServletContextListener() {
MyServletContextListener myServletContextListener = new MyServletContextListener();
ServletListenerRegistrationBean<ServletContextListener> servletListenerRegistrationBean =
new ServletListenerRegistrationBean<>(myServletContextListener);
return servletListenerRegistrationBean;
}
public static class MyServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// System.out.println("MyServletContextListener初始化");
}
}
}
<file_sep>/boot-dao/src/main/java/com/hp/base/qo/BaseQO.java
package com.hp.base.qo;
import java.io.Serializable;
import com.hp.base.model.Dict;
import hp.boot.mybatis.pojo.Page;
public class BaseQO extends Page<Dict> implements Serializable{
/** */
private static final long serialVersionUID = 1L;
}
<file_sep>/boot-service/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.hp</groupId>
<artifactId>boot-all</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>boot-service</artifactId>
<dependencies>
<dependency>
<groupId>com.hp</groupId>
<artifactId>boot-dao</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.hp.boot</groupId>
<artifactId>hp-spring-boot-start-web</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.hp.boot</groupId>
<artifactId>hp-spring-boot-start-redis</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.8</version>
</dependency>
</dependencies>
</project><file_sep>/boot-web/src/main/java/com/hp/MainApplication.java
package com.hp;
import org.redisson.spring.session.config.EnableRedissonHttpSession;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import hp.boot.transaction.config.annotation.EnableTransactionCommonConfig;
import hp.boot.web.config.annotation.EnableWebMvcCommonConfig;
@SpringBootApplication
@EnableWebMvcCommonConfig
@EnableTransactionCommonConfig
@EnableRedissonHttpSession(keyPrefix = "custom:session:")
public class MainApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(MainApplication.class);
}
}
<file_sep>/boot-service/src/main/java/com/hp/service/impl/DictServiceImpl.java
package com.hp.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hp.base.mapper.DictMapper;
import com.hp.base.model.Dict;
import com.hp.base.qo.BaseQO;
import com.hp.service.DictService;
@Service("dictService")
public class DictServiceImpl implements DictService {
@Autowired
private DictMapper dictMapper;
@Override
public List<Dict> getAllDictList() {
List<Dict> allDictList = dictMapper.getAllDictList();
return allDictList;
}
@Override
public void updateIncreVersion() {
Dict dict = new Dict();
dict.setId("app0000000000000101");
dictMapper.updateIncreVersion(dict);
}
@Override
public void asycnTest() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public Object getListPage() {
BaseQO qo = new BaseQO();
List<Dict> list = dictMapper.getListPage(qo);
return list;
}
}
<file_sep>/boot-web/src/main/java/com/hp/bean/User.java
package com.hp.bean;
public class User {
private ImportBean importBean;
public ImportBean getImportBean() {
return importBean;
}
public void setImportBean(ImportBean importBean) {
this.importBean = importBean;
}
}
| 4f3a968e2c85c90b62f2db0a8257173b983822a3 | [
"Java",
"Maven POM"
]
| 7 | Java | 15151873042/boot-all | 055737ee760f080d79c0d8b0b6d6cbb4052c6240 | eabd21c3872c75cdf2751a9a081ea9fe7bf70093 |
refs/heads/master | <repo_name>mahokie/foobar<file_sep>/foo.go
package main
import "fmt"
func main() {
fmt.Println("Hello world!")
}
// this change is on 'mybranch' only
| 24313350d532d41558d0b2b1c96a83eccc84ef03 | [
"Go"
]
| 1 | Go | mahokie/foobar | ac1ce42aa9880b4a69fd9390ba3b1bac03882812 | 0bef968f70a77462cdbb8ce2c0dba61d86f32a9c |
refs/heads/master | <file_sep>Introduction à Docker
=====================
Slides de présentation avec des démonstrations simples.
# Consulter la présentation
Lancer le script `build.sh` pour construire les slides et ouvrir la présentation `slides.html` avec votre navigateur.
# Consulter les démonstrations
Les démonstrations sont dans le dossier `demos`.
## Demo Pandoc
La démonstration Pandoc introduit le concept de volume et est en charge de construire les slides de présentation.
<file_sep>% Un introduction à Docker
% <NAME>
% Présentation du __DATE__
# Le constat
## Un projet classique
> - Durant votre dernier projet informatique, vous avez pu développer une application web sur votre poste de travail
> - La date de rendu approche et l'application doit être installable facilement afin d'être évaluée par l'enseignant
. . .
> Comment procédez-vous ?
## La jungle applicative
Les projets modernes s'appuient désormais sur un grand nombre d'outils variés.
Chaque brique possède ses propres spécificités de mise en place selon l'environnement et nécessite un effort d'adaptation plus ou moins important selon sa complexité.
## Illustration

## La matrice application / environnement
------- --- --- --- ---
Static Website ? ? ? ?
Database ? ? ? ?
Backend API ? ? ? ?
Frontend Website ? ? ? ?
Workstation QA Server Cloud Cluster
------- --- --- --- ---
. . .
> L'effort d'adaptation doit être pensé pour chaque environnement sur lequel l'application est déployée.
# Une solution
## Le monde industriel
Avant 1960

## Introduction du conteneur
Après 1960

## Introduction de Docker
Docker est un logiciel libre qui automatise le déploiement d'applications dans des conteneurs logiciels.

> « Docker est un outil qui peut empaqueter une application et ses dépendances dans un conteneur virtuel, qui pourra être exécuté sur n'importe quel serveur Linux »
## Illustration

## Apports de Docker
Docker apporte une réponse à la problématique de la séparation entre les applicatifs et l'infrastructure.
> - Le conteneur est autosuffisant et prend en charge les contraintes de l'application
> - Les applicatifs ne sont plus dépendants de la machine physique ou virtuelle sur laquelle ils sont déployés et inversement
> - Le conteneur peut être manipulé en utilisant un jeu de commandes standard applicable sur n’importe quelle plate-forme
## La jungle applicative
La matrice se simplifie grandement
------- --- --- --- ---
Static Website Container Container Container Container
Database Container Container Container Container
Backend API Container Container Container Container
Frontend Website Container Container Container Container
Workstation QA Server Cloud Cluster
------- --- --- --- ---
## Design de Docker

## Fonctionnement interne

## Pourquoi utiliser Docker
> - Docker utilise libcontainer comme système de virtualisation, plus léger qu'une virtualisation complète du système
> - Docker repose sur des concepts et technologies connues, stables et modernes (API, Go, etc...)
> - Déploiement rapide et répétable à l'infini
> - S'exécute n'importe où (tant qu'on a un noyau linux > 2.6)
. . .
> Passage progressif vers un modèle DevOps
## Qui utilise Docker

# Show Time!
## Premier conteneur 1/2
Commençons simplement par récupérer l'image de référence :
```{.bash}
$ docker pull debian:jessie
```
Lançons ensuite notre première commande :
```{.bash}
$ docker run -it debian:jessie echo "Hello World"
```
. . .
Grâce à cette commande, nous avons exécuté notre premier processus dans un conteneur.
## Premier conteneur 2/2
À l'issue de l'exécution de la commande, il est possible de consulter l'état des conteneurs sur la machine :
```{.bash}
$ docker ps -a
```
```
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b90302cc3c47 debian:jessie "/bin/bash" About a minute ago Exited (0) 4 seconds ago fervent_wright
```
## Manipulation directe
Il est possible aussi d'entrer dans le conteneur afin d'y effectuer des opérations :
```{.bash}
$ docker run -it debian:jessie
```
. . .
Par défaut, le point d'entrée dans le conteneur debian est `/bin/bash`
On se retrouve donc ensuite avec un prompt bien connu :
```{.bash}
root@b90302cc3c47:/# echo "Hello World"
```
## Garder une trace de son travail
Nous pouvons altérer le conteneur en effectuant des modifications. Il suffit ensuite de sauvegarder, à la manière d'une gestion de configuration, ses modifications :
```{.bash}
$ docker commit -m "Premier commit de conteneur" \
b90302cc3c47 docker-demo/docker0
```
. . .
On peut ensuite contrôler que l'image a bien été reférencée en local :
```
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
docker-demo/docker0 latest 8bad3c5a9f22 6 seconds ago 125.1 MB
debian jessie 6845b83c79fb 10 days ago 125.1 MB
```
## Next level 1/2
La manipulation directe des conteneurs telle que nous l'avons vu présente plusieurs inconvénients :
- Nécessite de documenter à coté les modifications effectuées sur le conteneur
- Oblige à sauvegarder des images parfois volumineuses
- N'est pas facilement transportable entre les projets
. . .
> Dès lors, il faut passer à la vitesse supérieure en décrivant ses conteneurs.
## Next level 2/2
Le **Dockerfile** répond à la problématique de description du conteneur.
Par exemple, voici un conteneur décrit à l'aide de ce fichier :
```{.bash}
FROM debian:jessie
CMD ["echo", "Hello World"]
```
. . .
Construction
```{.bash}
$ docker build -t docker-demo/hello .
```
. . .
Lancement
```{.bash}
$ docker run -it docker-demo/hello
```
# Pour aller plus loin
## Registry et hub Docker
Le registry Docker principal (hub) est comparable à Github pour les images Docker.
. . .
Des dizaines d'images préfabriquées prêtes à l'usage sont disponibles !
Exemple PHP + Apache :
```{.bash}
FROM php:5.6-apache
COPY src/ /var/www/html/
```
## Quelques ressources à consulter
Docker
- Documentation Docker : [https://docs.docker.com/](https://docs.docker.com/)
- Hub Docker : [https://hub.docker.com/](https://hub.docker.com/)
- Liste d'outils pour Docker : [http://veggiemonk.github.io/awesome-docker/](http://veggiemonk.github.io/awesome-docker/)
Cette présentation
- Slides et démos : [https://github.com/64q/docker-introduction](https://github.com/64q/docker-introduction)
## Questions
Me contacter
[quentin.lebourgeois at soprasteria.com](mailto:quentin.lebourgeois at soprasteria.com)
<file_sep>#!/bin/bash
set -e
# locale
export LC_ALL=fr_FR.UTF-8
export LANG=fr_FR.UTF-8
export LANGUAGE=fr_FR.UTF-8
# constantes
REVEALJS_CONFIG="-V slideNumber=true -V theme=black -V controls=true -V history=true -V width=\"100%\" -V height=\"100%\""
CURRENT_DATE=`date "+%A %d %B %Y"`
# fonctions
var_replace()
{
# gestion de la date (pattern __DATE__)
cat $1 | sed -e "s/__DATE__/$CURRENT_DATE/g" > tmp/$1.vr
}
# install reveal.js
if ! [[ -d "reveal.js" ]]; then
echo "installation de reval.js 3.1.0..."
wget https://github.com/hakimel/reveal.js/archive/3.1.0.zip \
&& unzip 3.1.0.zip \
&& mv reveal.js-3.1.0 reveal.js \
&& rm 3.1.0.zip
fi
# nettoyage
rm -f slides.html
rm -rf tmp/ && mkdir tmp/
# remplacement des variables dans les présentations
var_replace slides.md
# construction des slides du techlunch 1
pandoc -t revealjs $REVEALJS_CONFIG -s tmp/slides.md.vr -o slides.html
<file_sep>#!/bin/bash
docker build -t docker-demo/php .
docker run -p 8080:80 -d docker-demo/php
<file_sep>#!/bin/bash
cp ../../build.sh .
cp ../../slides.md .
# demo docker pandoc
# construction du conteneur
docker build -t docker-demo/pandoc .
# lancement de la compilation
docker run -v $PWD/tmp:/output -it docker-demo/pandoc
# vérification des slides
cat tmp/slides.html
rm build.sh
rm slides.md
<file_sep>#!/bin/bash
/pandoc/build.sh \
&& mv /pandoc/slides.html /output
<file_sep>FROM debian:jessie
#ENV HTTP_PROXY http://ntes.proxy.corp.sopra:8080
#ENV HTTPS_PROXY $HTTP_PROXY
#ENV http_proxy $HTTP_PROXY
#ENV https_proxy $HTTP_PROXY
ENV PANDOC_VERSION 1.15.2
WORKDIR /pandoc
RUN apt-get -y update && apt-get -y install \
wget \
unzip
RUN wget https://github.com/jgm/pandoc/releases/download/$PANDOC_VERSION/pandoc-$PANDOC_VERSION-1-amd64.deb \
&& dpkg -i pandoc-$PANDOC_VERSION-1-amd64.deb
VOLUME ["/output"]
COPY build.sh /pandoc/
COPY slides.md /pandoc/
COPY entrypoint.sh /usr/bin/
CMD ["/usr/bin/entrypoint.sh"]
| b00fc1c48e5ae93bf0564fc60dc37399ef24a85a | [
"Markdown",
"Dockerfile",
"Shell"
]
| 7 | Markdown | 64q/docker-introduction | b8e14c4677da6d21ec175162a63f3865ae39a3e6 | abd900248abc42aa00068c6edaaf9c6655dc7b86 |
refs/heads/master | <repo_name>eGarciaR/BurglarDetection<file_sep>/README.md
# BurglarDetection
This service is an application component used to perform a running task in background. This service can run in the background indefinitely, even if component that started the service is destroyed. Usually a service always performs a single operation and stops itself once intended task is complete.
<file_sep>/.gradle/2.8/taskArtifacts/cache.properties
#Sun Feb 21 13:53:16 CET 2016
<file_sep>/app/src/main/java/com/example/hackupc/usingservices/HelloActivity.java
package com.example.hackupc.usingservices;
/**
* Created by ericgarciaribera on 20/02/16.
*/
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class HelloActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello);
//starting service
findViewById(R.id.start_service).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(HelloActivity.this, HelloService.class);
startService(intent);
}
});
//service onDestroy callback method will be called
findViewById(R.id.stop_Service).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(HelloActivity.this, HelloService.class);
stopService(intent);
}
});
}
@Override
public void onResume() {
super.onResume();
}
}
| 0a8274db4ebcc5f88bb6d064cd59840e65b2fd6b | [
"Markdown",
"Java",
"INI"
]
| 3 | Markdown | eGarciaR/BurglarDetection | 7128e73699a536a63eb8f8cda2c960c971280051 | 7dda7bea2656d1903d367a3b2237851001640e54 |
refs/heads/master | <file_sep>[](https://codebeat.co/projects/github-com-blastar-swift-soap-with-alamofire)
# Swift-SOAP-with-Alamofire
This repository serves as example project for using SOAP with Swift as described at http://www.blastar.biz/2016/08/09/swift-how-to-consume-soap-using-alamofire/
<file_sep>//
// ViewController.swift
// Swift-SOAP-with-Alamofire
//
// Created by <NAME> on 04.08.2016.
// Copyright © 2016 biz.blastar. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
var countryList = [Country]()
override func viewDidLoad() {
super.viewDidLoad()
APIService.getCountries { (countries) in
self.countryList = countries
self.tableView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return countryList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = countryList[indexPath.row].name
return cell
}
}
<file_sep>use_frameworks!
target 'Swift-SOAP-with-Alamofire' do
pod 'Alamofire'
pod 'SWXMLHash'
pod 'AEXML'
pod 'StringExtensionHTML'
end
<file_sep>//
// APIService.swift
// Swift-SOAP-with-Alamofire
//
// Created by <NAME> on 01/03/2018.
// Copyright © 2018 biz.blastar. All rights reserved.
//
import UIKit
import Alamofire
import SWXMLHash
import StringExtensionHTML
import AEXML
struct Country {
var name:String = ""
}
class APIService {
class func getCountries(completion: @escaping (_ result: [Country]) -> Void) -> Void {
var countries = [Country]()
let soapRequest = AEXMLDocument()
let envelopeAttributes = ["xmlns:SOAP-ENV" : "http://schemas.xmlsoap.org/soap/envelope/",
"xmlns:ns1" : "http://www.webserviceX.NET"]
let envelope = soapRequest.addChild(name: "SOAP-ENV:Envelope", attributes: envelopeAttributes)
let body = envelope.addChild(name: "SOAP-ENV:Body")
body.addChild(name: "ns1:GetCountries")
let soapLength = String(soapRequest.xml.count)
let requestURL = URL(string: "http://www.webservicex.net/country.asmx")
var mutableR = URLRequest(url: requestURL!)
mutableR.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
mutableR.addValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
mutableR.addValue(soapLength, forHTTPHeaderField: "Content-Length")
mutableR.httpMethod = "POST"
mutableR.httpBody = soapRequest.xml.data(using: String.Encoding.utf8)
Alamofire.request(mutableR)
.responseString { response in
if let xmlString = response.result.value {
let xml = SWXMLHash.parse(xmlString)
let body = xml["soap:Envelope"]["soap:Body"]
if let countriesElement = body["GetCountriesResponse"]["GetCountriesResult"].element {
let getCountriesResult = countriesElement.text
let xmlInner = SWXMLHash.parse(getCountriesResult.stringByDecodingHTMLEntities)
for element in xmlInner["NewDataSet"]["Table"].all {
if let nameElement = element["Name"].element {
var country = Country()
country.name = nameElement.text
countries.append(country)
}
}
}
completion(countries)
}else{
print("error fetching XML")
}
}
}
}
| 18ff16a7ff32b0b17530b350f65554a2a76121b8 | [
"Markdown",
"Ruby",
"Swift"
]
| 4 | Markdown | Arvinwolf91/Swift-SOAP-with-Alamofire | e65c37759adb19146998c8e717005cef6c33e98d | aff0dd5889550c08bf2a1847bc82d4e3d6d0e79b |
refs/heads/master | <file_sep><?php
/**
* Created by PhpStorm.
* User: andriy
* Date: 13.12.16
* Time: 14:43
*
* see sample http://silex.sensiolabs.org/doc/master/providers/security.html
*/
namespace App\Services;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use App\Models\User;
class UserProvider implements UserProviderInterface
{
public function loadUserByUsername($username)
{
if (false) {
throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
}
return new User($username, explode(',', 'ROLE_MANAGER'));
}
public function refreshUser(UserInterface $user)
{
// TODO: Implement refreshUser() method.
return $user;
}
public function supportsClass($class)
{
return $class = User::class;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: andrey
* Date: 04.12.16
* Time: 17:27
*/
use Silex\Application;
use Silex\Provider\AssetServiceProvider;
use Silex\Provider\TwigServiceProvider;
use Silex\Provider\ServiceControllerServiceProvider;
use Silex\Provider\HttpFragmentServiceProvider;
use Silex\Provider\MonologServiceProvider;
use Silex\Provider\WebProfilerServiceProvider;
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
//echo (in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1','172.20.0.4'))) ? "<br>1" : "<br>0";
//echo (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) ? "<br>1" : "<br>0";
if (
isset($_SERVER['HTTP_X_FORWARDED_FOR'])
&& !in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1','172.20.0.4'))
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
/* @var $app Silex\Application */
$app->register(new ServiceControllerServiceProvider());
$app->register(new AssetServiceProvider());
$app->register(new TwigServiceProvider());
$app->register(new HttpFragmentServiceProvider());
$app->register(new \App\ServiceProviders\JWTProvider());
$app->register(new \App\ServiceProviders\UserProviderServiceProvider());
$app->register(new \App\ServiceProviders\UrlGeneratorServiceProvider(), [
'url.report.file' => '/reports/file'
]);
/*$app->register(new JMSServiceProvider(), [
'jms.metadata-dir' => __DIR__ . "/config/metadata",
]);*/
$app['twig'] = $app->extend('twig', function ($twig) {
return $twig;
});
$app['twig.path'] = array(__DIR__.'/../templates');
$app['twig.options'] = array('cache' => __DIR__.'/../var/cache/twig');
$app->register(new MonologServiceProvider(), array(
'monolog.logfile' => __DIR__.'/../var/logs/silex_dev.log',
'monolog.level' => (getenv('LOG_LEVEL') !== false ? getenv('LOG_LEVEL') : 'INFO'),
));
if ($app['debug']) {
$app->register(new WebProfilerServiceProvider(), array(
'profiler.cache_dir' => __DIR__.'/../var/cache/profiler',
));
}
<file_sep>#!/bin/bash
docker exec -ti reports-dev /bin/bash | 1ecda5fb02560ef0e6b3a113f47a9f190c02b595 | [
"PHP",
"Shell"
]
| 3 | PHP | anddorua/lo-reports | 62710ea80f76a389063336f35e3694ddd80d9520 | 4bd2558b4e94030a70adf412f3e75c41f86c222c |
refs/heads/master | <repo_name>yuemelz/flower<file_sep>/src/Flower.cpp
//
// Flower.cpp
// flower
//
// Created by Z on 12/5/17.
//
#include "Flower.hpp"
Flower::Flower(){
}
void Flower::setup( int _min, int _max, float _freq){
min = _min;
max = _max;
freq = _freq;
}
void Flower::setPosition(ofVec2f _pos){
position.x = _pos.x;
position.y = _pos.y;
// if (position.x > ofGetWidth()){
// position.x = 0;
// }
}
void Flower::update(){
position.x ++;
theta ++;
position.y = ofMap(sin(theta * freq), -1, 1, min, max);
}
void Flower::draw(){
img.draw(position.x, position.y);
}
<file_sep>/src/ofApp.cpp
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
// theta = 0;
serial.listDevices();
vector <ofSerialDeviceInfo> deviceList = serial.getDeviceList();
int baud = 9600;
serial.setup(1, 9600);
// serial.setup("/dev/cu.usbmodem1421", 9600);
int numFlower = 4;
for(int i = 0; i < numFlower; i++){
Flower temp = Flower();
temp.img.load(ofToString(i+1)+".png");
flowers.push_back(temp);
}
flowers[0].setup(30, 70, 0.03);
flowers[1].setup(150, 190, 0.01);
flowers[2].setup(400, 440, 0.05);
flowers[3].setup(590, 620, 0.1);
}
//--------------------------------------------------------------
void ofApp::update(){
if (serial.available()) {
int value = serial.readByte();
cout << "value is: "<<value<<endl;
if (serial.available() == 2){
start = true;
}
}
if(start == true){
for (int i = 0; i < flowers.size(); i ++){
flowers[i].update();
cout<<"flower["<<i<<": " << flowers[i].position.x << ", " <<flowers[i].position.y<<endl;
if (flowers[i].position.x > ofGetWidth()){
flowers[i].position.x = 0;
}
}
}
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackground(255);
for (int i = 0; i < flowers.size(); i++) {
flowers[i].draw();
}
// flower.draw(position.x, position.y);
// ofPushMatrix();
// ofRotate(30);
// image.draw(xPos, yPos*5, 90, 90);
// ofPopMatrix();
//
// image2.draw(xPos, yPos2*3, 60, 60);
//
// ofPushMatrix();
// ofRotate(10);
// image3.draw(xPos3, yPos3*7, 40, 40);
// ofPushMatrix();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
<file_sep>/src/Flower.hpp
//
// Flower.hpp
// flower
//
// Created by Z on 12/5/17.
//
#ifndef Flower_hpp
#define Flower_hpp
#include <stdio.h>
#include "ofMath.h"
#include "ofMain.h"
#endif /* Flower_hpp */
class Flower{
public:
Flower();
void setup( int _min, int _max, float _freq);
void setPosition(ofVec2f _pos);
void update();
void draw();
ofImage img;
ofVec2f position;
int min;
int max;
float freq;
float theta = 0;
};
| 276bb01be8b912c69281c3065234fe0e805850ff | [
"C++"
]
| 3 | C++ | yuemelz/flower | 6936e0af2ca457a686601f2282f8b52b4d7cd8be | 6695689a5624acbcfe348bd1d7d37d9de7752bc6 |
refs/heads/master | <repo_name>cbrgm/worldgeneration<file_sep>/src/dungeongeneration/worldgeneration/Room.java
package dungeongeneration.worldgeneration;
/**
* @author <NAME> <<EMAIL>>
* @version 21.08.2017
* @see dungeongeneration.worldgeneration
* @since 21.08.2017 , 13:16:35
*
*/
public class Room {
private int left, right, top, bottom;
/**
* Konstruktor fuer neue Exemplare der Klasse Room.
*
* @param left
* @param right
* @param width
* @param height
*/
public Room(int left, int right, int width, int height) {
}
/**
* Returns true if room is intersecting another room, false if not
* @param room
* @return
*/
public boolean touches(Room room) {
return false;
}
/**
* Returns true if room is intersecting another room, false if not
*
* @param room
* @param padding
* @return
*/
public boolean touches(Room room, int padding) {
return false;
}
/**
* Getter-Methode zu left. Ermöglicht es einem Klienten, den Wert der
* Exemplarvariablen left abzufragen.
*
* @return the left
*/
public int getLeft() {
return left;
}
/**
* Getter-Methode zu right. Ermöglicht es einem Klienten, den Wert der
* Exemplarvariablen right abzufragen.
*
* @return the right
*/
public int getRight() {
return right;
}
/**
* Getter-Methode zu top. Ermöglicht es einem Klienten, den Wert der
* Exemplarvariablen top abzufragen.
*
* @return the top
*/
public int getTop() {
return top;
}
/**
* Getter-Methode zu bottom. Ermöglicht es einem Klienten, den Wert der
* Exemplarvariablen bottom abzufragen.
*
* @return the bottom
*/
public int getBottom() {
return bottom;
}
}
| b7180754e06f2d02e42d33516f18e5f41ac762f0 | [
"Java"
]
| 1 | Java | cbrgm/worldgeneration | 1710685451dff72678be4ed9b71ebee9c8f2c409 | ca0f98490386e5555edec5e96c048406bd439406 |
refs/heads/main | <repo_name>ygoto3/sample-functional-ddd<file_sep>/database/scripts/init.sql
CREATE DATABASE IF NOT EXISTS sample_functional_ddd<file_sep>/database/migrations/20201031105537-create_table_comments.sql
-- +migrate Up
CREATE TABLE IF NOT EXISTS comments (
id VARCHAR(36) NOT NULL,
body VARCHAR(255) NOT NULL,
PRIMARY KEY(id)
);
-- +migrate Down
DROP TABLE IF EXISTS comments;
<file_sep>/README.md
# sample-functional-ddd
A sample project for functional DDD
| 1970508fe1c1ae0ed51494089f989df2380ab62a | [
"Markdown",
"SQL"
]
| 3 | SQL | ygoto3/sample-functional-ddd | 0abf99ccdfa8c4a81cf69c8c47693f76d16b04b6 | 3a57cc3aa10c25d13380bbe35e326502b9501e7f |
refs/heads/master | <file_sep>from sklearn.preprocessing import Imputer,StandardScaler
import pandas as pd
import numpy as np
import math
movie_data = pd.read_csv('R_gc.csv')
columns = ['budget', 'id', 'keywords', 'popularity', 'revenue', 'runtime',
'title', 'vote_average', 'vote_count', 'director','year']
num_columns = ['budget', 'id', 'popularity', 'revenue', 'runtime',
'title', 'vote_average', 'vote_count', 'year']
L1 = ['budget', 'popularity', 'vote_count', 'revenue']
def to_log(object_name):
movie_data[object_name] = movie_data[object_name].apply(lambda x: math.log(x))
dif = max(movie_data[object_name]) - min(movie_data[object_name])
avg = sum(movie_data[object_name]) / len(movie_data[object_name])
movie_data[object_name] = movie_data[object_name].apply(lambda x: (x - avg) / dif)
L2 = ['runtime', 'vote_average'] #,'year'
def to_one(object_name):
dif = max(movie_data[object_name]) - min(movie_data[object_name])
avg = sum(movie_data[object_name])/len(movie_data[object_name])
movie_data[object_name] = movie_data[object_name].apply(lambda x: (x-avg)/dif)
for a in L1:
to_log(a)
#
# for a in L2:
# to_one(a)
def cos(vector1, vector2):
dot_product = 0.0
normA = 0.0
normB = 0.0
for a, b in zip(vector1, vector2):
dot_product += a * b
normA += a ** 2
normB += b ** 2
if normA == 0.0 or normB == 0.0:
return None
else:
return dot_product / ((normA * normB) ** 0.5)
def return_id_index(id):
for index, content in enumerate(movie_data['id']):
if content == id:
return index
def comp_cos(I):
input_ = train.iloc[I]
print(I, movie_data['title'][I])
L = []
for ind in range(len(train)):
L.append(cos(input_, train.iloc[ind]))
train['cos'] =L
# print(movie_data)
# for i in range(len(movie_data)):
# if movie_data['director'][i] == '<NAME>':
# print(movie_data['vote_average'][i]) #, movie_data['vote_average'][i]
del movie_data['director']
del movie_data['keywords']
del movie_data['year']
# # del movie_data['production_countries']
# # del movie_data['genres']
train = movie_data
train = train.drop('id', axis=1)
train = train.drop('title', axis=1)
def out_():
AA=train.sort_values('cos', ascending=False)
ind = AA.index
l = []
for i in [1,2,3,4,5]:
l.append(ind[i])
print('-------------------')
print('output:')
for i in l:
print(i, movie_data['title'][i])
print('input:')
comp_cos(0)
out_()<file_sep>from sklearn.svm import SVR
from sklearn.linear_model import LinearRegression,Lasso
from sklearn.ensemble import GradientBoostingRegressor,ExtraTreesRegressor
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error, r2_score
import pickle
from sklearn import neighbors
from sklearn import preprocessing
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def read_data(split):
# imdb_score
# df = pd.read_csv("one_hot.csv",
# usecols=[ 'num_critic_for_reviews', 'duration',
# 'actor_3_facebook_likes', 'actor_2_facebook_likes', 'actor_1_facebook_likes',
# 'gross', 'num_voted_users', 'num_user_for_reviews', 'cast_total_facebook_likes',
# 'budget', 'imdb_score'])
# df = pd.read_csv("to.csv")
# Y = df['vote_average']
# X = df.drop(['vote_average'], axis=1)
# df = pd.read_csv("input/one_hot_gc.csv")
# df = df.drop(['content_rating'], axis=1)
# Y = df['imdb_score']
# X = df.drop(['imdb_score'], axis=1)
df = pd.read_csv("2.csv")
Y = df['score']
X = df.drop(['score'], axis=1)
print(X)
x_columns = X.columns
indexs = np.arange(0, len(X))
np.random.shuffle(indexs)
X = X.values[indexs]
Y = Y.values[indexs]
X_scaled = preprocessing.scale(X)
train_ = [X_scaled[:split], Y[:split]]
test_ = [X_scaled[split:], Y[split:]]
print(X_scaled.shape, Y.shape)
data = np.concatenate([X_scaled, Y.reshape([-1, 1])], axis=1)
data = pd.DataFrame(data, columns=list(x_columns) + ['imdb_score'])
# data.describe().T.to_csv('desc_scaled.csv')
# exit()
return train_, test_
def plot_(pred, real):
yy_pred = pred
yy_real = real
def sample(y):
import random
index=random.sample(range(len(y)),30)
return index
index = sample(yy_pred)
y_pred_sample = yy_pred[index]
y_real_sample = yy_real[index]
samples = zip(y_real_sample,y_pred_sample)
samples = sorted(samples)
# samples = sorted(samples,key=lambda samples : samples[1])
y_real_sample_sorted = []
y_pred_sample_sorted = []
for sample in samples:
y_real_sample_sorted.append(sample[0])
y_pred_sample_sorted.append(sample[1])
# print(y_real_sample_sorted)
# print(y_pred_sample_sorted)
plt.figure()
plt.plot(range(len(y_real_sample_sorted)),y_pred_sample_sorted,'b',label="predict")
plt.plot(range(len(y_real_sample_sorted)),y_real_sample_sorted,'r',label="real")
plt.legend(loc="upper right") # 显示图中的标签
plt.xlabel("movies")
plt.ylabel('vote average')
plt.show()
def main():
print("------------------------------")
cmp_model_list = ['Linear Regression','SVR','GBDT','KNN','ETR']#, 'Lasso','Linear Regression', 'SVR', 'GBDT', 'KNN',
print('start!')
tran_test_split_ = 2200
train_, test_ = read_data(tran_test_split_)
print('read finish!')
model_lr = LinearRegression()
model_lr.fit(train_[0], train_[1])
print('LinearRegression Training Finish')
model_svr = SVR()
model_svr.fit(train_[0], train_[1])
print('SVR Training Finish')
model_gbdt = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1)
model_gbdt.fit(train_[0], train_[1])
print('GBDT Training Finish')
#
model_knn = neighbors.KNeighborsRegressor()
model_knn.fit(train_[0], train_[1])
print('KNN Training Finish')
# model_lasso = Lasso()
# model_lasso.fit(train_[0], train_[1])
# print('Lasso Training Finish')
model_etr = ExtraTreesRegressor()
model_etr.fit(train_[0], train_[1])
print('ETR Training Finish')
lr_train_pred = model_lr.predict(train_[0])
lr_test_pred = model_lr.predict(test_[0])
svr_train_pred = model_svr.predict(train_[0])
svr_test_pred = model_svr.predict(test_[0])
gbdt_train_pred = model_gbdt.predict(train_[0])
gbdt_test_pred = model_gbdt.predict(test_[0])
knn_train_pred = model_knn.predict(train_[0])
knn_test_pred = model_knn.predict(test_[0])
# lasso_train_pred = model_lasso.predict(train_[0])
# lasso_test_pred = model_lasso.predict(test_[0])
etr_train_pred = model_etr.predict(train_[0])
etr_test_pred = model_etr.predict(test_[0])
for i, pred in enumerate([
[lr_train_pred, lr_test_pred],
[svr_train_pred, svr_test_pred],
[gbdt_train_pred, gbdt_test_pred],
[knn_train_pred, knn_test_pred],
# [lasso_train_pred, lasso_test_pred],
[etr_train_pred, etr_test_pred]
]):
print("------------------------------")
print("-Train-")
print("Selected Model: %s" % cmp_model_list[i])
# The mean squared error
print("Mean squared error: %.2f"
% mean_squared_error(train_[1], pred[0]))
# Explained variance score: 1 is perfect prediction
print('Variance score: %.2f'
% r2_score(train_[1], pred[0]))
print("-Test-")
# The mean squared error
print("Mean squared error: %.2f"
% mean_squared_error(test_[1], pred[1]))
# Explained variance score: 1 is perfect prediction
print('Variance score: %.2f'
% r2_score(test_[1], pred[1]))
print("------------------------------")
# plot_(knn_test_pred, test_[1])
if __name__ == '__main__':
main()
<file_sep>from sklearn.preprocessing import Imputer,StandardScaler
import pandas as pd
import numpy as np
import json
# using data which is transformed================================================================
D_movies = pd.read_csv('input/movie_with_director.csv')
D_columns = ['budget', 'genres', 'homepage', 'id', 'keywords','original_language', 'original_title', 'overview',
'popularity', 'production_companies', 'production_countries', 'release_date', 'revenue', 'runtime',
'spoken_languages', 'status', 'tagline','title', 'vote_average', 'vote_count', 'director']
info_columns = ['genres', 'homepage', 'keywords', 'original_language', 'original_title', 'overview',
'production_companies', 'production_countries', 'release_date', 'spoken_languages',
'status', 'tagline', 'title', 'director'] # 14
num_columns = ['budget', 'id', 'popularity', 'revenue', 'runtime','vote_average', 'vote_count'] #8,'year'
use_columns = [ 'id', 'title',
'budget','revenue',
'runtime', 'vote_average', 'vote_count','popularity', 'year',
'keywords', 'genres',
'production_countries',
'director']
# delete budget\revenue for too many 0
useless_columns = ['homepage','overview','tagline','status',
'spoken_languages','original_language','production_companies','original_title','release_date' ]
change_columns = [ 'genres','production_countries', 'director']
numerical_data = D_movies.select_dtypes(exclude=["object"])
information_data = D_movies.select_dtypes(include=["object"])
def print_count_nan():
def count_nan(object_name):
objects = D_movies[object_name].fillna('XXXX')
x = 0
for object in objects:
if object != 'XXXX':
x = x + 1
print (object_name + ': %d' % x)
for a in D_columns:
count_nan(a)
def print_count_zero():
def count_zero(object_name):
objects = D_movies[object_name]
x = 0
for object in objects:
if object == 0:
x = x + 1
print (object_name + ' zero_num: %d' % x)
for a in num_columns:
count_zero(a)
def fill_all_zero():
def fill_zero(object_name):
D_movies[object_name] = D_movies[object_name].apply(lambda x: D_movies[object_name].mean() if x == 0 else x)
for a in num_columns:
fill_zero(a)
def count_items(object_name):
L = []
for i in D_movies[object_name]:
for j in eval(i):
L.append(j)
return set(L)
def count_director():
L = []
for i in D_movies['director']:
L.append(i)
return set(L)
def word_to_vec(column_name='genres'):
object_list = []
object_dict = {}
objects = D_movies[column_name]
for object in objects:
for a in eval(object):
object_list.append(a)
object_list = set(object_list)
print(object_list)
object_num = len(object_list)
for object_rank, object in enumerate(object_list):
zero_vector = np.zeros(shape=object_num)
zero_vector[object_rank] = 1
object_dict[object] = zero_vector
object_to_vectors = []
for object in objects:
object_vec = sum(object_dict[o] for o in eval(object))
object_to_vectors.append(object_vec)
D_movies[column_name] = object_to_vectors
def split_vector(column_name='genres'):
objects = D_movies[column_name]
df = pd.DataFrame()
for object_rank, object in enumerate(objects):
df[object_rank] = object
lenth = len(df)
df = df.T
df.columns = [column_name+'{}'.format(i+1) for i in range(lenth)]
df = pd.concat([D_movies, df], axis=1)
return df
# change to year====
D_movies['year'] = pd.to_datetime(D_movies['release_date'], errors='coerce').apply(
lambda x: str(x).split('-')[0] if x != np.nan else np.nan)
# print(D_movies.head())
# fill nan =========
imp = Imputer(missing_values="NaN", strategy="mean", axis=0)
D_movies[num_columns] = imp.fit_transform(D_movies[num_columns])
# fill 0 =========
fill_all_zero()
# ------------------------------------------
# # change colums====
# word_to_vec('production_countries')
# D_movies = split_vector('production_countries')
# del D_movies['production_countries']
word_to_vec('keywords')
D_movies = split_vector('keywords')
# del D_movies['genres']
for i in useless_columns:
del D_movies[i]
print(D_movies.head())
#
# pd.DataFrame.to_csv(D_movies, 'R_gc.csv', index=None)
<file_sep>
import pandas as pd
import numpy as np
import json
# import enumerate
movies_df = pd.read_csv('input/tmdb_5000_movies.csv')
credit_df = pd.read_csv('input/tmdb_5000_credits.csv')
def get_all_content(object_name):
def get_content(object):
L = []
for i in object:
L.append(i['name'])
return L
movies_df[object_name] = movies_df[object_name].apply(lambda x: get_content(eval(x)))
return movies_df[object_name]
def get_all_director(object_name):
def get_director(object):
L = []
for i in object:
if i['job'] == 'Director':
L.append(i['name'])
return L
credit_df[object_name] = credit_df[object_name].apply(lambda x: get_director(eval(x)))
return credit_df[object_name]
def add_director():
for i in movies_df['id']:
for j in credit_df['movie_id']:
if i == j:
movies_df['director'] = credit_df['crew']
def to_csv():
L = ['genres', 'keywords', 'production_companies', 'production_countries', 'spoken_languages']
for a in L:
get_all_content(a)
get_all_director('crew')
add_director()
pd.DataFrame.to_csv(movies_df, 'movie_with_director1.csv', index=None)
to_csv()
<file_sep>from sklearn.svm import SVR
from sklearn.linear_model import LinearRegression, Lasso
from sklearn.ensemble import GradientBoostingRegressor, ExtraTreesRegressor
from sklearn.metrics import mean_squared_error, r2_score
from sklearn import preprocessing
from sklearn import neighbors
import numpy as np
import pandas as pd
def read_data(split):
# imdb_score
# df = pd.read_csv('4.csv')#original
#changed===============
df = pd.read_csv('input/one_hot_gc.csv')
df = df.drop(['content_rating'], axis=1)
# df = df.drop(['num_critic_for_reviews'], axis=1)
# df.describe().T.to_csv('desc.csv')
# exit()
Y = df['imdb_score']
X = df.drop(['imdb_score'], axis=1)
x_columns = X.columns
indexs = np.arange(0, len(X))
np.random.shuffle(indexs)
X = X.values[indexs]
Y = Y.values[indexs]
X_scaled = preprocessing.scale(X)
train_ = [X_scaled[:split], Y[:split]]
test_ = [X_scaled[split:], Y[split:]]
print(X_scaled.shape, Y.shape)
data = np.concatenate([X_scaled, Y.reshape([-1, 1])], axis=1)
data = pd.DataFrame(data, columns=list(x_columns) + ['imdb_score'])
# data.describe().T.to_csv('desc_scaled.csv')
# exit()
return train_, test_
def main():
print("------------------------------")
cmp_model_list = ['Linear Regression','SVR','GBDT','KNN','ETR']#, 'Lasso',
print('start!')
tran_test_split_ = 4000
train_, test_ = read_data(tran_test_split_)
print('read finish!')
model_lr = LinearRegression()
model_lr.fit(train_[0], train_[1])
print('LinearRegression Training Finish')
model_svr = SVR()
model_svr.fit(train_[0], train_[1])
print('SVR Training Finish')
model_gbdt = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1)
model_gbdt.fit(train_[0], train_[1])
print('GBDT Training Finish')
model_knn = neighbors.KNeighborsRegressor()
model_knn.fit(train_[0], train_[1])
print('KNN Training Finish')
# model_lasso = Lasso()
# model_lasso.fit(train_[0], train_[1])
# print('Lasso Training Finish')
model_etr = ExtraTreesRegressor()
model_etr.fit(train_[0], train_[1])
print('ETR Training Finish')
lr_train_pred = model_lr.predict(train_[0])
lr_test_pred = model_lr.predict(test_[0])
svr_train_pred = model_svr.predict(train_[0])
svr_test_pred = model_svr.predict(test_[0])
gbdt_train_pred = model_gbdt.predict(train_[0])
gbdt_test_pred = model_gbdt.predict(test_[0])
knn_train_pred = model_knn.predict(train_[0])
knn_test_pred = model_knn.predict(test_[0])
# lasso_train_pred = model_lasso.predict(train_[0])
# lasso_test_pred = model_lasso.predict(test_[0])
etr_train_pred = model_etr.predict(train_[0])
etr_test_pred = model_etr.predict(test_[0])
for i, pred in enumerate([
[lr_train_pred, lr_test_pred],
[svr_train_pred, svr_test_pred],
[gbdt_train_pred, gbdt_test_pred],
[knn_train_pred, knn_test_pred],
# [lasso_train_pred, lasso_test_pred],
[etr_train_pred, etr_test_pred]
]):
print("------------------------------")
print("-Train-")
print("Selected Model: %s" % cmp_model_list[i])
# The mean squared error
print("Mean squared error: %.2f"
% mean_squared_error(train_[1], pred[0]))
# Explained variance score: 1 is perfect prediction
print('Variance score: %.2f'
% r2_score(train_[1], pred[0]))
print("-Test-")
# The mean squared error
print("Mean squared error: %.2f"
% mean_squared_error(test_[1], pred[1]))
# Explained variance score: 1 is perfect prediction
print('Variance score: %.2f'
% r2_score(test_[1], pred[1]))
print("------------------------------")
if __name__ == '__main__':
main()
<file_sep>
import pandas as pd
import numpy as np
import json
# import enumerate
D_movies = pd.read_csv('input/movie_with_director.csv')
D_columns = ['budget', 'genres', 'homepage', 'id', 'keywords',
'original_language', 'original_title', 'overview', 'popularity',
'production_companies', 'production_countries', 'release_date',
'revenue', 'runtime', 'spoken_languages', 'status', 'tagline',
'title', 'vote_average', 'vote_count', 'director']
D_info_columns = ['genres', 'homepage', 'keywords', 'original_language', 'original_title',
'overview', 'production_companies', 'production_countries',
'release_date', 'spoken_languages', 'status', 'tagline', 'title','director']
D_num_columns = ['budget', 'id', 'popularity', 'revenue', 'runtime', 'vote_average','vote_count']
def count_items(object_name):
L = []
for i in D_movies[object_name]:
for j in eval(i):
L.append(j)
return L
def count_director():
L = []
for i in D_movies['director']:
L.append(i)
return L
# m = ['11']
# for i in m:
# print(i)
print(count_director())
# print(eval(D_movies['genres'][1])[1])
# print(eval(D_movies['director'][1])[0])<file_sep># %matplotlib inline
import pandas as pd
import json
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
from ast import literal_eval
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.metrics.pairwise import linear_kernel, cosine_similarity
from nltk.stem.snowball import SnowballStemmer
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.corpus import wordnet
# from surprise import Reader, Dataset, SVD, evaluate
import warnings; warnings.simplefilter('ignore')
# select some data and transform it to CSV=================
# md = pd. read_csv('movies_metadata.csv')
# data = md.iloc[:55,:]
# pd.DataFrame.to_csv(data,'test_1.csv', ',', '', None, None, True, False)
# test_data = pd.read_csv('test_1.csv')
# print(type(test_data['original_title'][30]))#select some item
# print(len(test_data.iloc[34,:]))#select some row
# print(test_data.iloc[:,3]) #select some column
#
# test_data = test_data.drop(1)#delete one row
# del test_data['adult']#delete one column
# delete some columns and are transferred to CSV
# del test_data['adult']
# del test_data['belongs_to_collection']
# del test_data['homepage']
# del test_data['poster_path']
# del test_data['video']
# pd.DataFrame.to_csv(test_data, 'form.csv', ',', '', None, None, True, False)
# data has been transferred to be cleaner
md = pd.read_csv('form.csv')
#
# md['genres'] = md['genres'].fillna('[]').apply(literal_eval).\
# apply(lambda x: [i['name'] for i in x] if isinstance(x, list) else [])
# md['production_companies'] = md['production_companies'].fillna('[]').apply(literal_eval).\
# apply(lambda x: [i['name'] for i in x] if isinstance(x, list) else [])
# md['production_countries'] = md['production_countries'].fillna('[]').apply(literal_eval).\
# apply(lambda x: [i['name'] for i in x] if isinstance(x, list) else [])
# md['spoken_languages'] = md['spoken_languages'].fillna('[]').apply(literal_eval).\
# apply(lambda x: [i['name'] for i in x] if isinstance(x, list) else [])
# del md['status']
#
# pd.DataFrame.to_csv(md, 'after.csv', ',', '', None, None, True, False)
# md = pd.read_csv('after.csv')
vote_averages = md[md['vote_average'].notnull()]['vote_average'].astype('int')
C = vote_averages.mean()
# print(C)
vote_counts = md[md['vote_count'].notnull()]['vote_count'].astype('int')
m = vote_counts.quantile(0.95)
md['spoken_languages'] = md['spoken_languages'].fillna('[]').apply(literal_eval).\
apply(lambda x: [i['name'] for i in x] if isinstance(x, list) else [])
# md['year'] = pd.to_datetime(md['release_date'], errors='coerce').apply(lambda x: str(x).split('-')[0] if x != np.nan else np.nan)
# print(md['year'])
# qualified = md[(md['vote_count'] >= 0) & (md['vote_count'].notnull()) & (md['vote_average'].notnull())]\
# [['title', 'year', 'vote_count', 'vote_average', 'popularity', 'genres']]
# pd.DataFrame.to_csv(qualified, 'qualified.csv', ',', '', None, None, True, False)
print(md['spoken_languages'])<file_sep># coding:utf-8
import numpy as np
import pandas as pd
from sklearn.preprocessing import Imputer,StandardScaler
#count zero number=============================
def count_zero(object_name):
objects = meta_df[object_name]
x = 0
for object in objects:
if object == 0:
x = x+1
print(object_name+ ' zero_num: %d' % x)
def print_count_zero():
for a in numerical_columns:
count_zero(a)
# print_count_zero()
#print count nan=============================================
def count_nan(object_name):
objects = meta_df[object_name].fillna('XXXX')
x = 0
for object in objects:
if object != 'XXXX':
x = x+1
print(object_name + ': %d' %x)
def print_count_nan():
for a in df_columns:
count_nan(a)
# print_count_nan()
#fill all zeros in all numerical columns================================
def fill_zero(object_name):
numerical_data[object_name] = numerical_data[object_name].apply(lambda x: numerical_data[object_name].mean() if x==0 else x)
def fill_all_zero():
for a in numerical_columns:
fill_zero(a)
meta_df = pd.read_csv("movie_metadata.csv"
# ,usecols=['director_name', 'director_facebook_likes', 'num_critic_for_reviews', 'duration',
# 'actor_3_facebook_likes', 'actor_2_facebook_likes', 'actor_1_facebook_likes',
# 'actor_1_facebook_likes', 'actor_3_name', 'actor_2_name', 'actor_1_name', 'genres',
# 'gross', 'num_voted_users', 'num_user_for_reviews', 'cast_total_facebook_likes',
# 'country', 'content_rating', 'budget', 'plot_keywords', 'imdb_score']
)
df_columns = ['color', 'director_name', 'num_critic_for_reviews', 'duration',
'director_facebook_likes', 'actor_3_facebook_likes', 'actor_2_name',
'actor_1_facebook_likes', 'gross', 'genres', 'actor_1_name',
'movie_title', 'num_voted_users', 'cast_total_facebook_likes',
'actor_3_name', 'facenumber_in_poster', 'plot_keywords',
'movie_imdb_link', 'num_user_for_reviews', 'language', 'country',
'content_rating', 'budget', 'title_year', 'actor_2_facebook_likes',
'imdb_score', 'aspect_ratio', 'movie_facebook_likes']
numerical_data = meta_df.select_dtypes(exclude=["object"])
numerical_columns = ['num_critic_for_reviews', 'duration', 'director_facebook_likes',
'actor_3_facebook_likes', 'actor_1_facebook_likes', 'gross',
'num_voted_users', 'cast_total_facebook_likes',
'facenumber_in_poster', 'num_user_for_reviews', 'budget',
'title_year', 'actor_2_facebook_likes', 'imdb_score',
'aspect_ratio', 'movie_facebook_likes']
information_data = meta_df.select_dtypes(include=["object"])
information_columns = ['color', 'director_name', 'actor_2_name', 'genres', 'actor_1_name',
'movie_title', 'actor_3_name', 'plot_keywords', 'movie_imdb_link',
'language', 'country', 'content_rating']
# 将数值型空值的填充为平均值,并执行填充0值函数,转移到meta_df中============================================
imp = Imputer(missing_values="NaN", strategy="mean", axis=0) # default values
numerical_data[numerical_columns] = imp.fit_transform(numerical_data[numerical_columns])
fill_all_zero()#还在numerical_data
for C in numerical_columns:#将numerical_data中数据转到meta_df中
meta_df[C] = numerical_data[C]
# 将文本型的空值填充为上一条数据,转移到meta_df中============================================
information_data = pd.DataFrame(information_data)
information_data = information_data.fillna(method='pad')
for C in information_columns:#将information_data转到meta_df中
meta_df[C] = information_data[C]
pd.DataFrame.to_csv(meta_df, 'data_cleaning.csv')<file_sep>import matplotlib.pyplot as plt
yy_pred = gbdty_pred
yy_real = gbdty_test
def sample(y):
import random
index=random.sample(range(len(y)),800)
return index
index = sample(yy_pred)
y_pred_sample = yy_pred[index]
y_real_sample = yy_real.iloc[index]
samples = zip(y_real_sample,y_pred_sample)
samples = sorted(samples)
# samples = sorted(samples,key=lambda samples : samples[1])
y_real_sample_sorted = []
y_pred_sample_sorted = []
for sample in samples:
y_real_sample_sorted.append(sample[0])
y_pred_sample_sorted.append(sample[1])
# print(y_real_sample_sorted)
# print(y_pred_sample_sorted)
plt.figure()
plt.plot(range(len(y_real_sample_sorted)),y_pred_sample_sorted,'b',label="predict")
plt.plot(range(len(y_real_sample_sorted)),y_real_sample_sorted,'r',label="real")
plt.legend(loc="upper right") # 显示图中的标签
plt.xlabel("movies")
plt.ylabel('vote average')
plt.show()<file_sep>import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import Imputer,StandardScaler
import warnings
warnings.filterwarnings('ignore')
movies = pd.read_csv("../input/movie_metadata.csv")
# print (movies.shape)
# print (movies.columns)
#get numeric data for computation and correlation purposes
numerical_data = movies.select_dtypes(exclude=["object"])
# print(numerical_data.columns)
score_imdb= numerical_data["imdb_score"]
numerical_data = numerical_data.drop(["imdb_score"],axis=1)
year_category = numerical_data["title_year"]
numerical_data = numerical_data.drop(["title_year"],axis=1)
numerical_columns = numerical_data.columns
sns.distplot(score_imdb, rug=True,label="IMDB Scores").legend()
# plt.show()
#fill missing values and normalize the data
imp = Imputer(missing_values="NaN",strategy="mean",axis=0) #default values
numerical_data[numerical_columns] = imp.fit_transform(numerical_data[numerical_columns])
# print (numerical_data.describe())
#Without StandardScaler, SVR with poly kernel will throw error of large size.
#With standard scaling, models has seen improvement in predicting.
#knn model is the most beneficiary of standard scaling
scaler = StandardScaler()
numerical_data[numerical_columns] = scaler.fit_transform(numerical_data[numerical_columns])
# print (numerical_data.describe())
# print (numerical_data.shape)
# numerical_data = pd.DataFrame(numerical_data)
# print (numerical_data.describe())
# print(numerical_data[numerical_columns])
#get non_numeric informational content
information_data = movies.select_dtypes(include=["object"])
# print (information_data.columns)
<file_sep># -*- coding:utf-8 -*-
from __future__ import division
import pandas as pd
import numpy as np
# meta_df = pd.read_csv("movie_metadata.csv",#原始的
# usecols=['director_name', 'director_facebook_likes', 'num_critic_for_reviews', 'duration',
# 'actor_3_facebook_likes', 'actor_2_facebook_likes', 'actor_1_facebook_likes',
# 'actor_1_facebook_likes', 'actor_3_name', 'actor_2_name', 'actor_1_name', 'genres',
# 'gross', 'num_voted_users', 'num_user_for_reviews', 'cast_total_facebook_likes',
# 'country', 'content_rating', 'budget', 'plot_keywords', 'imdb_score'])
meta_df = pd.read_csv("input/data_cleaning.csv",
usecols=['director_name', 'num_critic_for_reviews', 'duration',
'actor_3_facebook_likes', 'actor_2_facebook_likes', 'actor_1_facebook_likes',
'actor_3_name', 'actor_2_name', 'actor_1_name', 'genres',
'gross', 'num_voted_users', 'num_user_for_reviews', 'cast_total_facebook_likes',
'country', 'content_rating', 'budget', 'plot_keywords', 'imdb_score'])
# def get_onehot():
# directors = set(meta_df["director_name"])
#
# director_num = len(directors)
# director_dict = {}
# for director_rank, director in enumerate(directors):
# zero_vector = np.zeros(shape=director_num)
# zero_vector[director_rank] = 1
# director_dict[director] = zero_vector
#
# meta_df["director_name"] = meta_df["director_name"].apply(lambda x: director_dict[x])
def string_2_vec(column_name="director_name"):
objects = set(meta_df[column_name])
object_num = len(objects)
object_dict = {}
for object_rank, object in enumerate(objects):
object_vector = np.zeros(shape=object_num)
object_vector[object_rank] = 1
object_dict[object] = object_vector
meta_df[column_name] = meta_df[column_name].apply(lambda x: object_dict[x])
# genres = []
# genre_dict = {}
# for movie_genres in meta_df["genres"]:
# genres.extend(movie_genres.split("|"))
# genres = set(genres)
# genre_num = len(genres)
# for genre_rank, genre in enumerate(genres):
# zero_vector = np.zeros(shape=genre_num)
# zero_vector[genre_rank] = 1
# genre_dict[genre] = zero_vector
#
# genres_to_vectors = []
# for movie_genres in meta_df["genres"]:
# genres = movie_genres.split("|")
# genre_vec = sum([genre_dict[genre] for genre in genres])
# genres_to_vectors.append(genre_vec)
# meta_df["genres"] = genres_to_vectors
def word_to_vec(column_name='genres'):
object_list = []
object_dict = {}
objects = meta_df[column_name]
for object in objects:
object_list.extend(str(object).split('|'))
object_list = set(object_list)
object_num = len(object_list)
for object_rank, object in enumerate(object_list):
zero_vector = np.zeros(shape=object_num)
zero_vector[object_rank] = 1
object_dict[object] = zero_vector
object_to_vectors = []
for object in objects:
object_list = str(object).split('|')
object_vec = sum(object_dict[object] for object in object_list)
object_to_vectors.append(object_vec)
meta_df[column_name] = object_to_vectors
# df = pd.DataFrame()
# for i_rank, i in enumerate(meta_df["genres"]):
# df[i_rank] = i
# df = df.T
# df.columns = ["genre{}".format(i+1) for i in range(26)]
# df = pd.concat([meta_df, df], axis=1)
# print df.shape
def split_vector(column_name='genres'):
objects = meta_df[column_name]
df = pd.DataFrame()
for object_rank, object in enumerate(objects):
df[object_rank] = object
lenth = len(df)
df = df.T
df.columns = [column_name+'{}'.format(i+1) for i in range(lenth)]
df = pd.concat([meta_df, df], axis=1)
return df
string_2_vec('director_name')
string_2_vec('actor_1_name')
string_2_vec('actor_2_name')
# string_2_vec('actor_3_name')
string_2_vec('country')
word_to_vec('genres')
# word_to_vec('plot_keywords')
meta_df = split_vector('director_name')
meta_df = split_vector('actor_1_name')
meta_df = split_vector('actor_2_name')
# meta_df = split_vector('actor_3_name')
meta_df = split_vector('country')
meta_df = split_vector('genres')
# meta_df = split_vector('plot_keywords')
del meta_df['director_name']
del meta_df['actor_1_name']
del meta_df['actor_2_name']
del meta_df['actor_3_name']
del meta_df['country']
del meta_df['genres']
del meta_df['plot_keywords']
print(meta_df.shape)
pd.DataFrame.to_csv(meta_df, 'one_hot_dcgaa.csv', index=None)
<file_sep>from pymongo import MongoClient
import re
import time
client = MongoClient("localhost", 27017)
db = client.local
def add_year():
collection = db.movies
ss = collection.find({})
t1 = time.time()
for s in ss:
try:
year = re.search(r"\d{4}", s["title"]).group()
collection.update({"_id":s["_id"]},{"$set":{"year":int(year)}})
except AttributeError as e:
pass
t2 = time.time()
print("add_year:{:.3f}ms".format((t2-t1)*1000))
# add_year()
def change_to_hundred():
collection = db.ratings
ss = collection.find({})
t1 = time.time()
for s in ss:
try:
h = int(s["rating"])*20
collection.update({"_id":s["_id"]},{"$set":{"hundred":h}})
except AttributeError as e:
pass
t2 = time.time()
print("change_to_hundred:{:.3f}ms".format((t2-t1)*1000))
change_to_hundred()
| 3a732d032d65a99df0791e3c291d3d6def88921f | [
"Python"
]
| 12 | Python | guaidoukx/movie-data | 719aff480e0957aee47bda42518460da8a98419f | d7b8d6fe46f17fe18d18ed9ef400ca4c26e63f47 |
refs/heads/master | <repo_name>cloudfreexiao/skynet_etcd<file_sep>/encode_args.lua
local hex_to_char = function(x)
return string.char(tonumber(x, 16))
end
local function urlencode(url)
if url == nil then
return
end
url = url:gsub("\n", "\r\n")
url = url:gsub("([^%w ])", char_to_hex)
url = url:gsub(" ", "+")
return url
end
local urldecode = function(url)
if url == nil then
return
end
url = url:gsub("+", " ")
url = url:gsub("%%(%x%x)", hex_to_char)
return url
end
return function (params)
local str = ''
local is_first = true
for k,v in pairs(params) do
if is_table(v) then
--TODO:
assert(false)
else
str = str .. k .. '=' .. v
end
if is_first then
str = str .. '&'
is_first = false
end
end
return urlencode(str)
end<file_sep>/etcd.lua
local skynet = require "skynet"
local httpc = require "http.httpc"
local typeof = require "etcd.typeof"
local encode_args = require "etcd.encode_args"
local setmetatable = setmetatable
local cjson = require "cjson.safe"
local decode_json = cjson.decode
local encode_json = cjson.encode
local concat_tab = table.concat
local tostring = tostring
local select = select
local ipairs = ipairs
local type = type
local error = error
local _M = {}
local mt = { __index = _M }
local clear_tab = function (obj)
obj = {}
end
local tab_nkeys = function(obj)
local num = 0
for _, v in pairs(obj) do
if v then
num = num + 1
end
end
return num
end
local split = function(s, delim)
local sp = {}
local pattern = "[^" .. delim .. "]+"
string.gsub(s, pattern, function(v) table.insert(sp, v) end)
return sp
end
local normalize
do
local items = {}
local function concat(sep, ...)
local argc = select('#', ...)
clear_tab(items)
local len = 0
for i = 1, argc do
local v = select(i, ...)
if v ~= nil then
len = len + 1
items[len] = tostring(v)
end
end
return concat_tab(items, sep);
end
local segs = {}
function normalize(...)
local path = concat('/', ...)
local names = {}
local err
segs, err = split(path, [[/]], "jo", nil, nil, segs)
if not segs then
return nil, err
end
local len = 0
for _, seg in ipairs(segs) do
if seg == '..' then
if len > 0 then
len = len - 1
end
elseif seg == '' or seg == '/' and names[len] == '/' then
-- do nothing
elseif seg ~= '.' then
len = len + 1
names[len] = seg
end
end
return '/' .. concat_tab(names, '/', 1, len);
end
end
_M.normalize = normalize
function _M.new(opts)
if opts == nil then
opts = {}
elseif not typeof.table(opts) then
return nil, 'opts must be table'
end
opts.host = opts.host or "http://127.0.0.1:2379"
local timeout = opts.timeout or 5000 -- 5 sec
local ttl = opts.ttl or -1
local prefix = opts.prefix or "/v2/keys"
if not typeof.uint(timeout) then
return nil, 'opts.timeout must be unsigned integer'
end
if not typeof.string(opts.host) then
return nil, 'opts.host must be string'
end
if not typeof.int(ttl) then
return nil, 'opts.ttl must be integer'
end
if not typeof.string(prefix) then
return nil, 'opts.prefix must be string'
end
return setmetatable({
timeout = timeout,
ttl = ttl,
endpoints = {
full_prefix = normalize(prefix),
http_host = opts.host,
prefix = prefix,
version = opts.host .. '/version',
stats_leader = opts.host .. '/v2/stats/leader',
stats_self = opts.host .. '/v2/stats/self',
stats_store = opts.host .. '/v2/stats/store',
keys = opts.host .. '/v2/keys',
}
},
mt)
end
local header = {
["Content-Type"] = "application/x-www-form-urlencoded",
}
local function _request(host, method, uri, opts, timeout)
local body
if opts and opts.body and tab_nkeys(opts.body) > 0 then
body = encode_args(opts.body)
end
if opts and opts.query and tab_nkeys(opts.query) > 0 then
uri = uri .. '?' .. encode_args(opts.query)
end
local recvheader = {}
local status, body = httpc.request(method, host, uri, recvheader, header, body)
if status >= 500 then
return nil, "invalid response code: " .. status
end
if not typeof.string(body) then
return body
end
return decode_json(body)
end
local function set(self, key, val, attr)
local err
val, err = encode_json(val)
if not val then
return nil, err
end
local prev_exist
if attr.prev_exist ~= nil then
prev_exist = attr.prev_exist and 'true' or 'false'
end
local dir
if attr.dir then
dir = attr.dir and 'true' or 'false'
end
local opts = {
body = {
ttl = attr.ttl,
value = val,
dir = dir,
},
query = {
prevExist = prev_exist,
prevIndex = attr.prev_index,
}
}
-- todo: check arguments
-- verify key
key = normalize(key)
if key == '/' then
return nil, "key should not be a slash"
end
local res
res, err = _request(self.endpoints.http_host,
attr.in_order and 'POST' or 'PUT',
self.endpoints.full_prefix .. key,
opts,
self.timeout)
if err then
return nil, err
end
-- get
if res.status < 300 and res.body.node and not res.body.node.dir then
res.body.node.value, err = decode_json(res.body.node.value)
if err then
return nil, err
end
end
return res
end
local function decode_dir_value(body_node)
if not body_node.dir then
return false
end
if type(body_node.nodes) ~= "table" then
return false
end
local err
for _, node in ipairs(body_node.nodes) do
local val = node.value
if type(val) == "string" then
node.value, err = decode_json(val)
if err then
error("failed to decode node[" .. node.key .. "] value: " .. err)
end
end
decode_dir_value(node)
end
return true
end
local function get(self, key, attr)
local opts
if attr then
local attr_wait
if attr.wait ~= nil then
attr_wait = attr.wait and 'true' or 'false'
end
local attr_recursive
if attr.recursive then
attr_recursive = attr.recursive and 'true' or 'false'
end
opts = {
query = {
wait = attr_wait,
waitIndex = attr.wait_index,
recursive = attr_recursive,
consistent = attr.consistent, -- todo
}
}
end
local res, err = _request(self.endpoints.http_host,
"GET",
self.endpoints.full_prefix .. normalize(key),
opts,
attr and attr.timeout or self.timeout)
if err then
return nil, err
end
-- readdir
if attr and attr.dir then
if res.status == 200 and res.body.node and not res.body.node.dir then
res.body.node.dir = false
end
end
if res.status == 200 and res.body.node then
if not decode_dir_value(res.body.node) then
local val = res.body.node.value
if type(val) == "string" then
res.body.node.value, err = decode_json(val)
if err then
return nil, err
end
end
end
end
return res
end
local function delete(self, key, attr)
local val, err = attr.prev_value
if val ~= nil and type(val) ~= "number" then
val, err = encode_json(val)
if not val then
return nil, err
end
end
local attr_dir
if attr.dir then
attr_dir = attr.dir and 'true' or 'false'
end
local attr_recursive
if attr.recursive then
attr_recursive = attr.recursive and 'true' or 'false'
end
local opts = {
query = {
dir = attr_dir,
prevIndex = attr.prev_index,
recursive = attr_recursive,
prevValue = val,
},
}
-- todo: check arguments
return _request(self.endpoints.http_host,
"DELETE",
self.endpoints.full_prefix .. normalize(key),
opts,
self.timeout)
end
do
function _M.get(self, key)
if not typeof.string(key) then
return nil, 'key must be string'
end
return get(self, key)
end
local attr = {}
function _M.wait(self, key, modified_index, timeout)
clear_tab(attr)
attr.wait = true
attr.wait_index = modified_index
attr.timeout = timeout
return get(self, key, attr)
end
function _M.readdir(self, key, recursive)
clear_tab(attr)
attr.dir = true
attr.recursive = recursive
return get(self, key, attr)
end
-- wait with recursive
function _M.waitdir(self, key, modified_index, timeout)
clear_tab(attr)
attr.wait = true
attr.dir = true
attr.recursive = true
attr.wait_index = modified_index
attr.timeout = timeout
return get(self, key, attr)
end
-- /version
function _M.version(self)
return _request(self.endpoints.http_host, 'GET', self.endpoints.version, nil, self.timeout)
end
-- /stats
function _M.stats_leader(self)
return _request(self.endpoints.http_host, 'GET', self.endpoints.stats_leader, nil, self.timeout)
end
function _M.stats_self(self)
return _request(self.endpoints.http_host, 'GET', self.endpoints.stats_self, nil, self.timeout)
end
function _M.stats_store(self)
return _request(self.endpoints.http_host, 'GET', self.endpoints.stats_store, nil, self.timeout)
end
end -- do
do
local attr = {}
function _M.set(self, key, val, ttl)
clear_tab(attr)
attr.ttl = ttl
return set(self, key, val, attr)
end
-- set key-val and ttl if key does not exists (atomic create)
function _M.setnx(self, key, val, ttl)
clear_tab(attr)
attr.ttl = ttl
attr.prev_exist = false
return set(self, key, val, attr)
end
-- set key-val and ttl if key is exists (update)
function _M.setx(self, key, val, ttl, modified_index)
clear_tab(attr)
attr.ttl = ttl
attr.prev_exist = true
attr.prev_index = modified_index
return set(self, key, val, attr)
end
-- dir
function _M.mkdir(self, key, ttl)
clear_tab(attr)
attr.ttl = ttl
attr.dir = true
return set(self, key, nil, attr)
end
-- mkdir if not exists
function _M.mkdirnx(self, key, ttl)
clear_tab(attr)
attr.ttl = ttl
attr.dir = true
attr.prev_exist = false
return set(self, key, nil, attr)
end
-- in-order keys
function _M.push(self, key, val, ttl)
clear_tab(attr)
attr.ttl = ttl
attr.in_order = true
return set(self, key, val, attr)
end
end -- do
do
local attr = {}
function _M.delete(self, key, prev_val, modified_index)
clear_tab(attr)
attr.prev_value = prev_val
attr.prev_index = modified_index
return delete(self, key, attr)
end
function _M.rmdir(self, key, recursive)
clear_tab(attr)
attr.dir = true
attr.recursive = recursive
return delete(self, key, attr)
end
end -- do
return _M
<file_sep>/examples/etcd.lua
return function ()
local etcd = require "etcd.etcd"
local cli, err = etcd.new()
if not cli then
ERROR("etcd cli error:", err)
return
end
local res, err = cli:get('/path/to/key')
DEBUG("res:", inspect(res))
end<file_sep>/typeof.lua
local INFINITE_POS = math.huge
local INFINITE_NEG = -INFINITE_POS
local type = type
local floor = math.floor
local rawequal = rawequal
local function typeof(cmp, arg)
return cmp == type(arg)
end
local function typeof_nil(...)
return typeof('nil', ...)
end
local function typeof_bool(...)
return typeof('boolean', ...)
end
local function typeof_str(...)
return typeof('string', ...)
end
local function typeof_num(...)
return typeof('number', ...)
end
local function typeof_fun(...)
return typeof('function', ...)
end
local function typeof_table(...)
return typeof('table', ...)
end
local function typeof_thread(...)
return typeof('thread', ...)
end
local function typeof_userdata(...)
return typeof('userdata', ...)
end
local function typeof_finite(arg)
return type(arg) == 'number' and (arg < INFINITE_POS and arg > INFINITE_NEG)
end
local function typeof_unsigned(arg)
return type(arg) == 'number' and (arg < INFINITE_POS and arg >= 0)
end
local function typeof_int(arg)
return typeof_finite(arg) and rawequal(floor(arg), arg)
end
local function typeof_int8(arg)
return typeof_int(arg) and arg >= -128 and arg <= 127
end
local function typeof_int16(arg)
return typeof_int(arg) and arg >= -32768 and arg <= 32767
end
local function typeof_int32(arg)
return typeof_int(arg) and arg >= -2147483648 and arg <= 2147483647
end
local function typeof_uint(arg)
return typeof_unsigned(arg) and rawequal(floor(arg), arg)
end
local function typeof_uint8(arg)
return typeof_uint(arg) and arg <= 255
end
local function typeof_uint16(arg)
return typeof_uint(arg) and arg <= 65535
end
local function typeof_uint32(arg)
return typeof_uint(arg) and arg <= 4294967295
end
local function typeof_nan(arg)
return arg ~= arg
end
local function typeof_non(arg)
return arg == nil or arg == false or arg == 0 or arg == '' or arg ~= arg
end
local _M = {
version = 0.1,
['nil'] = typeof_nil,
['boolean'] = typeof_bool,
['string'] = typeof_str,
['number'] = typeof_num,
['function'] = typeof_fun,
['table'] = typeof_table,
['thread'] = typeof_thread,
['userdata'] = typeof_userdata,
['finite'] = typeof_finite,
['unsigned'] = typeof_unsigned,
['int'] = typeof_int,
['int8'] = typeof_int8,
['int16'] = typeof_int16,
['int32'] = typeof_int32,
['uint'] = typeof_uint,
['uint8'] = typeof_uint8,
['uint16'] = typeof_uint16,
['uint32'] = typeof_uint32,
['nan'] = typeof_nan,
['non'] = typeof_non,
-- alias
['Nil'] = typeof_nil,
['Function'] = typeof_fun
}
return _M | 7ece3140d4661a45a96acee622bad71093e648bd | [
"Lua"
]
| 4 | Lua | cloudfreexiao/skynet_etcd | 5f37010d5318b8c1e0a203f2190c56cc914a75f6 | 73a4f69e78c12da3e1c97df71395e5381d404465 |
refs/heads/main | <repo_name>0xC0DE6502/python<file_sep>/bulletdirection.py
# (c) 0xC0DE Dec 2020
# example Python3 code for a bullet travelling from an enemy in the *general direction* of a player
# one time calculation of (stepx, stepy) needed to advance the bullet to the (old) location of the player
# written with a translation to 6502 asm code in mind
# PLEASE NOTE: I have since created a more accurate version in BBC BASIC. Consider this to be obsolete!!
import math
# example player and enemy coordinates (inverted y-axis!)
# Acorn screen MODE 5 is 160x256 wide pixels
mode5_enemy=(30, 10)
mode5_player=(6, 80)
# convert to actual coordinates as if square pixels
enemy=(mode5_enemy[0], mode5_enemy[1]//2)
player=(mode5_player[0], mode5_player[1]//2)
ex=enemy[0]
ey=enemy[1]
px=player[0]
py=player[1]
real_dx=px-ex
real_dy=py-ey
# determine in which quadrant the player is relative to the enemy
# quadrant bottom right = A, bottom left = B, top left = C, top right = D
if real_dy>=0:
if real_dx>=0: quad=0 # A
else: quad=1 # B
else:
if real_dx>=0: quad=3 # D
else: quad=2 # C
dx=abs(real_dx)
dy=abs(real_dy)
if dy>=dx: r=4
else: r=0
if r==0: dx, dy = dy, dx # swap and compensate for it later
# simple calculations, keeping 6502 asm code in mind here (bit shifts)
half_dx=dx//2
if dy>=4*dx+dx: d=3
elif dy>=2*dx+half_dx: d=2
elif dy>=dx+half_dx: d=1
else: d=0
#################### ALL STEPS IN 2 SMALL TABLES #####################################
# this generates the two small tables we actually need in our 6502 asm code later
# a bullet can go in 32 distinct directions
# is easily extended to e.g. 64 if more precise direction is needed
mode5_step_x=[0]*32
mode5_step_y=[0]*32
spd=4
for n in range(32):
rad=(n/32)*2*math.pi # going clockwise(!) from x-axis
real_step_x=spd*math.cos(rad)
real_step_y=-spd*math.sin(rad) # inverted y-axis!
mode5_step_x[n]=round(0.5*real_step_x) # remember: wide pixels
mode5_step_y[n]=round(real_step_y)
print("stepx[]=", mode5_step_x)
print("stepy[]=", mode5_step_y)
#################### EXAMPLE STEP_X AND STEP_Y FOR PLAYER AND ENEMY COORDINATES GIVEN #####################################
dir=[3, 2, 1, 0, 4, 5, 6, 7, 12, 13, 14, 15, 11, 10, 9, 8, 19, 18, 17, 16, 20, 21, 22, 23, 28, 29, 30, 31, 27, 26, 25, 24]
idx=dir[8*quad+r+d]
print("stepx =", mode5_step_x[idx])
print("stepy =", mode5_step_y[idx])
| 67c4986d1b683cdd8d37e94dbf54a418f94e0a28 | [
"Python"
]
| 1 | Python | 0xC0DE6502/python | 8ea21b5d60886c5b926c5e1820ab9ffc46e7e596 | a69d9b88b4a2c37657c9e35a53848bb3e7c556b8 |
refs/heads/master | <file_sep>-- phpMyAdmin SQL Dump
-- version 3.4.7
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jun 21, 2013 at 12:49 PM
-- Server version: 5.5.29
-- PHP Version: 5.3.20-1~dotdeb.0
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- Database: `evemail`
--
-- --------------------------------------------------------
--
-- Table structure for table `api_keys`
--
CREATE TABLE IF NOT EXISTS `api_keys` (
`key_id` int(11) NOT NULL,
`v_code` varchar(255) CHARACTER SET latin1 NOT NULL,
`forward_mail` varchar(100) CHARACTER SET latin1 NOT NULL,
`username` varchar(100) COLLATE utf8_bin NOT NULL,
`premium` date NOT NULL,
`filters` text COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`key_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- --------------------------------------------------------
--
-- Table structure for table `corp_ally_names`
--
CREATE TABLE IF NOT EXISTS `corp_ally_names` (
`id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_bin NOT NULL,
`ticker` varchar(10) COLLATE utf8_bin NOT NULL,
`typ` varchar(1) COLLATE utf8_bin NOT NULL DEFAULT 'c',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- --------------------------------------------------------
--
-- Table structure for table `list_names`
--
CREATE TABLE IF NOT EXISTS `list_names` (
`list_id` int(11) NOT NULL,
`list_name` varchar(100) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`list_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- --------------------------------------------------------
--
-- Table structure for table `processed_mails`
--
CREATE TABLE IF NOT EXISTS `processed_mails` (
`key_id` int(11) NOT NULL,
`message_id` int(11) NOT NULL,
UNIQUE KEY `key_id` (`key_id`,`message_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- --------------------------------------------------------
--
-- Table structure for table `user_names`
--
CREATE TABLE IF NOT EXISTS `user_names` (
`character_id` int(11) NOT NULL,
`character_name` varchar(100) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`character_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
<file_sep><?php
/**
* eve api calls
*/
function object2array($object)
{
return @json_decode(@json_encode($object), 1);
}
function getUserNameByID($id)
{
if (!isset($GLOBALS['user'][$id]))
{
$GLOBALS['user'][$id] = GetValue("SELECT `character_name` FROM `user_names` WHERE `character_id`=" . $id);
if ($GLOBALS['user'][$id] == '')
{
$url = "https://api.eveonline.com/eve/CharacterName.xml.aspx?IDs={$id}";
$xml_object = simplexml_load_string(file_get_contents($url));
$xml_array = object2array($xml_object);
$characterName = $xml_array["result"]["rowset"]["row"]["@attributes"]["name"];
InsertData(array('character_id' => $id, 'character_name' => $characterName), 'user_names');
$GLOBALS['user'][$id] = $characterName;
}
}
return $GLOBALS['user'][$id];
}
function getOrgNameByID($id)
{
$org = GetRow("SELECT * FROM `corp_ally_names` WHERE `id`=" . $id);
if (!$org['name'])
{
$url = "https://api.eveonline.com/corp/CorporationSheet.xml.aspx?corporationID={$id}";
$xml_object = simplexml_load_string(file_get_contents($url));
$xml_array = object2array($xml_object);
$corporationName = $xml_array["result"]["corporationName"];
$org = array('typ' => 'c', 'id' => $id, 'name' => $corporationName, 'ticker' => $xml_array["result"]['ticker']);
InsertData($org, 'corp_ally_names');
}
return $org;
}
function getListNameByID($id)
{
global $characterID, $keyID, $vCode;
$list = GetValue("SELECT list_name FROM list_names WHERE list_id=$id");
if (!$list)
{
$url = "https://api.eveonline.com/char/mailinglists.xml.aspx?characterID={$characterID}&keyID={$keyID}&vCode={$vCode}";
$xml_object = simplexml_load_string(file_get_contents($url));
$xml_array = object2array($xml_object);
foreach ($xml_array["result"]["rowset"]["row"] as $lst){
$lstdata = array('list_id' => $lst['@attributes']['listID'],'list_name' => $lst['@attributes']['displayName']);
@InsertData($lstdata, 'list_names');
}
}
$list = GetValue("SELECT list_name FROM list_names WHERE list_id=$id");
return $list;
}
function is_checked($search,$string_data){
$data = unserialize($string_data);
if ($data[$search]==1){
echo ' checked="checked"';
}
}
function is_igb() {
return isset($_SERVER['HTTP_EVE_TRUSTED']);
}<file_sep>Evegate 0.1 Alpha
=======
Forward EVE Online in-game messages to e-mail box
Its just few php scripts, mysql tables, cron job's, and eve-online api calls.
Making this public for anyone to use, modify, etc.
Usage:
=====
1. use sql from populate_db.sql to initialise mysql database
2. setup cronjobs (cron_*.php)
3. try to adapt form_api_add.php for your needs
4. ...
Real life example
=====
if You can't host Your own copy of this software elsewhere, feel free to use this:
http://ash-alliance.eu/evegate.php
<file_sep><?php
/**
* configuration
*/
//setup db connection - mysql
$setup['db_ip'] = '127.0.0.1';
$setup['db_user'] = 'db_user';
$setup['db_pass'] = '<PASSWORD>';
$setup['db_name'] = 'database_name';
$link = dbConnection($setup['db_ip'], $setup['db_user'], $setup['db_pass'], $setup['db_name']);
//configure from mail
$from_mail = '<EMAIL>';<file_sep><?php
/**
*
* use it once a day - maybe there is a new alliance
*
* |
* | #cronjob example:
* | #
* | # m h d M W
* | 0 1 * * * www-data /usr/bin/php5 -f /home/www/evegate/cron/cron_ally_add.php
* |
* |
*
*/
include('include/db.php');
include('include/api_calls.php');
include('include/config.php');
$url = 'https://api.eveonline.com/eve/AllianceList.xml.aspx?version=1';
$xml_object = simplexml_load_string(file_get_contents($url));
$xml_array = object2array($xml_object);
foreach ($xml_array['result']['rowset']['row'] as $ally)
{
$temp['org'][$ally['@attributes']['allianceID']] = GetValue("SELECT `name` FROM `corp_ally_names` WHERE `id`=" . $ally['@attributes']['allianceID']);
if (!$temp['org'][$ally['@attributes']['allianceID']])
{
$temp['org'][$ally['@attributes']['allianceID']] = $ally['@attributes']['name'];
InsertData(array('typ' => 'a',
'id' => $ally['@attributes']['allianceID'],
'name' => $ally['@attributes']['name'],
'ticker' => $ally['@attributes']['shortName']),
'corp_ally_names');
}
}
<file_sep><?php
/**
*
* use it every 10 minutes
*
* |
* | #cronjob example:
* | #
* | # m h d M W
* | 0,10,20,30,40,50 * * * * www-data /usr/bin/php5 -f /home/www/evegate/cron/cron_messages_forward.php
* |
* |
*/
include('include/db.php');
include('include/api_calls.php');
include('include/config.php');
function SendMail($to1, $from, $subject, $message, $charset = "utf-8")
{
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=' . $charset . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
mail($to1, $subject, $message, $headers);
}
$api_keys_array = GetResult("SELECT * FROM api_keys WHERE key_id>0 and forward_mail>'' ");
foreach ($api_keys_array as $single_key)
{
$keyID = $single_key["key_id"];
$vCode = $single_key["v_code"];
$forwardmail = $single_key["forward_mail"];
$filters = unserialize($single_key['filters']);
//get api user
$url = 'https://api.eveonline.com/account/APIKeyInfo.xml.aspx?keyID=' . $keyID . '&vCode=' . $vCode;
$xml_object = simplexml_load_string(file_get_contents($url));
$xml_array = object2array($xml_object);
$characterID = $xml_array["result"]["key"]["rowset"]["row"]["@attributes"]["characterID"];
$characterNAME = getUserNameByID($characterID);
//get mail headers
$maildata = "https://api.eveonline.com/char/MailMessages.xml.aspx?characterID={$characterID}&keyID={$keyID}&vCode={$vCode}";
$xml_object2 = simplexml_load_string(file_get_contents($maildata));
$xml_array2 = object2array($xml_object2);
if (isset($xml_array2["result"]["rowset"]["row"]) && count($xml_array2["result"]["rowset"]["row"]) && is_array($xml_array2["result"]["rowset"]["row"]))
{
foreach ($xml_array2["result"]["rowset"]["row"] as $mailitem)
{
$mail = $mailitem["@attributes"];
$check = GetValue("SELECT `message_id` FROM `processed_mails` WHERE `key_id` = $keyID AND `message_id` = {$mail["messageID"]}");
if (!$check)
{
//init filter state
$no_send = false;
//don't send the same message twice
InsertData(array('key_id' => $keyID, 'message_id' => $mail["messageID"]), 'processed_mails');
//init mail title
$mail_title = $mail["title"];
//init list of mail recipients
$to_list = '';
if ($mail["toListID"] > '')
{
if ($filters[$mail["toListID"]])
{
$no_send = true;
}
$list = getListNameByID($mail["toListID"]);
$mail_title = '' . $list . ' // ' . $mail_title;
$to_list .= '<a style="font-weight:bold; color: #02FA46; text-decoration: none" href="https://gate.eveonline.com/Mail/MailingList/' .
$mail['toListID'] . '/">' . $list . '</a>, ';
}
if ($mail["toCorpOrAllianceID"] > '')
{
$org = getOrgNameByID($mail["toCorpOrAllianceID"]);
$name = $org['name'];
if ($org['typ'] == 'c')
{
if ($filters['fromcorp'])
{
$no_send = true;
}
$mail_title = 'CORP // ' . $mail_title;
$to_list .= '<a style="font-weight:bold; color: #fa9e0e; text-decoration: none" href="https://gate.eveonline.com/Corporation/' .
str_replace(' ', '%20', $org['name']) . '/">' . $org['name'] . ' [' .
$org['ticker'] . ']</a>, ';
}
if ($org['typ'] == 'a')
{
if ($filters['fromally'])
{
$no_send = true;
}
$mail_title = 'ALLY // ' . $mail_title;
$to_list .= '<a style="font-weight:bold; color: #fa9e0e; text-decoration: none" href="https://gate.eveonline.com/Alliance/' .
str_replace(' ', '%20', $org['name']) . '/">' . $org['name'] . ' [' .
$org['ticker'] . ']</a>, ';
}
}
if ($characterID == $mail["senderID"])
{
if ($filters['fromsent'])
{
$no_send = true;
}
$mail_title = 'SENT // ' . $mail_title;
}
if ($mail["toCharacterIDs"] > '')
{
$recipients = explode(',', $mail["toCharacterIDs"]);
foreach ($recipients as $character)
{
if ($character <> $mail["senderID"])
{
$name = getUserNameByID($character);
$to_list .= '<a style="color: #fa9e0e; text-decoration: none" href="https://gate.eveonline.com/Profile/' .
str_replace(' ', '%20', $name) . '/">' . $name . '</a>, ';
}
}
}
//get mesage body from api
$mailbody = "https://api.eveonline.com/char/MailBodies.xml.aspx?ids={$mail["messageID"]}&characterID={$characterID}&keyID={$keyID}&vCode={$vCode}";
$xml_mailbody = simplexml_load_string(file_get_contents($mailbody), null, LIBXML_NOCDATA);
$xml_amailbody = object2array($xml_mailbody);
$body = $xml_amailbody['result']['rowset']['row'];
//strip questionable things
$body = nl2br(strip_tags($body, '<a><b><br><p>'));
$body = str_replace("<a href=", "<a style=\"color: #fa9e0e; text-decoration: none\" href=", $body);
//eve style formatted mail body
$mail_body = '
<div style="color: #CCCCCC; background-color: #222222; padding: 15px">
<div style="position: relative; text-align: left; margin: 0 auto; font-size: 12px; width: 620px; padding: 20px; background-color: #333333;">
<div style="position: absolute; right: 0px; top: 0px;">
<p style="margin: 0px; color: #898989;"> ' . $mail["sentDate"] . '</p>
</div>
<h2 style="font-size: 18px; font-weight: normal; width: 620px;">' . $mail["title"] . '</h2>
<p style="margin: 0px; color: #898989;">
<span style="font-weight: bold;">From:</span> <a style="color: #fa9e0e; text-decoration: none" href="https://gate.eveonline.com/Profile/' .
str_replace(' ', '%20', getUserNameByID($mail["senderID"])) . '">' . getUserNameByID($mail["senderID"]) . '</a><br>
<span style="font-weight: bold;">To:</span> ' . $to_list . '
</p>
<br>
' . $body . '
<br />
<br />
<br />
<hr />
<a style="font-weight:bold; color: #fa9e0e; text-decoration: none" href="https://gate.eveonline.com/Mail/ReadMessage/' .
$mail["messageID"] . '/">If You want to reply, go to eve gate...</a>
</div>
</div>
';
//if there was no filter conditions met - send it
if (!$no_send)
{
SendMail("\"{$characterNAME}\"<{$forwardmail}>", '"' . getUserNameByID($mail["senderID"]) . '"' . "<{$from_mail}>", $mail_title, $mail_body);
}
}
}
}
}<file_sep><?php
/**
*
* form to add api, configure what to forward, etc
*
* working example here: http://ash-alliance.eu/evegate.php
*
*
*/
session_start();
include('include/db.php');
include('include/api_calls.php');
include('include/config.php');
//process post requests - start
if ($_POST['mode'] == 'logout')
{
$_SESSION['evegate'][0] = array();
$_SESSION['evegate']['loggedin'] = 0;
$_POST = array();
}
if ($_POST['mode'] == 'config')
{
$api_key = $_SESSION['evegate'][0];
$condition = " key_id = '{$api_key['key_id']}' ";
$data = array();
$data['forward_mail'] = mysql_real_escape_string($_POST['email']);
$filters['fromsent'] = $_POST['fromsent'];
$filters['fromcorp'] = $_POST['fromcorp'];
$filters['fromally'] = $_POST['fromally'];
foreach ($_POST as $pk => $pw)
{
if (substr($pk, 0, 4) == 'sub_')
{
$lid = substr($pk, 4);
$filters[$lid] = 1;
}
}
$data['filters'] = serialize($filters);
UpdateData($data, 'api_keys', $condition);
$api_key = GetRow("SELECT * FROM api_keys WHERE key_id = '{$api_key['key_id']}' AND v_code = '{$api_key['v_code']}' ");
$_SESSION['evegate'][0] = $api_key;
$_SESSION['evegate']['loggedin'] = 1;
}
if ($_POST['mode'] == 'login')
{
$_POST['vcode'] = mysql_real_escape_string($_POST['vcode']);
$_POST['keyid'] = mysql_real_escape_string($_POST['keyid']);
$api_key = GetRow("SELECT * FROM api_keys WHERE key_id = '{$_POST['keyid']}' AND v_code = '{$_POST['vcode']}' ");
//if not in db, try to register
if (!$api_key['key_id'])
{
$url = 'https://api.eveonline.com/account/APIKeyInfo.xml.aspx?keyID=' . $_POST['keyid'] . '&vCode=' . $_POST['vcode'];
$xml_object = simplexml_load_string(file_get_contents($url));
$xml_array = object2array($xml_object);
$characterID = $xml_array["result"]["key"]["rowset"]["row"]["@attributes"]["characterID"];
$characterNAME = getUserNameByID($characterID);
if (strlen($characterNAME) > 3)
{
$regdata = array('key_id' => $_POST['keyid'], 'v_code' => $_POST['vcode'], 'username' => $characterNAME);
InsertData($regdata, 'api_keys');
$api_key = GetRow("SELECT * FROM api_keys WHERE key_id = '{$_POST['keyid']}' AND v_code = '{$_POST['vcode']}' ");
}
}
if (!$api_key['key_id'])
{
?>
<H3>Error! Bad api key.</H3>
<?
exit;
}
$_SESSION['evegate'][0] = $api_key;
$_SESSION['evegate']['loggedin'] = 1;
}
// process post requests - end
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" />
<link href="style.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="row">
<?php
// login / register form
if ($_SESSION['evegate']['loggedin'] <> 1)
{
?>
<h2>Login or Register</h2>
<p>
If You want to register, create predefined <a
href="https://support.eveonline.com/api/Key/CreatePredefined/52736"
target="new" rel="nofollow">API key</a>, for exactly one character (not for account!).<br/>
In next step, set Your real E-mail address. That's all.
</p>
<p>
For managing simply use the same api key/vCode pair to login.
</p>
<form method="post" action="">
<label>Key ID<input type="text" name="keyid" class="edit"/></label>
<label>Verification Code<input type="text" name="vcode" class="edit"/></label>
<label><input type="submit" class="btn" value="Submit"/></label>
<input type="hidden" name="mode" value="login"/>
</form>
<?
}
else // api configure form
{
$url = 'https://api.eveonline.com/account/APIKeyInfo.xml.aspx?keyID=' . $_SESSION['evegate'][0]['key_id'] . '&vCode=' . $_SESSION['evegate'][0]['v_code'];
$xml_object = simplexml_load_string(file_get_contents($url));
$xml_array = object2array($xml_object);
$characterID = $xml_array["result"]["key"]["rowset"]["row"]["@attributes"]["characterID"];
$characterNAME = getUserNameByID($characterID);
?>
<h2>Welcome back <?
echo $_SESSION['evegate'][0]['username'];
?></h2>
<form method="post" action="">
<label>Key ID: <?= $_SESSION['evegate'][0]['key_id'] ?></label>
<label>Verification Code: <?= substr($_SESSION['evegate'][0]['v_code'], 0, 16) ?>...</label>
<label>email address: <input type="text" name="email" placeholder="Your e-mail address"
value="<?= $_SESSION['evegate'][0]['forward_mail'] ?>"
class="edit"/></label>
<h3>Filters (message types You want to exclude) </h3>
<label>Sent folder: <input type="checkbox"
name="fromsent" <? is_checked('fromsent', $_SESSION['evegate'][0]['filters']); ?>
class="edit" value="1"/></label>
<label>From Corp: <input type="checkbox"
name="fromcorp" <? is_checked('fromcorp', $_SESSION['evegate'][0]['filters']); ?>
class="edit" value="1"/></label>
<label>From Ally: <input type="checkbox"
name="fromally" <? is_checked('fromally', $_SESSION['evegate'][0]['filters']); ?>
class="edit" value="1"/></label>
<h3>Mailing lists</h3>
<?
$url = 'https://api.eveonline.com/char/mailinglists.xml.aspx?characterID=' . $characterID . '&keyID=' . $_SESSION['evegate'][0]['key_id'] . '&vCode=' . $_SESSION['evegate'][0]['v_code'];
$xml_object = simplexml_load_string(file_get_contents($url));
$xml_array = object2array($xml_object);
foreach ($xml_array["result"]["rowset"]["row"] as $lrow)
{
$lid = $lrow['@attributes']['listID'];
$lname = $lrow['@attributes']['displayName'];
?>
<label><?= $lname ?>: <input type="checkbox"
name="sub_<?= $lid ?>" <? is_checked($lid, $_SESSION['evegate'][0]['filters']); ?>
class="edit" value="1"/></label>
<?
}
?>
<input type="hidden" name="mode" value="config"/>
<label><input type="submit" value="Submit" class="btn"/></label>
</form>
<br/>
<br/>
<br/>
<hr/>
<?
// logout button
?>
<form method="post" action="">
<input type="hidden" name="mode" value="logout"/>
<input type="submit" class="btn" value="Exit and logout"/>
</form>
<?
}
?>
<br/>
<br/>
</div>
</div>
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
</body>
</html>
<file_sep><?php
/**
*
* db fnc
*
*/
function ExecQuery($sql)
{
$result = mysql_query($sql);
if (!mysql_error())
{
$result_bool = true;
}
else
{
$result_bool = false;
}
return ($result_bool);
}
function dbConnection($ip, $user, $pass, $name)
{
$link = mysql_connect($ip, $user, $pass);
mysql_select_db($name, $link);
return $link;
}
function InsertData($data, $table)
{
$fields = '';
$values = '';
if ((is_array($data))and(count($data) > 0))
{
foreach ($data as $key => $value)
{
$fields .= $key . ", ";
if (is_array($value))
{
$values .= current($value) . ", ";
}
else
{
$values .= "'" . addslashes($value) . "', ";
}
}
}
$fields = preg_replace("/, $/", "", $fields);
$values = preg_replace("/, $/", "", $values);
$query = "INSERT INTO " . $table . "(" . $fields . ") VALUES(" . $values . "); ";
ExecQuery($query);
return (mysql_insert_id());
}
function UpdateData($data, $table, $where)
{
$query = 'UPDATE ' . $table . " SET ";
foreach ($data as $key => $value)
{
if (is_array($value))
{
$query .= $key . "=" . current($value) . ", ";
}
else
{
$query .= $key . "='" . addslashes($value) . "', ";
}
}
$query = preg_replace("/, $/", "", $query);
$query .= " WHERE " . $where;
ExecQuery($query);
return (mysql_affected_rows());
}
function GetValue($sql)
{
$result = mysql_query($sql);
$rows_count = @mysql_num_rows($result);
if ($rows_count == 1)
{
$row = @mysql_fetch_row($result);
}
@mysql_free_result($result);
return (stripcslashes(@$row[0]));
}
function GetRow($sql)
{
$result = mysql_query($sql);
if (!$result)
{
return false;
}
$rows_count = mysql_num_rows($result);
if ($rows_count == 1)
{
$row = StripSlashesRow(mysql_fetch_array($result));
}
$row_tmp = @$row;
for ($i = 0; $i < count($row_tmp); $i++)
unset($row_tmp[$i]);
$row = $row_tmp;
return ($row);
}
function StripSlashesRow($row)
{
if (count($row))
{
foreach ($row as $key => $value)
$row_upd[$key] = stripslashes($value);
return ($row_upd);
}
else
{
return ($row);
}
}
function GetResult($sql)
{
$row = array();
$result = mysql_query($sql);
if (!mysql_error())
{
$rows_count = @mysql_num_rows($result);
if ($rows_count)
{
for ($j = 0; $j < $rows_count; $j++)
{
$row_tmp = mysql_fetch_array($result, MYSQL_ASSOC);
$row_tmp = StripSlashesRow($row_tmp);
$row[$j] = $row_tmp;
}
}
}
@mysql_free_result($result);
return ($row);
}
| 0bb8ed88e547ed33d965a7845673034314b54755 | [
"Markdown",
"SQL",
"PHP"
]
| 8 | SQL | Covert-Inferno/evegate | 56b332046a32edaef40c8fe1aac670101d1fee3a | b91b683cd9e6795d567e00d069c6d9fc8acae6eb |
refs/heads/main | <repo_name>jaswanth333/GalleryApp-React<file_sep>/README.md
# GalleryApp-React
This App lets you view selected images from an list of images
#Nextupdate
1.To Add navigation between list of images<file_sep>/src/Images.js
export default [
"https://images.unsplash.com/photo-1471400974796-1c823d00a96f?ixlib=rb-1.2.1&dpr=1&auto=format&fit=crop&w=525&q=60",
"https://images.unsplash.com/photo-1505507845306-2c0ac7d65c6f?ixlib=rb-1.2.1&dpr=1&auto=format&fit=crop&w=525&q=60",
"https://images.unsplash.com/photo-1540206395-25926266db56?ixlib=rb-1.2.1&dpr=1&auto=format&fit=crop&w=525&q=60"
];
| 20b7e59349b7aa3966318d45326e37f7a3713a81 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | jaswanth333/GalleryApp-React | 2dbcd6374303bfc2b0d38853630c84500dd5d6a7 | c3ce3c186a3755854c76554934ceeac89fc033fd |
refs/heads/master | <repo_name>bradcypert/gorgeous-elephant-timelord<file_sep>/README.md
# gorgeous-elephant-timelord
Super basic server demonstrating how Clojure + Luminus works.
## Prerequisites
You will need [Leiningen][1] 2.0 or above installed.
[1]: https://github.com/technomancy/leiningen
## Running
To run db migrations, run:
lein migratus
To start a web server for the application, run:
lein run
Get that `localhost:3000/locations/1` and check that JSON ;)
## License
Copyright © 2015 FIXME
<file_sep>/resources/sql/queries.sql
-- name:get-locations
-- retrive all locations
SELECT * FROM locations
-- name:get-location
-- retrieve a user given the id.
SELECT * FROM locations
WHERE id = :id
<file_sep>/resources/migrations/001-main.up.sql
create table locations (id serial primary key, name varchar(200), locx real, locy real);
--;;
insert into locations (name, locx, locy) values ('Portland, OR', 45.5200, 122.6819); | 02e97cf94f2e48d1241581b8bb860607d3ea4421 | [
"Markdown",
"SQL"
]
| 3 | Markdown | bradcypert/gorgeous-elephant-timelord | 0a7043837f03fb7d2e83f920f838677dc5c2bd40 | 666e8c472a05acee22e823ef60ae682d87726073 |
refs/heads/master | <file_sep>#include "camera.hpp"
#include <iostream>
//constructor
Camera::Camera(){
int i;
std::cout << "Initialized" << std::endl;
capture = NULL;
for(i=0 ; capture == NULL ;i++){
capture = new cv::VideoCapture(i);
}
std::cout << "CameraID: " << i << std::endl;
}
//destructor
Camera::~Camera(){
delete capture;
}
void Camera::windowTest(){
std::cout << "Camera Test" << std::endl;
// cv::Mat redImg( cv::Size(320,240), CV_8UC3 , cv::Scalar(0,0,255));
cv::namedWindow("camera", cv::WINDOW_AUTOSIZE);
while(1) {
cv::Mat frame;
if (!(capture -> read(frame))) std::cout << "miss!" << std::endl;
cv::imshow("camera" , frame);
if (cv::waitKey(10) == 27){
break;
} else {
continue;
}
}
cv::destroyAllWindows();
}
<file_sep>#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
class Camera {
private:
cv::VideoCapture *capture;
public:
Camera();
~Camera();
void windowTest();
};<file_sep>#include<iostream>
#include "camera.hpp"
int main(void) {
Camera *camera = new Camera();
camera -> windowTest();
delete camera;
return 0;
}<file_sep>test1: main.cpp camera.cpp
g++ main.cpp camera.cpp \
-I/usr/include/opencv2 \
-L/usr/lib \
-lopencv_calib3d -lopencv_imgproc -lopencv_contrib -lopencv_core -lopencv_highgui | 942bdff69ff0028a952f5e0b7f29ae77022bc8df | [
"Makefile",
"C++"
]
| 4 | C++ | mukuri07/opencvtest | 7e5b7b3212a284c464103de8780cbe9067d6b8f0 | 978ab65db8516c21adc77c2602357835721ee531 |
refs/heads/master | <repo_name>navbor/neovim<file_sep>/src/os/input.h
#ifndef NEOVIM_OS_INPUT_H
#define NEOVIM_OS_INPUT_H
#include <stdint.h>
#include <stdbool.h>
void input_init(void);
bool input_ready(void);
void input_start(void);
void input_stop(void);
uint32_t input_read(char *buf, uint32_t count);
int os_inchar(uint8_t *, int, int32_t, int);
bool os_char_avail(void);
void os_breakcheck(void);
#endif // NEOVIM_OS_INPUT_H
| ac5b28c7f297c384eec09bbdee9cc76f21536545 | [
"C"
]
| 1 | C | navbor/neovim | 73fdf2d8e9e359ad80bf0538f74d1fdf5abd9389 | a80734ebb077f2239189eca85482988452323baf |
refs/heads/master | <file_sep>package org.netbeans.modules.ppcnf.main;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.prefs.Preferences;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectUtils;
import org.netbeans.spi.project.ui.support.ProjectCustomizer;
import org.openide.awt.Mnemonics;
import org.openide.util.Lookup;
public class PeterProjectCustomizer implements ProjectCustomizer.CompositeCategoryProvider {
@ProjectCustomizer.CompositeCategoryProvider.Registrations({
@ProjectCustomizer.CompositeCategoryProvider.Registration(
projectType = "org-netbeans-modules-java-j2seproject", // J2SE project type
position = 1000
)
})
public static PeterProjectCustomizer createCustomizer() {
return new PeterProjectCustomizer();
}
@Override
public ProjectCustomizer.Category createCategory(Lookup context) {
return ProjectCustomizer.Category.create("special", "Special", null);
}
@Override
public JComponent createComponent(ProjectCustomizer.Category category, Lookup context) {
Project project = context.lookup(Project.class);
final Preferences prefs = ProjectUtils.getPreferences(project, PeterProjectCustomizer.class, true);
JPanel panel = new JPanel();
final JCheckBox compileOnSave = new JCheckBox((String) null,
"true".equals(prefs.get("showMyNode", null)));
Mnemonics.setLocalizedText(compileOnSave, "&Show my node");
panel.add(compileOnSave);
category.setStoreListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (compileOnSave.isSelected()) {
prefs.put("showMyNode", "true");
} else {
prefs.remove("showMyNode");
}
}
});
return panel;
}
}<file_sep># Peter's ProjectCustomizer/NodeFactory
Go here for all the details:
<a href="https://blogs.oracle.com/geertjan/entry/projectcustomizer_nodefactory_combination">https://blogs.oracle.com/geertjan/entry/projectcustomizer_nodefactory_combination</a>
| 75b5515892a17707b808febe703762ed30cdd49c | [
"Markdown",
"Java"
]
| 2 | Java | GeertjanWielenga/PeterProjectCustomizerNodeFactory | eac55a3f208440f9773a7febb7d9597bde20d47b | 0b1d3c121a4244ea843eb081fa20b6de6be48883 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Configuration;
using FranklinSoft.RegCompare;
using FranklinSoft.RegCompare.Results;
namespace FranklinSoft.RegCompareDesktop
{
public partial class Form1 : Form
{
private List<RegistryEntry> _machineARegistryEntries;
private List<RegistryEntry> _machineBRegistryEntries;
private List<RegistryEntry> _missingEntriesFromMachineB;
private List<RegistryEntry> _missingEntriesFromMachineA;
private List<RegistryEntryDifference> _registryEntryDifferences;
private readonly int _testConnectionTimeout = Config.TestConnectionTimeout;
private readonly int _retrieveRegistryTimeout = Config.RetrieveRegistryTimeout;
private readonly string _defaultRegistryKeyRoot = Config.DefaultRegistryKeyRoot;
private readonly string _defaultMachineA = Config.DefaultMachineA;
private readonly string _defaultMachineB = Config.DefaultMachineB;
public Form1()
{
InitializeComponent();
lbl_MachineALoading.Visible = false;
lbl_MachineBLoading.Visible = false;
_machineARegistryEntries = new List<RegistryEntry>();
_machineBRegistryEntries = new List<RegistryEntry>();
_missingEntriesFromMachineB = new List<RegistryEntry>();
_missingEntriesFromMachineA = new List<RegistryEntry>();
_registryEntryDifferences = new List<RegistryEntryDifference>();
dataGridView1.BackgroundColor = dataGridView1.DefaultCellStyle.BackColor;
dataGridView2.BackgroundColor = dataGridView2.DefaultCellStyle.BackColor;
dataGridView3.BackgroundColor = dataGridView3.DefaultCellStyle.BackColor;
dataGridView4.BackgroundColor = dataGridView4.DefaultCellStyle.BackColor;
dataGridView5.BackgroundColor = dataGridView5.DefaultCellStyle.BackColor;
combobox_registryHive.DataSource = Enum.GetValues(typeof(RegistryHive));
combobox_registryHive.SelectedIndex = 1;
textbox_registryKeyRoot.Text = Config.DefaultRegistryKeyRoot;
textBox_machineAName.Text = Config.DefaultMachineA;
textBox_machineBName.Text = Config.DefaultMachineB;
}
private async void button1_Click(object sender, EventArgs e)
{
ClearDataTables();
ClearStatusBar();
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
RegistryHive registryHive = (RegistryHive)combobox_registryHive.SelectedItem;
var testConnectionA = TestConnection(textBox_machineAName.Text, lbl_MachineALoading, tokenSource, token);
var testConnectionB = TestConnection(textBox_machineBName.Text, lbl_MachineBLoading, tokenSource, token);
await Task.WhenAny(Task.WhenAll(new List<Task>() { testConnectionA, testConnectionB }));
if (!token.IsCancellationRequested)
{
var t1 = GetRegisty(registryHive, textBox_machineAName.Text, lbl_MachineALoading, tokenSource, token);
var t2 = GetRegisty(registryHive, textBox_machineBName.Text, lbl_MachineBLoading, tokenSource, token);
await Task.WhenAny(Task.WhenAll(new List<Task>() { t1, t2 }));
_machineARegistryEntries = t1.Result;
_machineBRegistryEntries = t2.Result;
}
if (!token.IsCancellationRequested)
{
PopulateRegistryTable(lbl_MachineALoading, dataGridView1, _machineARegistryEntries);
PopulateRegistryTable(lbl_MachineBLoading, dataGridView2, _machineBRegistryEntries);
}
if (!token.IsCancellationRequested)
await PopulateTabs();
}
private async Task TestConnection(string machineName, Label machineLabel, CancellationTokenSource tokenSource, CancellationToken token)
{
machineLabel.Text = "Testing Connection";
machineLabel.Visible = true;
TestConnectionResult testConnection =
await RegistryCompare.TestConnectionAsync(machineName, tokenSource, token, _testConnectionTimeout);
if (!testConnection.Successful)
{
if (testConnection.ErrorCode == ErrorCodes.SECURITY_EXCEPTION ||
testConnection.ErrorCode == ErrorCodes.UNAUTHORIZED_ACCESS_EXCEPTION)
{
machineLabel.Text = "Access Denied";
}
else if (testConnection.ErrorCode == ErrorCodes.IO_EXCEPTION)
{
machineLabel.Text = "Invalid Machine Name.";
}
else if (testConnection.ErrorCode == ErrorCodes.TIMEOUT)
{
machineLabel.Text = "Connection Timeout.";
}
try
{
SetStatusStripText("Error");
tokenSource.Cancel();
token.ThrowIfCancellationRequested();
}
catch (OperationCanceledException) { }
}
else
{
machineLabel.Text = "Connection Successful";
}
}
private async Task<List<RegistryEntry>> GetRegisty(RegistryHive registryHive, string machineName, Label machineLabel, CancellationTokenSource tokenSource, CancellationToken token)
{
machineLabel.Text = "Loading Registry";
machineLabel.Visible = true;
RegistryEntriesResult result = await RegistryCompare.GetRegistryEntriesAsync(registryHive, textbox_registryKeyRoot.Text, machineName, tokenSource, token, _testConnectionTimeout);
if (!result.Successful)
{
if (result.ErrorCode == ErrorCodes.SECURITY_EXCEPTION ||
result.ErrorCode == ErrorCodes.UNAUTHORIZED_ACCESS_EXCEPTION)
{
machineLabel.Text = "Access Denied";
}
else if (result.ErrorCode == ErrorCodes.IO_EXCEPTION)
{
machineLabel.Text = "Invalid Machine Name.";
}
else if (result.ErrorCode == ErrorCodes.TIMEOUT)
{
machineLabel.Text = "Connection Timeout.";
}
try
{
tokenSource.Cancel();
token.ThrowIfCancellationRequested();
}
catch (OperationCanceledException)
{
SetStatusStripText("Error");
return new List<RegistryEntry>(){};
}
}
SetStatusStripText("Success");
machineLabel.Text = "Loaded";
return result.RegistryEntries;
}
private void PopulateRegistryTable(Label machineLabel, DataGridView dataGridView, List<RegistryEntry> machineRegistryEntries)
{
machineLabel.Text = "Populating Table";
machineLabel.Visible = true;
if (machineRegistryEntries.Count <= 0)
{
machineLabel.Text = "There are no items under the specified key";
}
DataTable table = CreateDataTable(machineRegistryEntries);
dataGridView.DataSource = table;
SetColumnProperties(dataGridView);
StretchLastColumn(dataGridView);
machineLabel.Text = "Done";
}
private async Task PopulateTabs()
{
_missingEntriesFromMachineB = RegistryCompare.FindMissingRegistryEntries(_machineARegistryEntries, _machineBRegistryEntries);
PopulateTab(_missingEntriesFromMachineB, dataGridView3);
_missingEntriesFromMachineA = RegistryCompare.FindMissingRegistryEntries(_machineBRegistryEntries, _machineARegistryEntries);
PopulateTab(_missingEntriesFromMachineA, dataGridView4);
_registryEntryDifferences = RegistryCompare.FindMatchingRegistryEntries(_machineARegistryEntries, _machineBRegistryEntries);
PopulateTab(_registryEntryDifferences, dataGridView5);
}
private void PopulateTab<T>(IEnumerable<T> list, DataGridView dataGridView)
{
var table = CreateDataTable(list);
dataGridView.DataSource = table;
SetColumnProperties(dataGridView);
StretchLastColumn(dataGridView);
}
public static DataTable CreateDataTable<T>(IEnumerable<T> list)
{
Type type = typeof(T);
var properties = type.GetProperties();
DataTable dataTable = new DataTable();
foreach (PropertyInfo info in properties)
{
dataTable.Columns.Add(new DataColumn(info.Name,
Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
}
foreach (T entity in list)
{
object[] values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(entity);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
private void btn_missingEntriesFromMachineB_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Registry File|*.reg";
saveFileDialog1.Title = "Save a Registry File";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
StreamWriter sw = new StreamWriter(saveFileDialog1.OpenFile());
RegFileHandler.ExportMissingEntries(_missingEntriesFromMachineB, sw);
}
}
private void btn_missingEntriesFromMachineA_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Registry File|*.reg";
saveFileDialog1.Title = "Save a Registry File";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
StreamWriter sw = new StreamWriter(saveFileDialog1.OpenFile());
RegFileHandler.ExportMissingEntries(_missingEntriesFromMachineA, sw);
}
}
private void btn_matchingDifferences_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Text File|*.txt";
saveFileDialog1.Title = "Save File";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
StreamWriter sw = new StreamWriter(saveFileDialog1.OpenFile());
RegFileHandler.ExportMatchingDifferences(_registryEntryDifferences, sw);
}
}
private void textBox1_Enter(object sender, EventArgs e)
{
if (textBox_machineAName.Text == _defaultMachineA)
{
textBox_machineAName.Text = string.Empty;
}
}
private void textBox1_Leave(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(textBox_machineAName.Text))
{
textBox_machineAName.Text = _defaultMachineA;
}
}
private void textBox2_Enter(object sender, EventArgs e)
{
if (textBox_machineBName.Text == _defaultMachineB)
{
textBox_machineBName.Text = string.Empty;
}
}
private void textBox2_Leave(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(textBox_machineBName.Text))
{
textBox_machineBName.Text = _defaultMachineB;
}
}
private void textBox3_Enter(object sender, EventArgs e)
{
if (textbox_registryKeyRoot.Text == _defaultRegistryKeyRoot)
{
textbox_registryKeyRoot.Text = string.Empty;
}
}
private void textBox3_Leave(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(textbox_registryKeyRoot.Text))
{
textbox_registryKeyRoot.Text = _defaultRegistryKeyRoot;
}
}
private void btn_missingEntriesFromMachineARefresh_Click(object sender, EventArgs e)
{
DataTable table = CreateDataTable(_missingEntriesFromMachineA);
dataGridView4.DataSource = table;
}
private void btn_missingEntriesFromMachineBRefresh_Click(object sender, EventArgs e)
{
DataTable table = CreateDataTable(_missingEntriesFromMachineB);
dataGridView3.DataSource = table;
}
private void btn_matchingDifferencesRefresh_Click(object sender, EventArgs e)
{
DataTable table = CreateDataTable(_registryEntryDifferences);
dataGridView5.DataSource = table;
}
private void SetStatusStripText(string text)
{
toolStripStatusLabel1.Text = text;
}
private void ClearDataTables()
{
dataGridView1.DataSource = null;
dataGridView1.Refresh();
dataGridView2.DataSource = null;
dataGridView2.Refresh();
dataGridView3.DataSource = null;
dataGridView3.Refresh();
dataGridView4.DataSource = null;
dataGridView4.Refresh();
dataGridView5.DataSource = null;
dataGridView5.Refresh();
}
private void ClearStatusBar()
{
toolStripStatusLabel1.Text = string.Empty;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
public static void StretchLastColumn(DataGridView dataGridView)
{
var lastColIndex = dataGridView.Columns.Count - 1;
var lastCol = dataGridView.Columns[lastColIndex];
lastCol.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
public static void SetColumnProperties(DataGridView dataGridView)
{
foreach (DataGridViewColumn column in dataGridView.Columns)
{
column.MinimumWidth = 200;
column.SortMode = DataGridViewColumnSortMode.Automatic;
}
}
}
}
<file_sep># FranklinSoft.RegCompareDesktop

## RegCompareDesktop is a desktop interface for RegCompare.
- Find matching differences.
- Find missing keys
- Save missing results to a .reg file
## Installation
[](https://github.com/DouganRedhammer/FranklinSoft.RegCompareDesktop/releases/latest)
The Setup will remove the previous version before installing.
Use the zip for the non-install version.
## Release Notes
* Added error handling and replaced more sync calls with async
License
----
MIT
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace FranklinSoft.RegCompareDesktop
{
public static class Config
{
public static int TestConnectionTimeout => int.Parse(ConfigurationManager.AppSettings["TestConnectionTimeout"]);
public static int RetrieveRegistryTimeout => int.Parse(ConfigurationManager.AppSettings["RetrieveRegistryTimeout"]);
public static string DefaultRegistryKeyRoot => ConfigurationManager.AppSettings["DefaultRegistryKeyRoot"];
public static string DefaultMachineA => ConfigurationManager.AppSettings["DefaultMachineA"];
public static string DefaultMachineB => ConfigurationManager.AppSettings["DefaultMachineB"];
}
}
| 4d0de6f892dfec9db1e6e953a50f94287026a447 | [
"Markdown",
"C#"
]
| 3 | C# | DouganRedhammer/FranklinSoft.RegCompareDesktop | b543fd6279ea6db8a7790a5cfe91bf703de910e0 | 4f570ad9fca22c3cbc13f21b8d737c64dcd61b47 |
refs/heads/master | <file_sep>$(function(){
$("#dashBoard").attr("class","highlight active");
})<file_sep>$(function () {
var opt = {
foreColor:'#e25a48',
horTitle:'Arizona'
};
$('#arizona').barIndicator(opt);
});
$(function () {
var opt = {
foreColor:'#74b749',
horTitle:'California'
};
$('#california').barIndicator(opt);
});
$(function () {
var opt = {
foreColor:'#ffb400',
horTitle:'Florida'
};
$('#florida').barIndicator(opt);
});
$(function () {
var opt = {
foreColor:'#3693cf',
horTitle:'New Jersey'
};
$('#newJersey').barIndicator(opt);
});<file_sep>$(function(){
$("#user").attr("class","highlight active");
})<file_sep>$(function(){
$("#conf").attr("class","has-sub highlight active");
$("#confUl").css("display","block");
$("#conf_recevie").append('<span class="current-page"></span>');
}) | ef76765737031b42a17cd8c0fb347611524ed43b | [
"JavaScript"
]
| 4 | JavaScript | SKHon/openSource | 5b0ac7c8b08b1b61d70f2e3e2a880e6549791b19 | 19d1609e4f440e1c9cfb3c80e3fc3a99859404f7 |
refs/heads/master | <file_sep><?php
class StoreController extends Controller
{
function index()
{
$this->view("Store/index");
}
function cartAdd(){
session_start();
// 資料庫連線參數
$link = include 'config.php';
//抓取商品
$sql = <<<mutil
select * from product where id = "$_GET[productId]";
mutil;
$result = mysqli_query($link, $sql);
$product = mysqli_fetch_assoc($result);
//確認購物車是否有重複商品
$sql = <<<mutil
select * from cart where orderid = "$_SESSION[orderId]" and productId = "$_GET[productId]";
mutil;
$result = mysqli_query($link, $sql);
$cart = mysqli_fetch_assoc($result);
if ($cart == Null){
$sql = <<<mutil
insert into cart(orderId, productId, quantity, total)
values($_SESSION[orderId], $product[id], $_GET[quantity], $product[price]*$_GET[quantity])
mutil;
}else{
$sql = <<<mutil
update cart
set
quantity = quantity + $_GET[quantity],
total = quantity*$product[price]
where
id = $cart[id]
mutil;
}
if(mysqli_query($link, $sql)){
echo('已加入購物車');
}else{
echo('請先登入會員');
}
}
function cartUpdate(){
session_start();
// 資料庫連線參數
$link = include 'config.php';
//抓取商品
$sql = <<<mutil
select * from product where id = "$_GET[productId]";
mutil;
$result = mysqli_query($link, $sql);
$product = mysqli_fetch_assoc($result);
$sql = <<<mutil
update cart
set
quantity = $_GET[quantity],
total = quantity*$product[price]
where
id = $_GET[cartId]
mutil;
if(mysqli_query($link, $sql)){
echo('已更改購物車');
}else{
echo('更改失敗');
}
}
function orderCheck(){
session_start();
// 資料庫連線參數
$link = include 'config.php';
//確定訂單金額
$sql = <<<mutil
select * from cart where orderId = "$_SESSION[orderId]";
mutil;
$result = mysqli_query($link, $sql);
$orderTotal;
while($cart = mysqli_fetch_assoc($result)):
$orderTotal += $cart['total'];
endwhile;
$sql = <<<mutil
update orders
set
total = $orderTotal
where
id = $_SESSION[orderId]
mutil;
mysqli_query($link, $sql);
return $this->view('store/orderCheck');
}
function carts(){
$this->view('Store/carts');
}
function pay(){
$this->view('Store/sample_All_CreateOrder');
}
function orderDone(){
$link = include 'config.php';
$sql = <<<mutil
update orders
set
done = True
where
id = $_GET[orderId]
mutil;
mysqli_query($link, $sql);
}
function orders(){
return $this->view('Store/orders');
}
function order(){
return $this->view('Store/order');
}
}
?><file_sep><?php
$link = include 'config.php';
$sql = <<<mutil
select *, p.id, c.id categoryId from product as p inner join category as c on p.categoryId = c.id where p.id = $_GET[productId];
mutil;
$result = mysqli_query($link, $sql);
$product = mysqli_fetch_assoc($result);
$sql = <<<mutil
select * from category;
mutil;
$category = mysqli_query($link, $sql);
?>
<?php require_once('header.php'); ?>
<div style="padding-top:5.5em;" align="center">
<form id="form1" name="form1" method="post" action="http://localhost:8888/PID_Assignment/backend/productUpdate" enctype="multipart/form-data">
<input type="hidden" name="productId" value=<?php echo $product['id']?>>
<table width="300" border="0" align="center" cellpadding="5" cellspacing="0" bgcolor="#F2F2F2">
<tr>
<td width="80" align="center" valign="baseline">商品名稱</td>
<td valign="baseline"><input type="text" name="productName" id="productName" required="required" value="<?php echo $product['productName'] ?>"/></td>
</tr>
<tr>
<td width="80" align="center" valign="baseline">商品類別</td>
<td valign="baseline">
<select name="categoryId">
<?php while ($row = mysqli_fetch_assoc($category)): ?>
<option value="<?php echo $row['id'] ?>" <?php if($row['id'] = $product['categoryId']){echo "selected";} ?>><?php echo $row['categoryName'] ?></option>
<?php endwhile ?>
</select>
</td>
</tr>
<tr>
<td width="80" align="center" valign="baseline">商品價格</td>
<td valign="baseline"><input type="number" name="productPrice" id="productPrice" required="required" value="<?php echo $product['price']?>"/></td>
</tr>
<tr>
<td width="80" align="center" valign="baseline">商品內容</td>
<td valign="baseline"><textarea rows="4" cols="50" name="productDescription"><?php echo $product['description']?></textarea></td>
</tr>
<tr>
<td width="80" align="center" valign="baseline">圖片</td>
<td valign="baseline">
<input type="file" name="fileToUpload" id="fileToUpload">
<div class="c-zt-pic">
<img id="preview" src="../<?php echo $product['picture']?>">
</div>
</td>
</tr>
<tr>
<td colspan="2" align="center" bgcolor="#CCCCCC"><input type="submit" name="btnOK" id="btnOK" value="確認" />
<a href="http://localhost:8888/PID_Assignment/backend/products" class="cancel">取消</a>
</td>
</tr>
</table>
</form>
</div>
<script>
$('#fileToUpload').change(function() {
var f = document.getElementById('fileToUpload').files[0];
var src = window.URL.createObjectURL(f);
document.getElementById('preview').src = src;
});
</script>
<?php require_once('views/store/footer.php'); ?><file_sep><?php
$link = include 'config.php';
$sql = <<<mutil
select * from user where role = "會員";
mutil;
$result = mysqli_query($link, $sql);
?>
<?php require_once('header.php'); ?>
<script src='/PID_Assignment/js/jquery.min.js'></script>
<div style="padding-top:5.5em;" align="center">
<table>
<tr>
<th>編號</th><th>會員名稱</th><th>會員級別</th><th>啟用/停用</th>
</tr>
<?php while ($row = mysqli_fetch_assoc($result)): ?>
<tr>
<td><?php echo $row['id'] ?></td>
<td><?php echo $row['userName'] ?></td>
<td><?php echo $row['role'] ?></td>
<td><input type="checkbox" name="isActive" value=<?php echo $row['id'] ?> <?php if($row['isActive']){echo "checked";} ?>></td>
</tr>
<?php endwhile ?>
</table>
</div>
<script>
$(document).on('change', 'input[name=isActive]', function () {
var $this = $(this);
$.ajax({
type:"GET",
url:"http://localhost:8888/PID_Assignment/backend/memberisActive?userId="+$this.val()
})
.done(function (data) {
alert(data);
})
});
</script>
<?php require_once('views/store/footer.php'); ?><file_sep><?php
class BackendController extends Controller
{
function index()
{
$this->view("Backend/index");
}
function members()
{
$this->view("Backend/members");
}
function memberisActive()
{
// 資料庫連線參數
$link = include 'config.php';
$userId = $_GET['userId'];
$sql = <<<mutil
select * from user where id = '$userId';
mutil;
$result = mysqli_query($link, $sql);
$search = mysqli_fetch_assoc($result);
if ($search['isActive']) {
$sql = <<<mutil
update user
set
isActive = 0
where
id = '$userId';
mutil;
} else {
$sql = <<<mutil
update user
set
isActive = 1
where
id = '$userId';
mutil;
}
if (mysqli_query($link, $sql)) {
echo "已成功";
} else {
echo "失敗";
}
}
function categorys()
{
$this->view("Backend/categorys");
}
function categoryCreate()
{
if($_SERVER['REQUEST_METHOD']=='GET') {
if(isset($_GET['Message'])){
echo $_GET['Message'];
}
return $this->view("Backend/categoryCreate");
}
$categoryName = $_POST['categoryName'];
// 資料庫連線參數
$link = include 'config.php';
$sql = <<<mutil
insert into category(
categoryName
)
values(
"$categoryName"
)
mutil;
mysqli_query($link, $sql);
return header("Location: http://localhost:8888/PID_Assignment/backend/categorys");
}
function categoryUpdate()
{
if($_SERVER['REQUEST_METHOD']=='GET') {
if(isset($_GET['Message'])){
echo $_GET['Message'];
}
return $this->view("Backend/categoryUpdate");
}
$categoryName = $_POST['categoryName'];
$categoryId = $_POST['categoryId'];
// 資料庫連線參數
$link = include 'config.php';
$sql = <<<mutil
update category
set
categoryName = "$categoryName"
where
id = '$categoryId';
mutil;
mysqli_query($link, $sql);
return header("Location: http://localhost:8888/PID_Assignment/backend/categorys");
}
function categoryDelete()
{
$categoryId = $_GET['categoryId'];
// 資料庫連線參數
$link = include 'config.php';
$sql = <<<mutil
DELETE FROM category
WHERE
id = "$categoryId";
mutil;
if (mysqli_query($link, $sql)) {
echo "刪除成功";
return header("Location: http://localhost:8888/PID_Assignment/backend/categorys");
} else {
echo "刪除失敗";
return header("Location: http://localhost:8888/PID_Assignment/backend/categorys");
}
}
function products()
{
$this->view("Backend/products");
}
function productCreate()
{
if($_SERVER['REQUEST_METHOD']=='GET') {
if(isset($_GET['Message'])){
echo $_GET['Message'];
}
return $this->view("Backend/productCreate");
}
$productName = $_POST['productName'];
$categoryId = $_POST['categoryId'];
$productPrice = $_POST['productPrice'];
$productDescription = $_POST['productDescription'];
$target_dir = "productImg/";
// 資料庫連線參數
$link = include 'config.php';
$sql = <<<mutil
insert into product(
productName, price, description, categoryId
)
values(
"$productName", "$productPrice", "$productDescription", "$categoryId"
)
mutil;
mysqli_query($link, $sql);
//取的剛新增資料的ID
$newID = mysqli_insert_id($link);
$sql = <<<mutil
UPDATE product
SET
picture = "$target_dir$newID.jpg"
where
id = "$newID";
mutil;
mysqli_query($link, $sql);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_dir . $newID . ".jpg");
return header("Location: http://localhost:8888/PID_Assignment/backend/products");
}
function productUpdate(){
if($_SERVER['REQUEST_METHOD']=='GET') {
if(isset($_GET['Message'])){
echo $_GET['Message'];
}
return $this->view("Backend/productUpdate");
}
// 資料庫連線參數
$link = include 'config.php';
$target_dir = "productImg/";
$sql = <<<mutil
UPDATE product
SET
productName = "$_POST[productName]",
price = "$_POST[productPrice]",
description = "$_POST[productDescription]",
categoryId = $_POST[categoryId]
where
id = "$_POST[productId]";
mutil;
echo $sql;
mysqli_query($link, $sql);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_dir . $_POST["productId"] . ".jpg");
return header("Location: http://localhost:8888/PID_Assignment/backend/products");
}
function productDelete(){
// 資料庫連線參數
$link = include 'config.php';
$productId = $_GET['productId'];
$sql = <<<mutil
delete from product where id = $productId
mutil;
mysqli_query($link, $sql);
return $this->view('Backend/products');
}
function order(){
$this->view("Backend/order");
}
function orders(){
$this->view("Backend/orders");
}
}
<file_sep><?php
$link = include 'config.php';
$sql = <<<mutil
select *, p.id from product as p inner join category as c on p.categoryId = c.id;
mutil;
$result = mysqli_query($link, $sql);
?>
<?php require_once('header.php'); ?>
<div style="padding-top:5.5em;" align="center">
<a href="http://localhost:8888/PID_Assignment/backend/productCreate" class="create">新增</a>
<table>
<tr>
<th>商品名稱</th><th>類別</th><th>價格</th><th>內容</th><th>刪除</th>
</tr>
<?php while ($row = mysqli_fetch_assoc($result)): ?>
<tr>
<td><a href="http://localhost:8888/PID_Assignment/backend/productUpdate?productId=<?php echo $row['id'] ?>" class="update"><?php echo $row['productName'] ?></a></td>
<td><?php echo $row['categoryName'] ?></td>
<td><?php echo $row['price'] ?></td>
<td><?php echo $row['description'] ?></td>
<td><a href="http://localhost:8888/PID_Assignment/backend/productDelete?productId=<?php echo $row['id'] ?>">刪除</a></td>
</tr>
<?php endwhile ?>
</table>
</div>
<?php require_once('views/store/footer.php'); ?><file_sep><?php
$link = include 'config.php';
$sql = <<<mutil
select *, p.id from product as p inner join category as c on p.categoryId = c.id;
mutil;
$result = mysqli_query($link, $sql);
?>
<script src='/PID_Assignment/js/jquery.min.js'></script>
<?php require_once('header.php'); ?>
<div class="wrap full-wrap">
<div class="main-wrap">
<section class="main main-archive">
<div class="loop">
<article class="post format-gallery post_format-post-format-gallery">
<a href="#" title="陰間條例 夜神篇">
<div class="part-gallery">
<div class="flexslider">
<ul class="slides">
<li><span class="post-image"><img width="502" height="502" src="/PID_Assignment/img/117960712_1478591842322708_5243812457812818534_o.jpg" alt="陰間條例 夜神篇" /></span></li>
<!-- <li><span class="post-image"><img width="502" height="502" src="/PID_Assignment/img/118076033_1485082471673645_778841976934694298_n.jpg" alt="Run-1" /></span></li>
<li><span class="post-image"><img width="502" height="502" src="/PID_Assignment/img/118398197_1483998731782019_4389253984520822273_o.jpg" alt="Run-2" /></span></li> -->
</ul>
</div>
</div>
</a>
<div class="inner">
<h2 class="entry-title">
<a href="#" title="陰間條例 夜神篇">
陰間條例 夜神篇 </a>
</h2>
<ul class="meta top">
<li class="time">
<a href="#" title="陰間條例 夜神篇">
<time class="post-date updated" datetime="2015-02-01">September 2, 2020</time>
</a></li>
<li class="comments post-tags">
<a href="#">1
Comments</a></li>
<li class="author-m post-tags">
By <span class="vcard author post-author"><span class="fn"><a href="#" title="Posts by <NAME>" rel="author">Ballfish</a></span></span>
</li>
</ul>
<div class="post-content">
<p>台灣第一款漫畫改編劇本殺於今天開始募資!
知名漫畫「陰間條例」帶你進入記憶碎片的夜神旅店中,特別的玩法、多種結局令你意想不到的劇情!</p>
</div>
</div>
</article>
</div>
</section>
<h1>桌上有戲</h1>
<div class="row">
<?php while ($row = mysqli_fetch_assoc($result)) : ?>
<div class="col-md-4">
<h3><?php echo $row['productName'] ?></h3>
<div>
<div class="pull-left">
<img src="../<?php echo $row['picture']?>" style="background-size: contain; width:200px; height:250px" border="0" title="<?php echo $row['productName'] ?>">
</div>
<div class="pull-left">
<h4><?php echo $row['price'] ?>$NTD</h4>
<input type="hidden" value="<?php echo $row['id']?>">
<div class="form-group">
<label>數量:</label>
<input type="number" value="1" class="form-control quantity">
</div>
<div class="form-group pull-right">
<butten class="btn btn-danger add-to-cart">
<i class="fa fa-shopping-cart">加入購物車</i>
</butten>
</div>
</div>
<div class="clearfix">
</div>
</div>
</div>
<?php endwhile ?>
</div>
</div><!-- /main-wrap -->
</div><!-- /wrap -->
<script>
$(".add-to-cart").on("click", function() {
$this = $(this);
$productId = $this.parent().prev().parent().children().next().first().val();
$quantity = $this.parent().parent().children().children().next().val();
console.log("http://localhost:8888/PID_Assignment/store/cartAdd?productId="+$productId + "&quantity=" + $quantity)
$.ajax({
type:"GET",
url:"http://localhost:8888/PID_Assignment/store/cartAdd?productId="+$productId + "&quantity=" + $quantity
})
.done(function (data) {
alert(data);
})
});
</script>
<?php require_once('footer.php'); ?><file_sep><?php
session_start();
$orderTotal;
$link = include 'config.php';
$sql = <<<mutil
select * from orders as o inner join cart as c on o.id = c.orderId and o.id = $_SESSION[orderId];
mutil;
$result = mysqli_query($link, $sql);
$order = mysqli_fetch_assoc($result);
$sql = <<<mutil
select *, c.id cartId from cart as c inner join product as p on c.productId = p.id and c.orderId = $_SESSION[orderId];
mutil;
$result = mysqli_query($link, $sql);
?>
<?php require_once('header.php'); ?>
<script src='/PID_Assignment/js/jquery.min.js'></script>
<div style="padding-top:10em;" align="center">
<table>
<tr>
<th>商品圖</th><th>商品名稱</th><th>商品名稱</th><th>數量</th><th>價格</th><th>小計</th>
</tr>
<?php while ($row = mysqli_fetch_assoc($result)): ?>
<?php $orderTotal+=$row['total'] ?>
<tr>
<td><img style="width:200px" src="../<?php echo $row['picture'] ?>"></td>
<td style="vertical-align: middle;text-align: center;"><?php echo $row['productName'] ?></td>
<td style="vertical-align: middle;text-align: center; width:20em;"><?php echo $row['description'] ?></td>
<td style="vertical-align: middle;text-align: center;"><?php echo $row['quantity'] ?></td>
<td style="vertical-align: middle;text-align: center;"><?php echo $row['price'] ?></td>
<td style="vertical-align: middle;text-align: center;"><?php echo $row['total'] ?></td>
</tr>
<?php endwhile ?>
<tr>
<td colspan="6" style="text-align:right;">總計:<?php echo $orderTotal ?></td>
</tr>
</table>
<br><br><br>
<form id="form1" name="form1" method="post" action="http://localhost:8888/PID_Assignment/store/pay">
<table width="300" border="0" align="center" cellpadding="5" cellspacing="0" bgcolor="#F2F2F2">
<tr>
<td width="100" align="center" valign="baseline">收件人姓名:</td>
<td valign="baseline"><input type="text" name="name" id="name" required="required"/></td>
</tr>
<tr>
<td width="80" align="center" valign="baseline">收件人信箱:</td>
<td valign="baseline"><input type="email" name="email" id="email" required="required"/></td>
</tr>
<tr>
<td width="80" align="center" valign="baseline">收件人地址:</td>
<td valign="baseline"><input type="text"" name="address" id="address" required="required"/></td>
</tr>
<tr>
<td colspan="2" align="center" bgcolor="#CCCCCC"><input type="submit" name="btnOK" id="btnOK" value="確認訂單" />
</td>
</tr>
</table>
</form>
<p>測試卡號:4311-9522-2222-2222 </p>
<p>安全密碼:222</p>
<p>有效日期:今日之後即可</p>
</div>
<?php
$sql = <<<mutil
update orders
set
total = $orderTotal
where
id = $_SESSION[orderId]
mutil;
mysqli_query($link, $sql);
?>
<?php require_once('footer.php'); ?>
<file_sep><?php
session_start();
$orderTotal;
$link = include 'config.php';
$sql = <<<mutil
select * from orders as o inner join cart as c on o.id = c.orderId and o.id = $_GET[orderId];
mutil;
$result = mysqli_query($link, $sql);
$order = mysqli_fetch_assoc($result);
$sql = <<<mutil
select *, c.id cartId from cart as c inner join product as p on c.productId = p.id and c.orderId = $_GET[orderId];
mutil;
$result = mysqli_query($link, $sql);
?>
<?php require_once('header.php'); ?>
<script src='/PID_Assignment/js/jquery.min.js'></script>
<div style="padding-top:10em;" align="center">
<table>
<tr>
<th>商品圖</th><th>商品名稱</th><th>商品描述</th><th>數量</th><th>價格</th><th>小計</th>
</tr>
<?php while ($row = mysqli_fetch_assoc($result)): ?>
<?php $orderTotal+=$row['total'] ?>
<tr>
<td><img style="width:200px" src="../<?php echo $row['picture'] ?>"></td>
<td style="vertical-align: middle;text-align: center;"><?php echo $row['productName'] ?></td>
<td style="vertical-align: middle;text-align: center; width:20em;"><?php echo $row['description'] ?></td>
<td style="vertical-align: middle;text-align: center;"><?php echo $row['quantity'] ?></td>
<td style="vertical-align: middle;text-align: center;"><?php echo $row['price'] ?></td>
<td style="vertical-align: middle;text-align: center;"><?php echo $row['total'] ?></td>
</tr>
<?php endwhile ?>
<tr>
<td colspan="6" style="text-align:right;">總計:<?php echo $orderTotal ?></td>
</tr>
</table>
</div>
<?php require_once('footer.php'); ?>
<file_sep><?php
session_start();
if(isset($_SESSION['userId'])){
$link = include 'config.php';
//是否有未結帳訂單,如無則新增新訂單
$sql = <<<mutil
select * from orders where userId = "$_SESSION[userId]" and done = false;
mutil;
$result = mysqli_query($link, $sql);
$order = mysqli_fetch_assoc($result);
if ($order == Null){
$sql = <<<mutil
insert into orders(total, userId, done)
values(0, "$_SESSION[userId]", false);
mutil;
$result = mysqli_query($link, $sql);
$order = mysqli_fetch_assoc($result);
$_SESSION['orderId'] = $order['id'];
}else{
$_SESSION['orderId'] = $order['id'];
}
}
require_once 'core/App.php';
require_once 'core/Controller.php';
$app = new App();
?><file_sep><?php
class UserController extends Controller
{
function index()
{
$this->view("User/login");
}
function login(){
session_start();
if($_SERVER['REQUEST_METHOD']=='GET') {
if(isset($_GET['Message'])){
echo $_GET['Message'];
}
return $this->view("User/login");
}
//POST
$accountName = $_POST['accountName'];
$passwd = $_POST['passwd'];
$link = include 'config.php';
$sql = <<<mutil
select * from user where accountName = "$accountName";
mutil;
$result = mysqli_query($link, $sql);
$user = mysqli_fetch_assoc($result);
if ($user == Null){
$Message = "查無此用戶";
return header("Location: http://localhost:8888/PID_Assignment/user/login?Message=".$Message);
}
elseif(!password_verify($passwd, $user['passwd'])){
$Message = "密碼錯誤";
return header("Location: http://localhost:8888/PID_Assignment/user/login?Message=".$Message);
}elseif(!$user['isActive']){
$Message = "會員已停用";
return header("Location: http://localhost:8888/PID_Assignment/user/login?Message=".$Message);
}
$_SESSION['userId'] = $user['id'];
$Message = "親愛的用戶$search[userName]" . "你好";
if ($user['role'] == "管理者"){
return $this->view("Backend/index");
}else{
return $this->view("Store/index");
}
}
function logout(){
session_start();
session_destroy();
$Message = "歡迎下次購物";
return header("Location: http://localhost:8888/PID_Assignment/store?Message=".$Message);
}
function register(){
if($_SERVER['REQUEST_METHOD']=='GET') {
if(isset($_GET['Message'])){
echo $_GET['Message'];
}
return $this->view("User/register");
}
//POST
$userName = $_POST['userName'];
$passwd = password_hash($_POST['passwd'], PASSWORD_DEFAULT);
$accountName = $_POST['accountName'];
// 資料庫連線參數
$link = include 'config.php';
$sql = <<<mutil
insert into user(
accountName, userName, passwd, role
)
values(
"$accountName", "$userName", "$passwd", "會員"
)
mutil;
if (mysqli_query($link, $sql)){
return header("Location: http://localhost:8888/PID_Assignment/store/");
}else{
$Message = "帳號或信箱重複";
return header("Location: http://localhost:8888/PID_Assignment/user/register?Message=".$Message);
}
}
//填充程式
function admin(){
$link = include 'config.php';
$passwd = password_hash("<PASSWORD>", PASSWORD_DEFAULT);
$sql = <<<mutil
insert into user(
accountName, userName, passwd, role
)
values(
"admin", "球魚", "$passwd", "管理者"
)
mutil;
mysqli_query($link, $sql);
return header("Location: http://localhost:8888/PID_Assignment/store/");
}
}
?><file_sep><?php
$link = include 'config.php';
$sql = <<<mutil
select *, o.id from orders as o inner join user as u on o.userId = u.id where o.done = True;
mutil;
$result = mysqli_query($link, $sql);
?>
<?php require_once('header.php'); ?>
<script src='/PID_Assignment/js/jquery.min.js'></script>
<div style="padding-top:5.5em;" align="center">
<table>
<tr>
<th>訂單編號</th><th>會員名稱</th><th>會員級別</th><th>結帳日期</th><th>總額</th>
</tr>
<?php while ($row = mysqli_fetch_assoc($result)): ?>
<tr>
<td><a href="http://localhost:8888/PID_Assignment/store/order?orderId=<?php echo $row['id'] ?>"><?php echo $row['id'] ?></a></td>
<td><?php echo $row['userName'] ?></td>
<td><?php echo $row['role'] ?></td>
<td><?php echo $row['date'] ?></td>
<td><?php echo $row['total'] ?></td>
</tr>
<?php endwhile ?>
</table>
</div>
<?php require_once('views/store/footer.php'); ?><file_sep><?php
$link = include 'config.php';
$sql = <<<mutil
select * from product;
mutil;
$result = mysqli_query($link, $sql);
?>
<?php require_once('header.php'); ?>
<div style="padding-top:5.5em;" align="center">
<form id="form1" name="form1" method="post" action="http://localhost:8888/PID_Assignment/backend/categoryUpdate">
<input type="hidden" name="categoryId" id="categoryId" value="<?php echo $_GET['categoryId']?>" required="required"/>
<table width="300" border="0" align="center" cellpadding="5" cellspacing="0" bgcolor="#F2F2F2">
<tr>
<td width="80" align="center" valign="baseline">類別名稱</td>
<td valign="baseline"><input type="text" name="categoryName" id="categoryName" required="required"/></td>
</tr>
<tr>
<td colspan="2" align="center" bgcolor="#CCCCCC"><input type="submit" name="btnOK" id="btnOK" value="確認" />
<a href="http://localhost:8888/PID_Assignment/backend/categorys" class="cancel">取消</a>
</td>
</tr>
</table>
</form>
</div>
<?php require_once('views/store/footer.php'); ?><file_sep><?php
$link = include 'config.php';
$sql = <<<mutil
select * from orders where userId = $_SESSION[userId] and done = True;
mutil;
$result = mysqli_query($link, $sql);
?>
<?php require_once('header.php'); ?>
<div style="padding-top:8em;" align="center">
<table>
<tr>
<th>編號</th><th>日期</th><th>總額</th>
</tr>
<?php while ($row = mysqli_fetch_assoc($result)): ?>
<tr>
<td><a href="http://localhost:8888/PID_Assignment/store/order?orderId=<?php echo $row['id'] ?>"><?php echo $row['id'] ?></a></td>
<td><?php echo $row['date'] ?></td>
<td><?php echo $row['total'] ?></td>
</tr>
<?php endwhile ?>
</table>
</div>
<?php require_once('footer.php'); ?><file_sep><?php
$link = include 'config.php';
$sql = <<<mutil
select * from category;
mutil;
$result = mysqli_query($link, $sql);
?>
<?php require_once('header.php'); ?>
<div style="padding-top:5.5em;" align="center">
<a href="http://localhost:8888/PID_Assignment/backend/categoryCreate" class="create">新增</a>
<table>
<tr>
<th>類別名稱</th><th>刪除</th>
</tr>
<?php while ($row = mysqli_fetch_assoc($result)): ?>
<tr>
<td><a href="http://localhost:8888/PID_Assignment/backend/categoryUpdate?categoryId=<?php echo $row['id']?>" class="update"><?php echo $row['categoryName'] ?></a></td>
<td><a href="http://localhost:8888/PID_Assignment/backend/categoryDelete?categoryId=<?php echo $row['id']?>" class="cancel">刪除</a></td>
</tr>
<?php endwhile ?>
</table>
</div>
<?php require_once('views/store/footer.php'); ?><file_sep><?php require_once('views/store/header.php'); ?>
<div style="padding-top:8em;" align="center">
<form id="form1" name="form1" method="post" action="http://localhost:8888/PID_Assignment/user/login">
<table width="300" border="0" align="center" cellpadding="5" cellspacing="0" bgcolor="#F2F2F2">
<tr>
<td width="80" align="center" valign="baseline">帳號</td>
<td valign="baseline"><input type="text" name="accountName" id="accountName" required="required"/></td>
</tr>
<tr>
<td width="80" align="center" valign="baseline">密碼</td>
<td valign="baseline"><input type="<PASSWORD>" name="passwd" id="passwd" required="required"/></td>
</tr>
<tr>
<td colspan="2" align="center" bgcolor="#CCCCCC"><input type="submit" name="btnOK" id="btnOK" value="登入" />
</td>
</tr>
</table>
</form>
</div>
<?php require_once('views/store/footer.php'); ?><file_sep><?php require_once('header.php'); ?>
<div style="padding-top:5.5em;" align="center">
這是後台(報表預定位子),施工中
</div>
<?php require_once('views/store/footer.php'); ?><file_sep><!doctype html>
<!--
Itsy by FreeHTML5.co
Twitter: https://twitter.com/fh5co
Facebook: https://fb.com/fh5co
URL: https://freehtml5.co
-->
<html class="home blog no-js" lang="en-US">
<head>
<title>阿魚桌遊店</title>
<meta charset="UTF-8"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/cosmo/bootstrap.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
type="text/css" media="all"/>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Amatic+SC%3A400%2C700%7CLato%3A400%2C700%2C400italic%2C700italic&ver=4.9.8"
type="text/css" media="screen"/>
<link rel="stylesheet" href="/PID_Assignment/css/style.css" type="text/css" media="screen"/>
<link rel="stylesheet" href="/PID_Assignment/css/print.css" type="text/css" media="print"/>
<!--[if (lt IE 9) & (!IEMobile)]>
<link rel="stylesheet" id="lt-ie9-css" href="ie.css" type="text/css" media="screen"/>
<![endif]-->
<script src='/PID_Assignment/js/jquery-3.0.0.min.js'></script>
<script src='/PID_Assignment/js/jquery-migrate-3.0.1.min.js'></script>
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body class="home sticky-menu sidebar-off" id="top">
<header class="header">
<div class="header-wrap">
<div class="logo plain logo-left">
<div class="site-title">
<a href="http://localhost:8888/PID_Assignment/store/" title="Go to Home">阿魚桌遊店</a>
</div>
</div><!-- /logo -->
<nav id="nav" role="navigation">
<div class="table">
<div class="table-cell">
<ul id="menu-menu-1">
<li class="menu-item">
<a href="http://localhost:8888/PID_Assignment/store/">首頁</a></li>
<li class="menu-item">
<a href="http://localhost:8888/PID_Assignment/store/carts">購物車</a></li>
<li class="menu-item">
<a href="http://localhost:8888/PID_Assignment/store/orders">訂單</a></li>
<li class="menu-item">
<a href="http://localhost:8888/PID_Assignment/user/register">註冊</a></li>
<?php
session_start();
if(isset($_SESSION['userId'])){
echo("<li class='menu-item'>
<a href='http://localhost:8888/PID_Assignment/user/logout'>登出</a></li>");
}else{
echo("<li class='menu-item'>
<a href='http://localhost:8888/PID_Assignment/user/login'>登入</a></li>");
}
?>
<li class="menu-inline menu-item">
<a title="Facebook" href="https://www.facebook.com/tbgm0906311158">
<i class="fa fa-facebook"></i><span class="i">Facebook</span>
</a></li>
<li class="menu-inline menu-item">
<a title="Instagram" href="https://www.instagram.com/tbgm.service/">
<i class="fa fa-instagram"></i><span class="i">Instagram</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
<a href="#nav" class="menu-trigger"><i class="fa fa-bars"></i></a>
<a href="#topsearch" class="search-trigger"><i class="fa fa-search"></i></a>
</div>
</header> | 1e9a7c6935d249f598802c3bf623e1e98c8ccb30 | [
"PHP"
]
| 17 | PHP | ballfish30/PID_Assignment | 472e5e52f74ac649370ddfc07c55b682fb916fcb | 92b3b340719ae67eeac1f622813a55a3b9250901 |
refs/heads/master | <file_sep>namespace ConsoleApplication1
{
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Wellhub;
class Program
{
const string END_PT = "https://oilhub.documents.azure.com:443/";
const string AUTH_KEY = "<KEY>;
const string DB_NAME = "wellHubTest";
const string COLL_NAME = "whMessages";
const string COLL_ID = "dbs/EPNLAA==/colls/EPNLAOgLWAA=/";
public static void Main(string[] args)
{
try
{
TestConstructors();
//RunAddDocAsync();
//RunDelDocAsync();
//RunDelBatchAsync();
//RunAddBatchAsync();
//RunGetDocByID();
//RunGetDocFeedAsync();
//RunReplaceDocAsync();
//RunReplaceBatchAsync();
}
catch (Exception)
{
throw;
}
}
//private static async Task RunDelBatchAsync()
//{
// try
// {
// DocHandler handler = new DocHandler();
// string[] batch =
// { "6f654eb7-569c-4de9-95c6-0bda12417f4b",
// "84424d92-a98e-4a36-9cfc-cfa8a9a8d43b",
// "2e6dbab8-cbce-4643-8fdc-9d7ca9ba2bbe",
// "605e8af8-67f6-41e9-a04a-50d871e18cb7",
// "e4346009-05a4-4852-85fc-371cab3ca39e",
// "674995f0-a42e-4d24-8f66-2304e4a20385"
// };
// Task<List<WHResponse>> taskTest = handler.DeleteBatchAsync(batch.ToList());
// Task.WaitAll(taskTest);
// List<WHResponse> retInt = taskTest.Result;
// }
// catch (Exception)
// {
// throw;
// }
//}
//private static async Task RunDelDocAsync()
//{
// try
// {
// DocHandler handler = new DocHandler();
// Task<WHResponse> taskTest = handler.DeleteDocAsync("f80aa2b3-40fc-4725-b9cf-68f46ad819ab");
// Task.WaitAll(taskTest);
// WHResponse retObj = taskTest.Result;
// }
// catch (Exception)
// {
// throw;
// }
//}
private static void TestConstructors()
{
//open with ID, should succeed
DocHandler handler = new DocHandler(new Uri(END_PT), AUTH_KEY, COLL_ID);
handler.Dispose();
handler = null;
//open with name, should succeed
handler = new DocHandler(new Uri(END_PT), AUTH_KEY, DB_NAME, COLL_NAME);
handler.Dispose();
handler = null;
try
{
//open with bad end point, should fail
handler = new DocHandler(new Uri("http://www.google.com"), AUTH_KEY, DB_NAME, COLL_NAME);
}
catch (Exception)
{
handler = null;
}
try
{
//open with blank authkey, should fail
handler = new DocHandler(new Uri(END_PT), "", DB_NAME, COLL_NAME);
}
catch (Exception)
{
handler = null;
}
try
{
//open with bad authkey, should fail
handler = new DocHandler(new Uri(END_PT), string.Concat(AUTH_KEY,"x"), DB_NAME, COLL_NAME);
}
catch (Exception)
{
handler = null;
}
try
{
//open with bad dbname, should fail
handler = new DocHandler(new Uri(END_PT), AUTH_KEY, string.Concat(DB_NAME,"x"), COLL_NAME);
}
catch (Exception)
{
handler = null;
}
try
{
//open with blank dbname, should fail
handler = new DocHandler(new Uri(END_PT), AUTH_KEY, "", COLL_NAME);
}
catch (Exception)
{
handler = null;
}
try
{
//open with bad collection name, should fail
handler = new DocHandler(new Uri(END_PT), AUTH_KEY, DB_NAME, string.Concat(COLL_NAME, "x"));
}
catch (Exception)
{
handler = null;
}
try
{
//open with blank collection name, should fail
handler = new DocHandler(new Uri(END_PT), AUTH_KEY, DB_NAME, "");
}
catch (Exception)
{
handler = null;
}
try
{
//open with bad collection id, should fail
handler = new DocHandler(new Uri(END_PT), AUTH_KEY, string.Concat(COLL_ID,"x"));
}
catch (Exception)
{
handler = null;
}
try
{
//open with blank collection id, should fail
handler = new DocHandler(new Uri(END_PT), AUTH_KEY, "");
}
catch (Exception)
{
handler = null;
}
}
private static async Task RunAddDocAsync()
{
try
{
//POCO test
dynamic docDB = new
{
teststring1 = "AddDocAsync POCO testing",
teststring2 = DateTime.Now.ToUniversalTime()
};
DocHandler handler = new DocHandler(new Uri(END_PT), AUTH_KEY, COLL_ID);
Task <WHResponse> taskTest = handler.AddDocAsync(docDB);
Task.WaitAll(taskTest);
WHResponse respObj = taskTest.Result;
//string test
string strJson = string.Concat("{ 'AddDocAsync string testing' : '", DateTime.Now, "'}");
taskTest = handler.AddDocAsync(strJson);
Task.WaitAll(taskTest);
respObj = taskTest.Result;
//string test - fails - empty string
strJson = "{ }";
taskTest = handler.AddDocAsync(strJson);
Task.WaitAll(taskTest);
respObj = taskTest.Result;
//document test
strJson = string.Concat("{ 'AddDocAsync document testing' : '", DateTime.Now, "'}");
Document doc = new Document();
doc.LoadFrom(new JsonTextReader(new StringReader(strJson)));
taskTest = handler.AddDocAsync(doc);
Task.WaitAll(taskTest);
respObj = taskTest.Result;
//jobject test
strJson = string.Concat("{ 'AddDocAsync jobject testing' : '", DateTime.Now, "'}");
JObject jObj = JObject.Parse(strJson);
taskTest = handler.AddDocAsync(jObj);
Task.WaitAll(taskTest);
respObj = taskTest.Result;
//xml document test
XmlDocument docXML = new XmlDocument();
docXML.InnerXml = string.Concat("<testroot><firstField>XML doc test</firstField><secondField>", DateTime.Now, "</secondField></testroot>");
taskTest = handler.AddDocAsync(docXML);
Task.WaitAll(taskTest);
respObj = taskTest.Result;
//xml string test
string strXml = string.Concat("<testroot><firstField>XML string test</firstField><secondField>", DateTime.Now, "</secondField></testroot>");
taskTest = handler.AddDocAsync(strXml);
Task.WaitAll(taskTest);
respObj = taskTest.Result;
//xml string test - fails - bad xml
strXml = string.Concat("<testroot><firstField>XML string test<firstField><secondField>", DateTime.Now, "</secondField></testroot>");
taskTest = handler.AddDocAsync(strXml);
Task.WaitAll(taskTest);
respObj = taskTest.Result;
//POCO test - fails - duplicate ID
docDB = new
{
id = "94a23e36-8xyz-45ce-9189-8624e7e174b9",
teststring1 = "AddDocAsync POCO testing - fails",
teststring2 = DateTime.Now.ToUniversalTime()
};
taskTest = handler.AddDocAsync(docDB);
Task.WaitAll(taskTest);
respObj = taskTest.Result;
}
catch (Exception)
{
throw;
}
}
//private static async Task RunAddBatchAsync()
//{
// try
// {
// //POCO test
// var docsDB = new List<object>();
// docsDB.Add(new
// {
// teststring1 = "AddBatchAsync POCO testing obj1",
// teststring2 = DateTime.Now
// });
// docsDB.Add(new
// {
// teststring1 = "AddBatchAsync POCO testing obj2",
// teststring2 = DateTime.Now
// });
// DocHandler handler = new DocHandler();
// Task<List<WHResponse>> taskTest = handler.AddBatchAsync(docsDB);
// Task.WaitAll(taskTest);
// List<WHResponse> respList = taskTest.Result;
// //string test
// List<string> listJson = new List<string>();
// listJson.Add("{ }");
// listJson.Add(string.Concat("{ 'AddBatchAsync string testing 1' : '", DateTime.Now, "'}"));
// listJson.Add(string.Concat("{ 'AddBatchAsync string testing 2' : '", DateTime.Now, "'}"));
// listJson.Add(string.Concat("{ 'AddBatchAsync string testing 3' : '", DateTime.Now, "'}"));
// taskTest = handler.AddBatchAsync(listJson);
// Task.WaitAll(taskTest);
// respList = taskTest.Result;
// ////document test
// //strJson = string.Concat("{ 'AddDocAsync document testing' : '", DateTime.Now, "'}");
// //Document doc = new Document();
// //doc.LoadFrom(new JsonTextReader(new StringReader(strJson)));
// //taskTest = handler.AddDocAsync(doc);
// //Task.WaitAll(taskTest);
// //respList = taskTest.Result;
// ////jobject test
// //strJson = string.Concat("{ 'AddDocAsync jobject testing' : '", DateTime.Now, "'}");
// //JObject jObj = JObject.Parse(strJson);
// //taskTest = handler.AddDocAsync(jObj);
// //Task.WaitAll(taskTest);
// //respList = taskTest.Result;
// ////xml document test
// //XmlDocument docXML = new XmlDocument();
// //docXML.InnerXml = string.Concat("<testroot><firstField>XML doc test</firstField><secondField>", DateTime.Now, "</secondField></testroot>");
// //taskTest = handler.AddDocAsync(docXML);
// //Task.WaitAll(taskTest);
// //respList = taskTest.Result;
// //// stream test
// //docXML.GetElementsByTagName("firstField").Item(0).InnerText = "Streaming test";
// //docXML.GetElementsByTagName("secondField").Item(0).InnerText = DateTime.Now;
// //MemoryStream testStream = new MemoryStream();
// //docXML.Save(testStream);
// //taskTest = handler.AddDocAsync(testStream);
// //Task.WaitAll(taskTest);
// //respList = taskTest.Result;
// ////xml string test
// //string strXml = string.Concat("<testroot><firstField>XML string test</firstField><secondField>", DateTime.Now, "</secondField></testroot>");
// //taskTest = handler.AddDocAsync(strXml);
// //Task.WaitAll(taskTest);
// //respList = taskTest.Result;
// }
// catch (Exception)
// {
// throw;
// }
//}
//private static void RunGetDocByID()
//{
// DocHandler handler = new DocHandler();
// WHResponse respObj = handler.GetDocByID("94a23e36-8ba1-45ce-9189-8624e7e174b9");
// respObj = handler.GetDocByID("94a23e36-8ba1-45ce-9189-8624e7e174b9", DocHandler.ReturnType.XMLstring);
//}
//private static void RunGetDocFeedAsync()
//{
// DocHandler handler = new DocHandler();
// Task<WHResponse> taskTest = handler.GetDocsAsync("SELECT * FROM Docs d WHERE d.id !='94a23e36-8ba1-45ce-9189-8624e7e174b9'",DocHandler.ReturnType.JSONstring, 20);
// Task.WaitAll(taskTest);
// WHResponse respObj = taskTest.Result;
// taskTest = handler.GetDocsAsync("SELECT * FROM Docs d WHERE d.id !='674995f0-a42e-4d24-8f66-2304e4a20385'", DocHandler.ReturnType.XMLstring, 5);
// Task.WaitAll(taskTest);
// respObj = taskTest.Result;
// taskTest = handler.GetDocsAsync("SELECT * FROM Docs d WHERE d.id !='674995f0-a42e-4d24-8f66-2304e4a20385'", DocHandler.ReturnType.XMLstring, 8, null, respObj.Continuation);
// Task.WaitAll(taskTest);
// respObj = taskTest.Result;
// Expression<Func<Document, bool>> lambdaExp = d => d.Id == "674995f0-a42e-4d24-8f66-2304e4a20385";
// taskTest = handler.GetDocsAsync(lambdaExp, DocHandler.ReturnType.XMLstring, 3, null, respObj.Continuation);
// Task.WaitAll(taskTest);
// respObj = taskTest.Result;
//}
//private static void RunReplaceDocAsync()
//{
// //regular replace
// DocHandler handler = new DocHandler();
// string savedID = "94a23e36-8xyz-45ce-9189-8624e7e174b9";
// WHResponse respObj = handler.GetDocByID(savedID);
// JObject code = JObject.Parse(respObj.Return);
// code["checking3"] = DateTime.Now;
// Task<WHResponse> taskTest = handler.ReplaceDocAsync(code, respObj.Link);
// Task.WaitAll(taskTest);
// respObj = taskTest.Result;
// //replace with no self-id - fails because document is not type Document //where is not found error?
// code["checking3"] = DateTime.Now;
// taskTest = handler.ReplaceDocAsync(code);
// Task.WaitAll(taskTest);
// respObj = taskTest.Result;
// //no self-id - succeeds because document is type Document
// code["checking3"] = DateTime.Now;
// Document newDoc = code.ToObject<Document>();
// taskTest = handler.ReplaceDocAsync(newDoc);
// Task.WaitAll(taskTest);
// respObj = taskTest.Result;
// //replace with conflict - should fail - id is taken by another document
// code["checking3"] = 111;
// code["id"] = "ead28a30-7104-47c5-8691-eef70dad61f2";
// taskTest = handler.ReplaceDocAsync(code, respObj.Link);
// Task.WaitAll(taskTest);
// respObj = taskTest.Result;
// //replace with bad selfID - should fail for document not found
// code["id"] = savedID;
// taskTest = handler.ReplaceDocAsync(code, "dbs/EPNLAA==/colls/EPNLAOgLWAA=/docs/EPNLAOgLWAAHAAAAAAAAAA=6/");
// Task.WaitAll(taskTest);
// respObj = taskTest.Result;
//}
//private static void RunReplaceBatchAsync()
//{
// //regular replace
// DocHandler handler = new DocHandler();
// List<Document> newDocs = new List<Document>();
// string savedID = "a012d1c9-398a-48da-95a7-d3f5f94e4d69";
// WHResponse respObj = handler.GetDocByID(savedID);
// JObject code = JObject.Parse(respObj.Return);
// code["replbatch"] = DateTime.Now;
// newDocs.Add(code.ToObject<Document>());
// savedID = "8324db59-dbce-4804-b0af-3f774551c35a";
// respObj = handler.GetDocByID(savedID);
// code = JObject.Parse(respObj.Return);
// code["replbatch"] = DateTime.Now;
// newDocs.Add(code.ToObject<Document>());
// savedID = "21ad3b66-d3ec-4204-8617-c03ddb0ded31";
// respObj = handler.GetDocByID(savedID);
// code = JObject.Parse(respObj.Return);
// code["replbatch"] = DateTime.Now;
// newDocs.Add(code.ToObject<Document>());
// code["id"] = "ead28a30-7104-47c5-8691-eef70dad61f2"; //should fail
// newDocs.Add(code.ToObject<Document>());
// Task<List<WHResponse>> taskTest = handler.ReplaceBatchAsync(newDocs);
// Task.WaitAll(taskTest);
// List<WHResponse> respList = taskTest.Result;
//}
//private void CreateTrigger()
//{
// DocHandler handler = new DocHandler();
// DocumentClient client = handler.Client;
// // 1. Create a trigger.
// string triggerId = "CanonicalizeSchedule";
// string body = File.ReadAllText(@"JS\CanonicalizeSchedule.js");
// Trigger trigger = new Trigger
// {
// Id = triggerId,
// Body = body,
// TriggerOperation = TriggerOperation.Create,
// TriggerType = TriggerType.Pre
// };
// //await TryDeleteStoredProcedure(colSelfLink, trigger.Id);
// Task<WHResponse> taskTest = client.CreateTriggerAsync(colSelfLink, trigger);
// Task.WaitAll(taskTest);
// WHResponse respObj = taskTest.Result;
//}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq.Expressions;
using System.Xml;
namespace Wellhub
{
/// <summary>
/// Class for interacting with Azure DocumentDB. Service endpoint and authorization key for the database must be set in the Azure app.
/// Collection can be passed as parameter or the class will use the default from the configuration file.
/// </summary>
public class DocHandler
{
#region Constants and Variables
//root node added to json to convert to well-formed XML with namespace
const string JSON_ROOT = "{'?xml': {'@version': '1.0','@standalone': 'no'}, 'whResponse' : { '@xmlns' : 'http://well-hub.com', 'whDocument' :";
//WHResponse messages
const string BAD_QUERY = "The query could not be executed as written. ";
const string DOC_NULL = "The document to be added is empty. ";
const string BAD_STRING = "Invalid string passed, will not serialize to JSON or XML. Raw string should be JSON or XML syntax.";
const string BAD_COLL_ID = "Cannot open document collection with collection ID given: ";
const string EMPTY_ID = "The request did not specify a document ID. ";
const string DOC_ERR_MSG = "The Document Client could not be created from stored credentials. ";
const string CREDENTIAL_MSG = "Endpoint, authorization key and either collection selfID or database and collection names must be specified. ";
const string AGG_ERR_MSG = " Errors Occurred. ";
const string STAT_TEXT = ", StatusCode: ";
const string ACT_TEXT = ", Activity id: ";
const string ERR_TYPE = "Error type: ";
const string MSG_TEXT = ", Message: ";
const string BASE_MSG_TEXT = ", BaseMessage: ";
const string CONFLICT_MSG = "There is already a document in the database with this ID but a different SelfID. ";
const string NOTFOUND_MSG = "There is no document with the specified SelfID. ";
const string NO_SELF_ID = "The SelfID cannot be blank unless the replacement object is a Document with a SelfID set in the SelfID property. ";
const string DB_INVALID = "The database specified does not exist or could not be opened with the credentials submitted. ";
const string COLL_INVALID = "The collection specified does not exist or could not be opened with the credentials submitted. ";
//Other constants
const string CONFLICT_TEXT = "conflict";
const string NOTFOUND_TEXT = "notfound";
const string EMPTY_DOC = "{}";
//variables used throughout program
private static Uri endPt; //azure endpoint for DocDB database
private static string authKey; //azure authorization key for DocDB database
private static string collID; //collection selfID
private static string dbName; //database name if collection selfID is not passed
private static string collName; //collection name if collection selfID is not passed
private static DocumentClient client; //document client - created once per instance for performance
#endregion
#region Constructor and Class Properties
/// <summary>
/// Returns the collection SelfID. Must be set in the constructor directly or using the database and collection names.
/// </summary>
public static string CollectionID { get { return collID; } }
/// <summary>
/// Returns the DocumentDB endpoint. Must be set in the constructor.
/// </summary>
public static Uri EndPoint { get { return endPt; } }
/// <summary>
/// Returns the DocumentDB authorization key. Must be set in the constructor.
/// </summary>
public static string AuthorizationKey { get { return authKey; } }
/// <summary>
/// Returns the DocumentDB database name. Can be set in the constructor. Not required or populated if collection selfID is used in constructor.
/// </summary>
public static string DBName { get { return dbName; } }
/// <summary>
/// Returns the DocumentDB collection name. Can be set in the constructor. Not required or populated if collection selfID is used in constructor.
/// </summary>
public static string CollectionName { get { return collName; } }
private static DocumentClient Client
{
get
{
//if there is no client yet
if (client == null)
{
try
{
// create an instance of DocumentClient from from settings in config file
client = new DocumentClient(EndPoint, AuthorizationKey,
new ConnectionPolicy
{
ConnectionMode = ConnectionMode.Direct,
ConnectionProtocol = Protocol.Tcp
});
//explicitly open for performance improvement
client.OpenAsync();
}
catch (DocumentClientException docEx)
{
// get base exception
Exception baseException = docEx.GetBaseException();
// create application exception
ApplicationException appEx = new ApplicationException(string.Concat(DOC_ERR_MSG, STAT_TEXT, docEx.StatusCode,
ACT_TEXT, docEx.ActivityId, MSG_TEXT, docEx.Message, BASE_MSG_TEXT, baseException.Message), baseException);
//throw the error
throw appEx;
}
catch (AggregateException aggEx)
{
// create error message
var msg = string.Concat(aggEx.InnerExceptions.Count, AGG_ERR_MSG);
// for each exception
foreach (var ex in aggEx.InnerExceptions)
{
// try casting as document client exception
DocumentClientException docEx = ex as DocumentClientException;
// if success
if (docEx != null)
{
// append document client message
msg = string.Concat(msg, "[", DOC_ERR_MSG, STAT_TEXT, docEx.StatusCode,
ACT_TEXT, docEx.ActivityId, MSG_TEXT, docEx.Message, BASE_MSG_TEXT, ex.GetBaseException().Message, "]");
}
else
{
//append other message
msg = string.Concat(msg, "[", ERR_TYPE, ex.GetType(), MSG_TEXT, docEx.Message, "]");
}
}
//throw the error
throw new ApplicationException(msg, aggEx);
}
catch (Exception ex)
{
//throw the error
throw new ApplicationException(string.Concat(ERR_TYPE, ex.GetType(), MSG_TEXT, ex.Message), ex);
}
}
return client;
}
}
static void Main(string[] args) { }
/// <summary>
/// Creates an object for interacting with Azure DocumentDB.
/// </summary>
/// <param name="endPoint">The endpoint of the Azure DocumentDB. </param>
/// <param name="authorizationKey">The authorization key of the Azure DocumentDB. </param>
/// <param name="collSelfId">SelfID of the DocDB Collection to use for interaction. </param>
public DocHandler(Uri endPoint, string authorizationKey, string collSelfId)
{
//if endpoint, authkey or collectionID not specified throw an error
if (string.IsNullOrEmpty(authorizationKey) | string.IsNullOrEmpty(collSelfId) | endPoint == null)
{
throw new ApplicationException(CREDENTIAL_MSG);
}
else
{
// set properties from parameters
endPt = endPoint;
authKey = authorizationKey;
collID = collSelfId;
try
{
//initialize client
DocumentClient testClient = Client;
//validate collection id
Task<ResourceResponse<DocumentCollection>> coll = Client.ReadDocumentCollectionAsync(collID);
Task.WaitAll(coll);
if (coll.Status != TaskStatus.RanToCompletion)
{
throw new ApplicationException(COLL_INVALID);
}
}
catch (Exception)
{
//remove settings and throw any exception encountered
Dispose();
throw;
}
}
}
/// <summary>
/// Creates an object for interacting with Azure DocumentDB.
/// </summary>
/// <param name="endPoint">The endpoint of the Azure DocumentDB. </param>
/// <param name="authorizationKey">The authorization key of the Azure DocumentDB. </param>
/// <param name="databaseName">Name of the DocDB database to use for interaction. </param>
/// <param name="collectionName">Name of the collection in the DocDB database to use for interaction. </param>
public DocHandler(Uri endPoint, string authorizationKey, string databaseName, string collectionName)
{
//if endpoint, authkey or collectionID not specified throw an error
if (string.IsNullOrEmpty(authorizationKey) | string.IsNullOrEmpty(databaseName) | string.IsNullOrEmpty(collectionName) | endPoint == null)
{
throw new ApplicationException(CREDENTIAL_MSG);
}
else
{
// set properties from parameters
endPt = endPoint;
authKey = authorizationKey;
dbName = databaseName;
collName = collectionName;
try
{
//get the database
Database db = Client.CreateDatabaseQuery().Where(d => d.Id == databaseName).ToArray().FirstOrDefault();
if (db == null)
{
throw new ApplicationException(DB_INVALID);
}
else
{
DocumentCollection coll = Client.CreateDocumentCollectionQuery(db.SelfLink).Where(c => c.Id == collectionName).ToArray().FirstOrDefault();
if (coll == null)
{
throw new ApplicationException(COLL_INVALID);
}
else
{
collID = coll.SelfLink;
}
}
}
catch (Exception)
{
// remove settings and throw any exception encountered
Dispose();
throw;
}
}
}
/// <summary>
/// Disposes of the object by eliminating all references to existing credentials
/// </summary>
public void Dispose()
{
client = null;
endPt = null;
authKey = null;
dbName = null;
collName = null;
}
#endregion
#region Enumerations
/// <summary>
/// Operations type for DocOpsAsync and RunBatchAsync
/// </summary>
private enum OpsType : int
{
AddDoc = 0,
UpdateDoc = 1,
ReplaceDoc = 2,
DeleteDoc = 3
}
/// <summary>
/// Return types for WHResponse objects
/// </summary>
public enum ReturnType : int
{
JSONstring = 1,
XMLstring = 2
}
#endregion
#region Public Methods
#region Add Methods
/// <summary>
/// Adds a document to the database and returns ID of new document.
/// </summary>
/// <param name="newDoc">The document to be created. Can be anything that evaluates to JSON: a JSON document or string, XML document or string,
/// a POCO (plain old CLR object), or just a string that converts to JSON</param>
/// <returns>String containing the ID of the document that was added. </returns>
public async Task<WHResponse> AddDocAsync(object newDoc)
{
return await DocOpsAsync(newDoc, OpsType.AddDoc);
}
/// <summary>
/// Add a batch of documents. Returns List of document IDs in same order as submitted IDs (blank if error - check exceptions).
/// </summary>
/// <param name="newDocColl">IEnumerable(object) of documents. </param>
/// <returns>List(string) of status codes (204=success, 404=not found, 500=error)</returns>
public async Task<List<WHResponse>> AddBatchAsync(IEnumerable<object> newDocColl)
{
// return from the batch runner
return await RunBatchAsync(newDocColl, OpsType.AddDoc);
}
#endregion
#region Get Methods
/// <summary>
/// Get documents using SQL string. Returns JSON array of documents or XML document.
/// </summary>
/// <param name="queryExp">DocDB SQL string or lambda expression to select documents. Sample lambda declaration: Expression(Func(Document, bool)) lambdaExp = d => d.Id == docID </param>
/// <param name="returnType">Enumerated return type, default is JSON.</param>
/// <param name="maxCount">Maximum number of documents to return.</param>
/// <param name="sessionToken">Session token for consistency if required.</param>
/// <param name="contToken">Continuation token for paging. Taken from previous WHResponse.Continuation property.</param>
/// <returns>WHResponse object</returns>
public async Task<WHResponse> GetDocsAsync(object queryExp, ReturnType returnType = ReturnType.JSONstring, int maxCount = 100, string sessionToken = null, string contToken = null)
{
//set the feed options
FeedOptions feedOpt = new FeedOptions
{
MaxItemCount = maxCount,
SessionToken = sessionToken,
RequestContinuation = contToken
};
try
{
// set up to receive queryable document collection based upon query expression
IDocumentQuery<Document> queryable = GetDocuments(queryExp, feedOpt) as IDocumentQuery<Document>;
//execute query and get results as a feed
FeedResponse<Document> feedResp = await queryable.ExecuteNextAsync<Document>();
// convert to response format
WHResponse resObj = FormatQueryResults(feedResp, returnType);
// store continuation token and return response object
resObj.Continuation = feedResp.ResponseContinuation;
return resObj;
}
catch (Exception ex)
{
// return bad request
return new WHResponse(WHResponse.ResponseCodes.BadRequest, null, true, string.Concat(BAD_QUERY, ex.Message), ex);
}
}
/// <summary>
/// Get single document using document ID. Returns JSON array of documents or XML document in Return property. SelfID is in the Link property.
/// </summary>
/// <param name="docID">ID of the document to return.</param>
/// <param name="returnType">Enumerated return type, default is JSON.</param>
/// <returns>WHResponse object</returns>
public WHResponse GetDocByID(string docID, ReturnType returnType = ReturnType.JSONstring)
{
try
{
//get document with matching ID
Expression<Func<Document, bool>> lambdaExp = d => d.Id == docID;
IEnumerable<Document> docs = GetDocuments(lambdaExp);
//return formatted response object
return FormatQueryResults(docs, returnType);
}
catch (Exception ex)
{
// return bad request
return new WHResponse(WHResponse.ResponseCodes.BadRequest, null, true, ex.Message, ex);
}
}
////get documents by document type
//public DbDocumentCollection GetDocsByType(int limit = 0, int offset = 0);
#endregion
#region Replace Methods
/// <summary>
/// Replace a document in the database with a new document
/// </summary>
/// <param name="newDoc">The document to be created. Can be anything that evaluates to JSON: a JSON document or string, XML document or string,
/// a POCO (plain old CLR object), or just a string that converts to JSON.</param>
/// <param name="selfID">The selfID of the document to be replaced. Can be blank if newDoc parm contains a Document object with a valid SelfID property.</param>
/// <returns></returns>
public async Task<WHResponse> ReplaceDocAsync(object newDoc, string selfID = null)
{
// if selfID is blank and newDoc is a Document, try to set the selfID from newDoc
if (selfID == null)
if (newDoc is Document)
{
Document chkDoc = newDoc as Document;
selfID = chkDoc.SelfLink;
}
else
{
// return bad request
return new WHResponse(WHResponse.ResponseCodes.BadRequest, null, true, NO_SELF_ID);
}
try
{
//replace document
return await DocOpsAsync(newDoc, OpsType.ReplaceDoc, selfID);
}
catch (Exception ex)
{
// return bad request
return new WHResponse(WHResponse.ResponseCodes.BadRequest, null, true, ex.Message, ex);
}
}
/// <summary>
/// Replace a batch of documents. Returns a List of WHReponse objects.
/// </summary>
/// <param name="newDocColl">IEnumerable(object) of Documents objects that have SelfID set in each. If unknown, getDocByID returns SelfID in the Link property. </param>
/// <returns>List of WHResponse objects with results in each.</returns>
public async Task<List<WHResponse>> ReplaceBatchAsync(IEnumerable<Document> newDocColl)
{
// return from the batch runner
return await RunBatchAsync(newDocColl, OpsType.ReplaceDoc);
}
#endregion
#region Update Methods
//public void UpdateDoc(DbDocument newDoc);
//public Task<List<string>> UpdateBatchAsync(DbDocumentCollection newDocBatch);
#endregion
#region Delete Methods
/// <summary>
/// Deletes a document from the database and returns HTTP status code of operation (204=success, 404=not found).
/// </summary>
/// <param name="docID">The ID of the document to be deleted. If not found, returns HTTP status code 404.</param>
/// <returns>Integer containing HTTP status code: 204=success; 404=not found; </returns>
public async Task<WHResponse> DeleteDocAsync(string docID = "")
{
try
{
//if there is a document ID
if (docID != "")
{
// call create document method and return ID of created document
IEnumerable<Document> delDocs = Client.CreateDocumentQuery(CollectionID).Where(d => d.Id == docID).AsEnumerable();
//if there are no docs with that ID
if (delDocs.Count() == 0)
{
// return http status for not found
return new WHResponse(WHResponse.ResponseCodes.NotFound, null);
}
else
{
//get the self link of document and delete
string sLink = delDocs.First().SelfLink;
ResourceResponse<Document> retDoc = await Client.DeleteDocumentAsync(sLink);
//return http status for delete success (no content)
return new WHResponse(WHResponse.ResponseCodes.SuccessDelete, null);
}
}
else
{
// return invalid client
return new WHResponse(WHResponse.ResponseCodes.BadRequest, null, true, EMPTY_ID);
}
}
catch (Exception ex)
{
// return invalid client
return new WHResponse(WHResponse.ResponseCodes.BadRequest, null, true, ex.Message, ex);
}
}
/// <summary>
/// Delete a batch of documents. Returns List of status codes (204=success, 404=not found, 500=error) in same order as submitted IDs.
/// </summary>
/// <param name="docIDs">List(string) of document IDs. If found will be deleted (204 status), if not skipped (404)</param>
/// <returns>List(int) of status codes (204=success, 404=not found, 500=error)</returns>
public async Task<List<WHResponse>> DeleteBatchAsync(List<string> docIDs)
{
// return from the batch runner
return await RunBatchAsync(docIDs, OpsType.DeleteDoc);
}
#endregion
#endregion
#region Private Internal Use Methods
/// <summary>
/// Perform document operation (add, update or replace) on the database.
/// </summary>
/// <param name="newDoc">The document to be created. Can be anything that evaluates to JSON: a JSON document or string, XML document or string,
/// a POCO (plain old CLR object), or just a string that converts to JSON</param>
/// <param name="operation">The enumerated operation to perform (add, update, replace).</param>
/// <param name="selfID">The selfID of the document to replace (replace operation only).</param>
/// <returns>String containing the ID of the document that was added. </returns>
private async Task<WHResponse> DocOpsAsync(object newDoc, OpsType operation, string selfID = null)
{
try
{
// if the document is empty, return bad request
if (newDoc.ToString().Replace(" ", "") == EMPTY_DOC)
{
return new WHResponse(WHResponse.ResponseCodes.BadRequest, null, true, DOC_NULL);
}
else
{
// if the parameter passed was a string and not a formal object
if (newDoc is string)
{
try
{
//try converting to JSON object and reassigning
JObject jStr = JObject.Parse(newDoc.ToString());
newDoc = jStr;
}
catch (Exception jEx)
{
//if string is not XML
string testStr = newDoc as string;
if (testStr.First() != Convert.ToChar("<"))
{
// return invalid string
return new WHResponse(WHResponse.ResponseCodes.BadRequest, null, true, BAD_STRING, jEx);
}
else
{
try
{
XmlDocument docXML = new XmlDocument();
docXML.InnerXml = newDoc.ToString();
newDoc = docXML;
}
catch (Exception xEx)
{
// return invalid string
return new WHResponse(WHResponse.ResponseCodes.BadRequest, null, true, BAD_STRING, xEx);
}
}
}
}
try
{
switch (operation)
{
case OpsType.AddDoc:
// call create document method and return ID of created document
Document created = await Client.CreateDocumentAsync(CollectionID, newDoc);
return new WHResponse(WHResponse.ResponseCodes.SuccessAdd, created.Id, false, null, null, WHResponse.ContentType.Text, created.SelfLink);
//case OpsType.UpdateDoc:
// break;
case OpsType.ReplaceDoc:
// call create document method and return ID of created document
created = await Client.ReplaceDocumentAsync(selfID, newDoc);
return new WHResponse(WHResponse.ResponseCodes.SuccessGetOrUpdate, created.Id, false, null, null, WHResponse.ContentType.Text, created.SelfLink);
default:
return new WHResponse(WHResponse.ResponseCodes.BadRequest, null, true, BAD_STRING);
}
}
catch (DocumentClientException docEx)
{
// if there is a conflict, return error message
if (docEx.Error.Code.ToLower() == CONFLICT_TEXT)
{
return new WHResponse(WHResponse.ResponseCodes.Conflict, newDoc.ToString(), true, string.Concat(CONFLICT_MSG, docEx.Message), docEx, WHResponse.ContentType.Text);
}
// if document not found, return error message
if (docEx.Error.Code.ToLower() == NOTFOUND_TEXT)
{
return new WHResponse(WHResponse.ResponseCodes.NotFound, newDoc.ToString(), true, string.Concat(NOTFOUND_MSG, docEx.Message), docEx, WHResponse.ContentType.Text);
}
//throw any other exceptions
throw;
}
catch (Exception)
{
//throw any other exceptions
throw;
}
}
}
catch (ApplicationException appEx)
{
// return invalid client
return new WHResponse(WHResponse.ResponseCodes.BadRequest, null, true, appEx.Message, appEx);
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Formats a WHResponse object from the results of a query.
/// </summary>
/// <param name="docs">Collection of one or more Documents to format</param>
/// <param name="returnType">Format of Return property.</param>
/// <param name="responseCode">Response Code to put in HTTPStatus property.</param>
/// <returns></returns>
private WHResponse FormatQueryResults(IEnumerable<Document> docs, ReturnType returnType, WHResponse.ResponseCodes responseCode = WHResponse.ResponseCodes.SuccessGetOrUpdate)
{
//if no document exists
if (docs == null)
{
//return not found
return new WHResponse(WHResponse.ResponseCodes.NotFound, null);
}
else
{
if (returnType == ReturnType.XMLstring)
{
//return success as formatted XML string
return new WHResponse(responseCode,
JsonConvert.DeserializeXmlNode(string.Concat(JSON_ROOT, JsonConvert.SerializeObject(docs).ToString(), "}}")).InnerXml,
false, null, null, WHResponse.ContentType.XML, docs.First().SelfLink, null, null, docs.Count());
}
else
{
//if only one document, handle json serialization separately
if (docs.Count() == 1)
{
//return success as json (only serialize first node to avoid sending an array with one element - causes issues in later json handling)
return new WHResponse(responseCode, JsonConvert.SerializeObject(docs.First()),
false, null, null, WHResponse.ContentType.JSON, docs.First().SelfLink, null, null, docs.Count());
}
else
{
//return success as json
return new WHResponse(responseCode, JsonConvert.SerializeObject(docs),
false, null, null, WHResponse.ContentType.JSON, docs.First().SelfLink, null, null, docs.Count());
}
}
}
}
private IQueryable<Document> GetDocuments(object queryExp, FeedOptions feedOpt = null)
{
try
{
//if query is string, execute and return
if (queryExp is string)
{
string sqlString = queryExp as string;
return Client.CreateDocumentQuery<Document>(CollectionID, sqlString, feedOpt);
}
else
{
//if query is lambda expression, execute and return
if (queryExp is Expression<Func<Document, bool>>)
{
Expression<Func<Document, bool>> lambdaExp = queryExp as Expression<Func<Document, bool>>;
return Client.CreateDocumentQuery<Document>(CollectionID, feedOpt).Where(lambdaExp);
}
}
// return empty set if not sql or lambda
return null;
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Process batch for CRUD operations. All batches are run the same way.
/// </summary>
/// <param name="batch">Object submitted to perform the operation. Differs for each operation, see non-batch methods for specific type required. </param>
/// <param name="operation">Enumerated type of operation to run.</param>
/// <returns></returns>
private async Task<List<WHResponse>> RunBatchAsync(IEnumerable<object> batch, OpsType operation)
{
try
{
//initialize query object
IEnumerable<Task<WHResponse>> iQuery = null;
// create a query to get each doc object from collection submitted (cannot use switch due to select statement)
if (operation == OpsType.AddDoc)
{
iQuery = from docObj in batch select AddDocAsync(docObj);
}
else
{
if (operation == OpsType.DeleteDoc)
{
iQuery = from docID in (batch as List<string>) select DeleteDocAsync(docID);
}
else
{
if (operation == OpsType.ReplaceDoc)
{
iQuery = from docObj in batch select ReplaceDocAsync(docObj);
}
else //(operation == OpsType.UpdateDoc)
{
//iQuery = from docObj in batch select UpdateDocAsync(docObj);
}
}
}
// execute the query into an array of tasks
Task<WHResponse>[] iTasks = iQuery.ToArray();
// load the results of each task into an array
WHResponse[] results = await Task.WhenAll(iTasks);
// iterate array to list for performance
List<WHResponse> respList = new List<WHResponse>();
for (int i = 0; i < results.Length; i++)
{
respList.Add(results[i]);
}
//return results as a list
return respList;
}
catch (Exception ex)
{
// return bad request
List<WHResponse> respList = new List<WHResponse>();
respList.Add(new WHResponse(WHResponse.ResponseCodes.BadRequest, null, true, ex.Message, ex));
return respList;
}
}
#endregion
}
public class WHResponse
{
#region Constructor and Class Properties
public ResponseCodes HTTPStatus { get; set; }
public string Return { get; set; }
public bool HasError { get; set; }
public string ErrorMsg { get; set; }
public Exception InnerException { get; set; }
public ContentType MediaType { get; set; }
public string Link { get; set; }
public string AttachmentLink { get; set; }
public string Continuation { get; set; }
public int Count { get; set; }
/// <summary>
/// Creates a blank Wellhub Response data transfer object.
/// </summary>
public WHResponse() { }
/// <summary>
/// Creates and populates a Wellhub Response data transfer object.
/// </summary>
/// <param name="status">HTTP status code of the respose.</param>
/// <param name="body">Body of the response - will be blank on errors.</param>
/// <param name="hasErr">Indicates if processing encountered an error.</param>
/// <param name="errMsg">Error message of processing exception.</param>
/// <param name="innerEx">Inner exception object - wraps a processing exception.</param>
/// <param name="contentType">Internet media type of the Return body. Default is JSON.</param>
/// <param name="link">String containing internal link to get associated document if there is one.</param>
/// <param name="attLink">String containing internal link to get attachment(s) of associated document if there is one.</param>
/// <param name="respCont">String containing response continuation key for paging operations (used to get next page).</param>
/// <param name="docCount">Integer showing how many documents are in Return.</param>
public WHResponse(ResponseCodes status, string body, bool hasErr = false, string errMsg = null, Exception innerEx = null,
ContentType contentType = ContentType.Text, string link = null, string attLink = null, string respCont = null, int docCount = 0)
{
//return a response object from parms
HTTPStatus = status;
Return = body;
HasError = hasErr;
ErrorMsg = errMsg;
InnerException = innerEx;
MediaType = contentType;
Link = link;
AttachmentLink = attLink;
Continuation = respCont;
Count = docCount;
}
#endregion
#region Enumerations
/// <summary>
/// Enumerated HTTP response codes for Wellhub Response data transfer objects.
/// </summary>
public enum ResponseCodes : int
{
//response codes are same as for Microsoft DocumentDB public API
SuccessGetOrUpdate = 200, //HTTP ok
SuccessAdd = 201, //HTTP created
SuccessDelete = 204, //HTTP no content
BadRequest = 400, //HTTP bad request
Unauthorized = 401, //HTTP unauthorized
Forbidden = 403, //HTTP forbidden
NotFound = 404, //HTTP not found
Conflict = 409, //HTTP conflict
TooLarge = 413 //HTTP entity too large
}
/// <summary>
/// Enumerated content types for Return property of Wellhub Response data transfer objects.
/// </summary>
public enum ContentType : int
{
Text = 0,
JSON = 1,
XML = 2,
HTML = 3,
JPG = 4,
GIF = 5,
PNG = 6,
PDF = 7
}
#endregion
#region Private Internal Use Methods
private string Content(ContentType intContent)
{
switch (intContent)
{
case ContentType.Text:
return "text/plain";
case ContentType.JSON:
return "application/json";
case ContentType.XML:
return "application/xml";
case ContentType.HTML:
return "text/html";
case ContentType.GIF:
return "image/gif";
case ContentType.JPG:
return "image/jpeg";
case ContentType.PNG:
return "image/png";
case ContentType.PDF:
return "application/pdf";
default:
return "text/plain";
}
}
#endregion
}
}
| 1c1ba1b583e5d0979b47f2bd348d0e90120853e3 | [
"C#"
]
| 2 | C# | gpdemarco/dbdoc | 3753c2626daa2498e4415a0c2182b16e3be8d6bc | 5dd2ea42d3b6822d467607fd3bf71309606f5ede |
refs/heads/master | <repo_name>vitoriagoncalvess/pop-soda-drink<file_sep>/painel_pessoa_fisica.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>POP'S - Perfil Pessoa Física</title>
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/painel_pessoa_fisica.css">
<link rel="stylesheet" type="text/css" href="css/titulo_pagina.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- CHAMANDO O JQUERY -->
<script src="js/jquery.js">
</script>
<!-- CHAMANDO O ARQUIVO DE EVENTOS EM JQUERY -->
<script src="js/event.js">
</script>
</head>
<body>
<header>
<?php require_once 'header.php' ?>
</header>
<!-- caixa que ocupa 100% de altura e largura -->
<div class="caixa_geral_pessoa_fisica centralizar_caixa">
<div class="caixa_central_pessoa_fisica centralizar_caixa">
<!-- FOTO E NOME-->
<div class="caixa_identidade">
<img src="img/a.jpg" id="foto" width="245" height="250" title="">
</div>
<!-- INFORMAÇÕES USER -->
<div class="informacoes_pessoa_fisica">
<div class="caixa_titulo_inf tamanho_caixa_nome">
<p>
<span class="font-titulo font-negrito">Nome:</span>
<span class="font-texto" id="nome"><EMAIL></span>
</p>
</div>
<div class="caixa_titulo_inf tamanho_caixa_celular_cpf_estado">
<span class="font-titulo font-negrito">CPF:</span>
<span class="font-texto color-blue" id="cpf">06604-220</span>
</div>
<div class="caixa_titulo_inf tamanho_caixa_celular_cpf_estado">
<span class="font-titulo font-negrito">Celular:</span>
<span class="font-texto color-blue" id="celular">(00) 95353-8395</span>
</div>
<div class="caixa_titulo_inf tamanho_caixa_celular_cpf_estado">
<span class="font-titulo font-negrito">Celular:</span>
<span class="font-texto color-blue" id="celular"></span>
</div>
<div class="caixa_titulo_inf tamanho_caixa_logradouro_bairro">
<span class="font-titulo font-negrito">Logradouro:</span>
<span class="font-texto color-blue" id="logradouro">Rua Senai Jandira</span>
</div>
<div class="caixa_titulo_inf tamanho_caixa_numero">
<span class="font-titulo font-negrito">Nº:</span>
<span class="font-texto color-blue" id="num">167</span>
</div>
<div class="caixa_titulo_inf tamanho_caixa_logradouro_bairro">
<span class="font-titulo font-negrito">Bairro:</span>
<span class="font-texto color-blue" id="bairro">Jd.Senai Jandira</span>
</div>
<div class="caixa_titulo_inf tamanho_caixa_cidade">
<span class="font-titulo font-negrito">Cidade:</span>
<span class="font-texto color-blue" id="cidade">Jandira</span>
</div>
<div class="caixa_titulo_inf tamanho_caixa_celular_cpf_estado">
<span class="font-titulo font-negrito">Estado:</span>
<span class="font-texto color-blue" id="uf">SP</span>
</div>
</div>
<!-- COMENTÁRIO -->
<section id="comentario">
<form class="form-comentario" id="form-comentario" action="painel_pessoa_fisica.php" method="POST">
<h1 class="font-titulo font-negrito color-blue">Comentário</h1>
<textarea class="font-texto" type="text" name="txtComentario" id="txtComentario"></textarea><br>
<input class="botao_comentario" type="submit" value="Enviar">
</form>
</section>
</div>
<?php } ?>
</div>
<footer> <?php require_once('footer.html')?> </footer>
<!-- CHAMANDO O ARQUIVO DE REQUESTS EM JQUERY -->
<script src="js/ws_requests.js">
</script>
<script>
$(document).ready(function(){
//SELECIONAR DADOS VIA COOKIE
getAllData();
});
</script>
</body>
</html><file_sep>/produtos.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>Produtos</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/murilo.css">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/arielle.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="js/jquery.js"></script>
<script src="js/event.js"></script>
<script src="js/effects.js"></script>
</head>
<body>
<?php
session_start();
require_once('../cms/model/DAO/Conexao.php');
$conex = new Conexao();
$con = $conex->connectDatabase();
?>
<header><?php require_once 'header.php'; ?></header>
<div class="teste_produto">
<div class="principal">
<div class="menu_filtos-produtos">
<form action="index.html" method="post">
<h3 class="title-menu-produtos">
Marca:
</h3>
<select class="input-select" name="selectfiltro"> </select>
<h3 class="title-menu-produtos">
Preço:
</h3>
<select class="input-select" name="selectfiltro"> </select>
<h3 class="title-menu-produtos">
Quantidade:
</h3>
<select class="input-select" name="selectfiltro"> </select>
</form>
</div>
<div class="area-produtos">
<?php
$sql = "SELECT * FROM tbl_produto WHERE status = 1";
$stm = $con->prepare($sql);
$success = $stm->execute();
foreach ($stm->fetchAll(PDO::FETCH_ASSOC) as $result){
?>
<div class="section-six-products">
<div class="section-six-image-products centralizar_elemento">
<img src="../cms/view/img/temp/<?php echo ($result['imagem']) ?>" alt="Produto">
</div>
<div class="section-six-text-products">
<h2><?php echo (utf8_decode($result['nome'])) ?></h2>
</div>
<div class="section-six-button">
<input type="button" name="btn_tabelanutricional" value="Tabela nutrional">
</div>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
<footer><?php require_once 'footer.html'; ?></footer>
</body>
</html>
<file_sep>/anuncios.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>Anúncios</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/arielle.css">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/anuncios.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="js/jquery.js"></script>
<script src="js/effects.js"></script>
<script src="js/event.js"></script>
</head>
<body>
<header><?php require_once 'header.php';?></header>
<!-- Conteúdo chamativo -->
<div id="caixa_conteudo_chamativo" style="background-image: url(img/estabelecimento1.jpg);">
<div id="conteudo_chamativo">
<h1 style="color:white; font-family:Helvetica "><strong>Anúncios</strong></h1>
<p class="texto_conteudo_chamativo" style="color:white; font-size:23px; text-align:center; margin-top:20px; font-family:Gadugi">
Quer adquirir os produtos da POP'Soda Drink? Confira os estabelecimentos que
participam da Rede POP'S.
</p>
</div>
</div>
<!-- Anuncio -->
<section class="caixa_geral_anuncios">
<div class="caixa_anuncios sombra">
<h3 style="font-family:Helvetica">Atacadão</h3>
<div class="img_anuncios">
<img src="img/atacadao.jpg" width="280" height="200" title="Ola" alt="Imagem não encontrada">
</div>
<p class="caixa_anuncios_texto" style="font-size:20px">
O Atacadão é um supermecado que revende varejo e atacado.
</p>
<div class="caixa_endereco">
<div class="endereco div_tamanho_fixo_endereco">
<p class="texto_negrito_anuncios">Logradouro:</p>
<span>Avenida Sebastião Jordão</span>
</div>
<div class="endereco div_tamanho_fixo_endereco_2">
<p class="texto_negrito_anuncios">Nº:</p>
<span>400 </span>
</div>
<div class="endereco div_tamanho_fixo_endereco_3">
<p class="texto_negrito_anuncios">Cidade:</p>
<span>Jandira</span>
</div>
<div class="endereco div_tamanho_fixo_endereco_3">
<p class="texto_negrito_anuncios">Estado:</p>
<span>São Paulo</span>
</div>
</div>
</div>
<div class="caixa_anuncios sombra">
<h3 style="font-family:Helvetica">Atacadão</h3>
<div class="img_anuncios">
<img src="img/atacadao.jpg" width="280" height="200" title="Ola" alt="Imagem não encontrada">
</div>
<p class="caixa_anuncios_texto" style="font-size:20px">
O Atacadão é um supermecado que revende varejo e atacado.
</p>
<div class="caixa_endereco">
<div class="endereco div_tamanho_fixo_endereco">
<p class="texto_negrito_anuncios">Logradouro:</p>
<span>Avenida Sebastião Jordão</span>
</div>
<div class="endereco div_tamanho_fixo_endereco_2">
<p class="texto_negrito_anuncios">Nº:</p>
<span>400 </span>
</div>
<div class="endereco div_tamanho_fixo_endereco_3">
<p class="texto_negrito_anuncios">Cidade:</p>
<span>Jandira</span>
</div>
<div class="endereco div_tamanho_fixo_endereco_3">
<p class="texto_negrito_anuncios">Estado:</p>
<span>São Paulo</span>
</div>
</div>
</div>
<div class="caixa_anuncios sombra">
<h3 style="font-family:Helvetica">Atacadão</h3>
<div class="img_anuncios">
<img src="img/atacadao.jpg" width="280" height="200" title="Ola" alt="Imagem não encontrada">
</div>
<p class="caixa_anuncios_texto" style="font-size:20px">
O Atacadão é um supermecado que revende varejo e atacado.
</p>
<div class="caixa_endereco">
<div class="endereco div_tamanho_fixo_endereco">
<p class="texto_negrito_anuncios">Logradouro:</p>
<span>Avenida Sebastião Jordão</span>
</div>
<div class="endereco div_tamanho_fixo_endereco_2">
<p class="texto_negrito_anuncios">Nº:</p>
<span>400 </span>
</div>
<div class="endereco div_tamanho_fixo_endereco_3">
<p class="texto_negrito_anuncios">Cidade:</p>
<span>Jandira</span>
</div>
<div class="endereco div_tamanho_fixo_endereco_3">
<p class="texto_negrito_anuncios">Estado:</p>
<span>São Paulo</span>
</div>
</div>
</div>
<div class="caixa_anuncios sombra">
<h3 style="font-family:Helvetica">Atacadão</h3>
<div class="img_anuncios">
<img src="img/atacadao.jpg" width="280" height="200" title="Ola" alt="Imagem não encontrada">
</div>
<p class="caixa_anuncios_texto" style="font-size:20px">
O Atacadão é um supermecado que revende varejo e atacado.
</p>
<div class="caixa_endereco">
<div class="endereco div_tamanho_fixo_endereco">
<p class="texto_negrito_anuncios">Logradouro:</p>
<span>Avenida <NAME></span>
</div>
<div class="endereco div_tamanho_fixo_endereco_2">
<p class="texto_negrito_anuncios">Nº:</p>
<span>400 </span>
</div>
<div class="endereco div_tamanho_fixo_endereco_3">
<p class="texto_negrito_anuncios">Cidade:</p>
<span>Jandira</span>
</div>
<div class="endereco div_tamanho_fixo_endereco_3">
<p class="texto_negrito_anuncios">Estado:</p>
<span>São Paulo</span>
</div>
</div>
</div>
<div class="caixa_anuncios sombra">
<h3 style="font-family:Helvetica">Atacadão</h3>
<div class="img_anuncios">
<img src="img/atacadao.jpg" width="280" height="200" title="Ola" alt="Imagem não encontrada">
</div>
<p class="caixa_anuncios_texto" style="font-size:20px">
O Atacadão é um supermecado que revende varejo e atacado.
</p>
<div class="caixa_endereco">
<div class="endereco div_tamanho_fixo_endereco">
<p class="texto_negrito_anuncios">Logradouro:</p>
<span>Avenida Sebastião Jordão</span>
</div>
<div class="endereco div_tamanho_fixo_endereco_2">
<p class="texto_negrito_anuncios">Nº:</p>
<span>400 </span>
</div>
<div class="endereco div_tamanho_fixo_endereco_3">
<p class="texto_negrito_anuncios">Cidade:</p>
<span>Jandira</span>
</div>
<div class="endereco div_tamanho_fixo_endereco_3">
<p class="texto_negrito_anuncios">Estado:</p>
<span>São Paulo</span>
</div>
</div>
</div>
<div class="caixa_anuncios sombra">
<h3 style="font-family:Helvetica">Atacadão</h3>
<div class="img_anuncios">
<img src="img/atacadao.jpg" width="280" height="200" title="Ola" alt="Imagem não encontrada">
</div>
<p class="caixa_anuncios_texto" style="font-size:20px">
O Atacadão é um supermecado que revende varejo e atacado.
</p>
<div class="caixa_endereco">
<div class="endereco div_tamanho_fixo_endereco">
<p class="texto_negrito_anuncios">Logradouro:</p>
<span><NAME></span>
</div>
<div class="endereco div_tamanho_fixo_endereco_2">
<p class="texto_negrito_anuncios">Nº:</p>
<span>400 </span>
</div>
<div class="endereco div_tamanho_fixo_endereco_3">
<p class="texto_negrito_anuncios">Cidade:</p>
<span>Jandira</span>
</div>
<div class="endereco div_tamanho_fixo_endereco_3">
<p class="texto_negrito_anuncios">Estado:</p>
<span>São Paulo</span>
</div>
</div>
</div>
</section>
<footer> <?php require_once('footer.html');?> </footer>
</body>
</html>
<file_sep>/pagamento.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>POP'Soda Drink - Pagamento</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/pagamento.css">
<link rel="stylesheet" type="text/css" href="css/titulo_pagina.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- CHAMANDO O JQUERY -->
<script src="js/jquery.js">
</script>
<!-- CHAMANDO O ARQUIVO DE EVENTOS EM JQUERY -->
<script src="js/event.js">
</script>
</head>
<body>
<!-- header -->
<header>
<?php require_once('header.php')?>
</header>
<!-- Título da página -->
<div class="titulo_pagina font-titulo">
<h1>Pagamento</h1>
</div>
<div class="caixa_central_pagamento">
<form name="frmPagamento" method="POST" action="pagamento.php">
<!-- Grupos form 1 -->
<div class="caixa_form_pagamento">
<!-- NOME -->
<div class="caixa_grupo_form div_esquerda">
<div class="caixa_campos_form">
<label for="txtNome" class="label_estilo font-titulo">Nome do titular do cartão: </label><br>
<input class="input_estilo input_titular_e_cartao" type="text" name="txtNome" id="txtNome">
</div>
<!-- Número do Cartão -->
<div class="caixa_campos_form">
<label for="txtNumCartao" class="label_estilo font-titulo">Número do cartão: </label><br>
<input class="input_estilo input_titular_e_cartao" type="text" name="txtNumCartao" id="txtNumCartao">
</div>
<!-- Número do Cartão -->
<div class="caixa_campos_form">
<label class="label_estilo font-titulo">Validade: </label><br>
<select id="sltValidadeNum1" class="input_estilo input_validade">
<option>1</option>
<option>2</option>
<option>2</option>
</select>
</div>
</div>
<!-- caixa form 2 -->
<div class="caixa_grupo_form div_direita">
<!-- Número do Cartão -->
<div class="caixa_campos_form margin_top_form_2">
<label for="txtCodSeguranca" class="label_estilo font-titulo">Código de Segurança: </label><br>
<input class="input_estilo input_seguranca" type="text" name="txtCodSeguranca" id="txtCodSeguranca">
<div class="imagem_cartao div_direita">
<img src="img/cartao.png" width="40" height="40" title="Código de Segurança" alt="Imagem não encontrada2">
</div>
</div>
<!-- Número do Cartão -->
<div class="caixa_campos_form">
<label class="label_estilo font-titulo">a</label><br>
<select id="sltValidadeNum2" class="input_estilo input_validade">
<option>1</option>
<option>2</option>
<option>2</option>
</select>
</div>
</div>
<!-- Botão finalizar -->
<div class="caixa_botao_pagamento">
<input class="botao_pagamento font-titulo" type="button" value="Finalizar Compra" id="btnFinalizarCompra" name="btnFinalizarCompra">
</div>
</div>
</form>
</div>
<footer> <?php require_once('footer.html')?> </footer>
</body>
</html>
<file_sep>/promocoes.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>Promoções</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/murilo.css">
<link rel="stylesheet" href="css/arielle.css">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/titulo_pagina.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="js/jquery.js"></script>
<script src="js/event.js"></script>
<script src="js/effects.js"></script>
</head>
<body>
<?php
session_start();
require_once('../cms/model/DAO/Conexao.php');
$conex = new Conexao();
$con = $conex->connectDatabase();
?>
<header><?php require_once 'header.php'; ?></header>
<div class="principal">
<div class="titulo_pagina font-titulo">
<h1 class="title-pag-promocoes">Promoções</h1>
</div>
<?php
$sql = "SELECT * FROM tbl_promocao WHERE status = 1";
$stm = $con->prepare($sql);
$success = $stm->execute();
foreach ($stm->fetchAll(PDO::FETCH_ASSOC) as $result){
?>
<div class="section-three-conteudo centralizar_elemento">
<div class="section-three-conteudo-imagem centralizarY">
<img class="centralizar_elemento" src="img/7upPromocao.jpg" alt="Promoção">
</div>
<div class="section-three-conteudo-infomarcao">
<div class="section-three-conteudo-titulo"><?php echo (utf8_decode($result['titulo'])) ?></div>
<div class="section-three-conteudo-texto">
<?php echo (utf8_decode($result['descricao'])) ?>
</div>
<br><br><br><div class="titleRegulamento">Regulamento</div>
<br>
<ol>
<li class="textRegulamento">1 - Compre refrigerantes de lata da 7up</li>
<li class="textRegulamento">2 - Junte as latas</li>
<li class="textRegulamento">3 - Vá até o estabelecimento no qual comprou e troque suas latas por cupons de sorteio</li>
<li class="textRegulamento">4 - Agora é só esperar para o sorteio</li>
<li class="textRegulamento">5 - O resultado será divulgado aqui no nosso site!</li>
</ol>
</div>
</div>
<?php } ?>
</div>
<footer> <?php require_once 'footer.html'; ?></footer>
</body>
</html>
<file_sep>/cadastro_pessoa_juridica.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>POP'S - Cadastro e Edição Pessoa Jurídica</title>
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/cadastro_edicao_pessoa_juridica.css">
<link rel="stylesheet" type="text/css" href="css/titulo_pagina.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- CHAMANDO O JQUERY -->
<script src="js/jquery.js">
<script src="js/effects.js"></script>
</script>
<!-- CHAMANDO O ARQUIVO DE EVENTOS EM JQUERY -->
<script src="js/event.js">
</script>
</head>
<body>
<header>
<?php require_once('header.php'); ?>
</header>
<!-- Título da página -->
<div class="titulo_pagina font-titulo">
<h1>Cadastro de pessoa juridica</h1>
</div>
<!-- Caixa central do formulário que ocupa 1200 da tela -->
<div class="caixa_central_formulario">
<form name="frmCadPjs" method="POST" enctype="multipart/form-data" action="cadastro_perfil_secundario_juridica.php">
<!-- caixa que guarda todo o formulário -->
<div class="caixa_form_juridica">
<!-- LINHA 1-->
<div class="caixa_input">
<!-- CNPJ -->
<div class="caixa_inputs_form caixa_inputs_form_pequena">
<label for="txtCnpjPj" class="label_estilo">CNPJ:</label><br>
<input class="input_estilo inputs_form" type="text" name="txtCnpjPj" id="txtCnpjPj">
</div>
<!-- Razão Social -->
<div class="caixa_inputs_form caixa_inputs_form_medio">
<label for="txtRazaoSocialPj" class="label_estilo">Razão Social:</label><br>
<input class="input_estilo inputs_form" type="text" name="txtRazaoSocialPj" id="txtRazaoSocialPj">
</div>
<!-- Nome Fantasia-->
<div class="caixa_inputs_form caixa_inputs_form_medio">
<label for="txtNomeFantasiaPj" class="label_estilo">Nome fantasia:</label><br>
<input class="input_estilo inputs_form" type="text" name="txtNomeFantasiaPj" id="txtNomeFantasiaPj">
</div>
</div>
<!-- LINHA 2-->
<div class="caixa_input">
<!-- Logradouro-->
<div class="caixa_inputs_form caixa_inputs_form_pequena">
<label for="txtLogradouroPj" class="label_estilo">Logradouro:</label><br>
<input class="input_estilo inputs_form" type="text" name="txtLogradouroPj" id="txtLogradouroPj">
</div>
<!-- num -->
<div class="caixa_inputs_form caixa_inputs_form_minima">
<label for="txtNumPj" class="label_estilo">Nº:</label><br>
<input class="input_estilo inputs_form" type="text" name="txtNumPj" id="txtNumPj">
</div>
<!-- Bairro-->
<div class="caixa_inputs_form caixa_inputs_form_pequena">
<label for="txtBairroPj" class="label_estilo">Bairro:</label><br>
<input class="input_estilo inputs_form" type="text" name="txtBairroPj" id="txtBairroPj">
</div>
<!-- CEP-->
<div class="caixa_inputs_form caixa_inputs_form_pequena">
<label for="txtCepPj" class="label_estilo">CEP:</label><br>
<input class="input_estilo inputs_form" type="text" name="txtCepPj" id="txtCepPj">
</div>
<!-- Cidade -->
<div class="caixa_inputs_form caixa_inputs_form_pequena">
<label for="txtCidadePj" class="label_estilo">Cidade:</label><br>
<input class="input_estilo inputs_form" type="text" name="txtCidadePj" id="txtCidadePj">
</div>
<!-- Estado -->
<div class="caixa_inputs_form caixa_inputs_form_pequena">
<label class="label_estilo">Estado:</label><br>
<select class="input_estilo inputs_form" name="txtEstadoPj" id="txtEstadoPj">
<option value="1">
SP
</option>
</select>
</div>
</div>
<!-- LINHA 3-->
<div class="caixa_input">
<!-- Responsavel pelo Contato -->
<div class="caixa_inputs_form caixa_inputs_form_medio">
<label for="txtRespContatoPj" class="label_estilo">Responsável pelo contato:</label><br>
<input class="input_estilo inputs_form" type="text" name="txtRespContatoPj" id="txtRespContatoPj">
</div>
<!-- Email-->
<div class="caixa_inputs_form caixa_inputs_form_medio">
<label for="txtEmailPj" class="label_estilo">Email:</label><br>
<input class="input_estilo inputs_form" type="text" name="txtEmailPj" id="txtEmailPj">
</div>
<!-- Telefone -->
<div class="caixa_inputs_form caixa_inputs_form_pequena">
<label for="txtTelefonePj" class="label_estilo">Telefone:</label><br>
<input class="input_estilo inputs_form" type="text" name="txtTelefonePj" id="txtTelefonePj">
</div>
</div>
<!-- Linha 4 -->
<!-- LINHA 3-->
<div class="caixa_imagem">
<div class="imagem_pj">
<label class="label_estilo">Foto:</label><br>
<img src="imagens/a.jpg" width="150" height="150" alt="ola" title="ola"><br>
<input type="file" name="txtFotoPj" id="txtFotoPj">
</div>
<!-- Usuário -->
<div class="caixa_inputs_form caixa_inputs_form_pequena">
<label for="txtUserPj" class="label_estilo">User:</label><br>
<input class="input_estilo inputs_form" type="text" name="txtUserPj" id="txtUserPj">
</div>
<!-- Senha -->
<div class="caixa_inputs_form caixa_inputs_form_pequena">
<label for="txtSenhaPj" class="label_estilo">Senha:</label><br>
<input class="input_estilo inputs_form" type="<PASSWORD>" name="txtSenhaPj" id="txtSenhaPj">
</div>
</div>
<!-- LINHA 4 BOTÃO -->
<div class="caixa_botao_pj">
<input class="botao_pj" type="button" value="Cadastrar" name="btnCadPj" id="btnCadPj">
</div>
</div>
</form>
</div>
<footer> <?php require_once('footer.html')?> </footer>
</body>
</html>
<file_sep>/cadastro_perfil_secundario_juridica.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>POP'Soda Drink - Cadastro do perfil jurídico secundário</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/cadastro_perfil_secundario_juridica.css">
<link rel="stylesheet" type="text/css" href="css/titulo_pagina.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- CHAMANDO O JQUERY -->
<script src="js/jquery.js">
<script src="js/effects.js"></script>
</script>
<!-- CHAMANDO O ARQUIVO DE EVENTOS EM JQUERY -->
<script src="js/event.js">
</script>
</head>
<body>
<!-- header -->
<header><?php require_once('header.php') ?></header>
<!-- Título da página -->
<div class="titulo_pagina font-titulo">
<h1>Cadastro do perfil jurídico secundário</h1>
</div>
<!-- caixa central que ocupa 1200 -->
<div class="caixa_central_pjs centralizar_caixa">
<form name="frmCadPjs" method="POST" enctype="multipart/form-data" action="cadastro_perfil_secundario_juridica.php">
<div class="caixa_central_form_pjs centralizar_caixa">
<!-- Linha 1 -->
<div class="caixa_inputs_pjs">
<!-- Responsável pelo contato -->
<div class="inputs_form inputs_form_grande">
<label class="label_estilo" for="txtRespContatoPjs">Responsável pelo Contato:</label>
<input class="input_estilo" type="text" name="txtRespContatoPjs" id="txtRespContatoPjs">
</div>
<!-- Email: -->
<div class="inputs_form inputs_form_grande">
<label class="label_estilo" for="txtEmailPjs">Email:</label>
<input class="input_estilo" type="text" name="txtEmailPjs" id="txtEmailPjs">
</div>
<!-- Telefone -->
<div class="inputs_form inputs_form_medio">
<label class="label_estilo" for="txtTelefonePjs">Telefone:</label>
<input class="input_estilo" type="text" name="txtTelefonePjs" id="txtTelefonePjs">
</div>
</div>
<!-- LINHA 2 -->
<div class="caixa_inputs_pjs">
<!-- Logradouro -->
<div class="inputs_form inputs_form_medio_2">
<label class="label_estilo" for="txtLogPjs">Logradouro:</label>
<input class="input_estilo" type="text" name="txtLogPjs" id="txtLogPjs">
</div>
<!-- Nº -->
<div class="inputs_form inputs_form_minima">
<label class="label_estilo" for="txtNumPjs">Nº:</label>
<input class="input_estilo" type="text" name="txtNumPjs" id="txtNumPjs">
</div>
<!-- Bairro -->
<div class="inputs_form inputs_form_medio_2">
<label class="label_estilo" for="txtBairroPjs">Bairro:</label>
<input class="input_estilo" type="text" name="txtBairroPjs" id="txtBairroPjs">
</div>
<!-- CEP -->
<div class="inputs_form inputs_form_medio_2">
<label class="label_estilo" for="txtCepPjs">CEP:</label>
<input class="input_estilo" type="text" name="txtCepPjs" id="txtCepPjs">
</div>
<!-- Cidade -->
<div class="inputs_form inputs_form_medio_2">
<label class="label_estilo" for="txtCidadePjs">Cidade:</label>
<input class="input_estilo" type="text" name="txtCidadePjs" id="txtCidadePjs">
</div>
<!-- Cidade -->
<div class="inputs_form inputs_form_medio_2">
<label class="label_estilo">Estado:</label><br>
<select class="input_estilo2" type="text" name="txtEstadoPjs" id="txtEstadoPjs">
<option value="ola">SP</option>
</select>
</div>
</div>
<!-- LINHA 3 -->
<div class="form_linha_3 centralizar_caixa">
<div class="caixa_img">
<img src="imagens/a.jpg" width="200" height="180" title="ola" alt="ola"><br>
<input type="file" name="flFotoPjs">
</div>
<!-- Usuário -->
<div class="inputs_form inputs_form_grande">
<label class="label_estilo" for="txtUserPjs">Usuário:</label>
<input class="input_estilo" type="text" name="txtUserPjs" id="txtUserPjs">
</div>
<!-- Senha -->
<div class="inputs_form inputs_form_grande">
<label class="label_estilo" for="txtSenhaPjs">Senha:</label>
<input class="input_estilo" type="text" name="txtSenhaPjs" id="txtSenhaPjs">
</div>
</div>
<div class="caixa_inputs_pjs centralizar_caixa">
<div class="caixa_botao_pjs centralizar_caixa">
<input class="botao_pjs" type="button" value="Cadastrar" name="btnCadPjs">
</div>
</div>
</div>
</div>
</form>
<footer> <?php require_once('footer.html');?> </footer>
</body>
</html><file_sep>/produtos-compra.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>Produtos</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/murilo.css">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/arielle.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="js/jquery.js"></script>
<script src="js/event.js"></script>
</head>
<body>
<header><?php require_once 'header.php'; ?></header>
<div class="principal">
<div class="menu_filtos-produtos">
<form action="index.html" method="post">
<h3 class"title-menu-produtos">
<img id="direita" src="img/triangulo.png" alt="">
Marca:
</h3>
<select class="input-select" name=""> </select>
<h3 class"title-menu-produtos">
<img id="direita" src="img/triangulo.png" alt="">
Preço:
</h3>
<select class="input-select" name=""> </select>
</form>
</div>
<!--
<div class="linha-divisa">
</div> -->
<div class="area-produtos">
<a href="carrinho.php">
<div class="carrinho-compras"></div>
</a>
<div class="section-six-products">
<div class="section-six-image-products centralizar_elemento">
<img src="img/crush.jpg" alt="Produto">
</div>
<div class="section-six-text-products">
<h2>Fardo com 16 Crush - 350ml cada</h2>
<p>R$30,40</p>
</div>
<div class="section-six-button">
<input type="button" name="" value="Adicionar o fardo">
</div>
</div>
<div class="section-six-products">
<div class="section-six-image-products centralizar_elemento">
<img src="img/gini.jpg" alt="Produto">
</div>
<div class="section-six-text-products">
<h2>Fardo com 16 Gini - 350ml cada</h2>
<p>R$30,40</p>
</div>
<div class="section-six-button">
<input type="button" name="" value="Adicionar o fardo">
</div>
</div>
<div class="section-six-products">
<div class="section-six-image-products centralizar_elemento">
<img src="img/7up1.jpg" alt="Produto">
</div>
<div class="section-six-text-products">
<h2>Fardo com 16 7UP - 350ml cada</h2>
<p>R$30,40</p>
</div>
<div class="section-six-button">
<input type="button" name="" value="Adicionar o fardo">
</div>
</div>
</div>
</body>
</html>
<file_sep>/pops_escola.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>Pop's nas escolas</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/arielle.css">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/pops_escola.css">
<link rel="stylesheet" type="text/css" href="css/titulo_pagina.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="js/jquery.js"></script>
<script src="js/event.js"></script>
</head>
<body>
<header><?php require_once 'header.php';?></header>
<!-- Título da página -->
<div class="titulo_pagina font-titulo">
<h1>POP'S nas Escolas</h1>
</div>
<!-- CONTEÚDO CHAMATIVO -->
<div class="caixa_pops_escola div_centro">
<div class="caixa_texto_imagem div_centro">
<p id="texto_formatacao">
A POP'S faz evento nas escolas, com a finalidade de apresentar nossos produtos e a nossa visão
para as crianças, jovens e adolescentes. Se você é diretor ou responsável por alguma instituição
de educação, preencha o formulário abaixo e aguarde o contato da POP'S.
</p>
<img class="sombra_imagens img_chamativa" src="img/escolas4.jpg" width="310" height="310" alt="Imagem não encontrada" title="ola">
</div>
</div>
<!-- CAIXA DO CADASTRO DA ESCOLA -->
<div id="caixa_geral_cadastro">
<section class="caixa_central_cadastro div_centro">
<h1 class="titulo_pops" >Cadastro da escola</h1>
<!-- FORM DIREITO -->
<div class="caixa_principal_formulario">
<!-- Nome da escola -->
<div class="caixa_formulario">
<input class="formatacao_inputs borda_inputs largura_fixa_inputs_1" type="text" placeholder="Nome da escola" id="txtNomeEscola" name="txtNomeEscola" value="">
</div>
<!-- Nome do diretor -->
<div class="caixa_formulario">
<input class="formatacao_inputs borda_inputs largura_fixa_inputs_1" type="text" placeholder="Nome do diretor" id="txtNomeDiretor" name="txtNomeDiretor" value="">
</div>
<!-- Telefone -->
<div class="caixa_formulario">
<input class="formatacao_inputs borda_inputs largura_fixa_inputs_2" type="text" placeholder="Telefone" id="txtTelefone" name="txtTelefone" value="">
</div>
<!-- Email -->
<div class="caixa_formulario">
<input class="formatacao_inputs borda_inputs largura_fixa_inputs_1" type="text" placeholder="Email" id="txtEmail" name="txtEmail" value="">
</div>
</div>
<!-- FORM ESQUERDO -->
<div class="caixa_principal_formulario">
<div class="caixa_formulario">
<!-- Logradouro -->
<div class="caixa_input largura_fixa_div">
<input class="formatacao_inputs borda_inputs largura_fixa_inputs_1" type="text" placeholder="Logradouro" id="txtLogradouro" name="txtLogradouro" value="">
</div>
<!-- Número -->
<div class="caixa_input largura_fixa_div_2">
<input class="formatacao_inputs borda_inputs largura_fixa_inputs_3" type="text" placeholder="Nº" id="txtNumero" name="txtNumero" value="">
</div>
<!-- Bairro -->
<div class="caixa_input largura_fixa_div_3">
<input class="formatacao_inputs borda_inputs largura_fixa_inputs_2" type="text" placeholder="Bairro" id="txtBairro" name="txtBairro" value="">
</div>
<!-- CEP -->
<div class="caixa_input largura_fixa_div_3">
<input class="formatacao_inputs borda_inputs largura_fixa_inputs_2" type="text" placeholder="CEP" id="txtCep" name="txtCep" value="">
</div>
<!-- Cidade -->
<div class="caixa_input largura_fixa_div_3">
<input class="formatacao_inputs borda_inputs largura_fixa_inputs_2" type="text" placeholder="Cidade" id="txtCidade" name="txtCidade" value="">
</div>
<div class="caixa_input largura_fixa_div_3">
<select class="slt_estado formatacao_inputs borda_inputs largura_fixa_inputs_3 slt_estado" id="sltEstado" name="sltEstado">
<option disabled selected>Estado:</option>
<option>SP</option>
<option>RJ</option>
<option>MG</option>
</select>
</div>
<div class="botao">
<input class="botao" type="button" value="Enviar" name="btnEnviar" id="btnEnviar">
</div>
</div>
</div>
<!-- AVISO -->
<div class="aviso aviso_form div_centro">
<h2 ><strong>Aviso</strong></h2>
<p>A POP'S entrará em contato nos próximos 7 dias uteis para prestar maiores informações e marcar data para o evento na instituição.
</p>
</div>
</section>
</div>
<!-- IMAGENS -->
<div id="caixa_imagens_pops">
<div class="caixa_central_imagens_pops div_centro">
<div class="imagens sombra_imagens">
<img src="img/escolas.jpg" width="300" height="300" title="ola" alt="Imagem não encontrada">
</div>
<div class="imagens sombra_imagens">
<img src="img/escolas2.jpg" width="300" height="300" title="ola" alt="Imagem não encontrada">
</div>
<div class="imagens sombra_imagens">
<img src="img/escolas3.jpg" width="300" height="300" title="ola" alt="Imagem não encontrada">
</div>
</div>
</div>
<!-- FOOTER -->
<footer> <?php require_once('footer.html')?> </footer>
</body>
</html><file_sep>/cadastro_pessoa_fisica.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>POP'S - Cadastro e Edição Pessoa Física</title>
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/cadastro_edicao_pessoa_fisica.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- CHAMANDO O JQUERY -->
<script src="js/jquery.js">
<script src="js/effects.js"></script>
</script>
<!-- CHAMANDO O ARQUIVO DE EVENTOS EM JQUERY -->
<script src="js/event.js">
</script>
</head>
<body>
<header>
<?php require_once('header.php'); ?>
</header>
<!-- Título da página -->
<div class="titulo_pagina font-titulo">
<h1>Cadastro perfil pessoa física</h1>
</div>
<!-- Caixa central do formulário que ocupa 1200 da tela -->
<div class="caixa_central_formulario">
<!-- caixa que guarda todo o formulário -->
<div class="caixa_form_fisica">
<!-- div dos labels e inputs do form -->
<!-- nome completo -->
<div class="campos_form_fisica">
<label for="txtNomePessoaFisica" class="label_estilo font-texto">Nome Completo: </label><br>
<input class="input_estilo input_largura_grande" type="text" name="txtNomePessoaFisica" id="txtNomePessoaFisica">
</div>
<!-- Email -->
<div class="campos_form_fisica">
<label for="txtEmailpessoaFisica" class="label_estilo font-texto">Email: </label><br>
<input class="input_estilo input_largura_grande" type="text" name="txtEmailPessoaFisica" id="txtEmailPessoaFisica">
</div>
<!-- CPF: -->
<div class="campos_form_fisica">
<label for="txtCpfPessoaFisica" class="label_estilo font-texto">CPF: </label><br>
<input class="input_estilo input_largura_media" type="text" name="txtCpfPessoaFisica" id="txtCpfPessoaFisica">
</div>
<!-- Celular -->
<div class="campos_form_fisica">
<label for="txtCelPessoaFisica" class="label_estilo font-texto">Celular: </label><br>
<input class="input_estilo input_largura_media" type="text" name="txtCelPessoaFisica" id="txtCelPessoaFisica">
</div>
<!-- Foto -->
<div class="campos_form_fisica">
<label class="label_estilo font-texto">Foto: </label><br>
<img width="150" height="150" src="imagens/a.jpg" alt="Imagem não encontrada" title="ola">
<input id="btnSalvarImagem" type="file" value="Salvar"><br>
</div>
<!-- Logradouro -->
<div class="campos_form_fisica">
<label for="txtLogradouroFisica" class="label_estilo font-texto">Logradouro: </label><br>
<input class="input_estilo input_largura_grande" type="text" name="txtLogradouroFisica" id="txtLogradouroFisica">
</div>
<!-- Número -->
<div class="campos_form_fisica">
<label for="txtNumFisica" class="label_estilo font-texto">Nº: </label><br>
<input class="input_estilo input_largura_pequena" type="text" name="txtNumFisica" id="txtNumFisica">
</div>
<!-- Bairro -->
<div class="campos_form_fisica">
<label for="txtBairroFisica" class="label_estilo font-texto">Bairro: </label><br>
<input class="input_estilo input_largura_grande" type="text" name="txtBairroFisica" id="txtBairroFisica">
</div>
<!-- Cidade -->
<div class="campos_form_fisica">
<label for="txtCidade" class="label_estilo font-texto">Cidade: </label><br>
<input class="input_estilo input_largura_grande" type="text" name="txtLogradouroFisica" id="txtCidade">
</div>
<!-- Estado -->
<div class="campos_form_fisica">
<label class="label_estilo font-texto">Estado: </label><br>
<select class="input_estilo input_largura_media" name="txtCelPessoaFisica" id="txtEstadoPessoaFisica">
<option> SP </option>
</select>
</div>
<!-- Usuário -->
<div class="campos_form_fisica">
<label for="txtCelPessoaFisica" class="label_estilo font-texto">User: </label><br>
<input class="input_estilo input_largura_media" type="text" name="txtUserPessoaFisica" id="txtUserPessoaFisica">
</div>
<!-- Senha -->
<div class="campos_form_fisica">
<label for="txtSenhaPessoaFisica" class="label_estilo font-texto">Senha: </label><br>
<input class="input_estilo input_largura_media" type="text" name="txtCelPessoaFisica" id="txtSenhaPessoaFisica">
</div>
<!-- Celular -->
<div id="caixa_botao">
<input class="botao" type="button" name="btnCadPessoaFisica" id="txtCelPessoaFisica" value="Cadastrar">
</div>
</div>
</div>
<footer> <?php require_once('footer.html') ?> </footer>
</body>
</html>
<file_sep>/carrinho.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>Produtos</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/murilo.css">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/arielle.css">
<link rel="stylesheet" type="text/css" href="css/carrinho.css">
<link rel="stylesheet" type="text/css" href="css/titulo_pagina.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="js/jquery.js"></script>
<script src="js/effects.js"></script>
<script src="js/event.js"></script>
</head>
<body>
<header><?php require_once 'header.php'; ?></header>
<!-- Título da página -->
<div class="titulo_pagina font-titulo">
<h1>Meu carrinho</h1>
</div>
<!-- caixa geral do conteúdo -->
<div class="caixa_central_carrinho centralizar_caixa">
<!-- caixa título das informações do produto -->
<div class="caixa_inf_produto centralizar_caixa">
<div class="inf_produto inf_nome_produto font-titulo inf_produto_texto">Produto</div>
<div class="inf_produto inf_qtd_produto font-titulo inf_produto_texto centralizar_texto">Quantidade</div>
<div class="inf_produto inf_valor_produto font-titulo inf_produto_texto centralizar_texto">Valor<br>Unitário</div>
<div class="inf_produto inf_valor_produto font-titulo inf_produto_texto centralizar_texto">Valor<br>Total</div>
</div>
<!-- Div do carrinho / fazer while aqui -->
<div class="caixa_carrinho centralizar_caixa">
<!-- caixa da imagem do produto -->
<div class="caixa_imagem_carrinho">
<img src="img/crush.jpg" width="150" height="150" title="Nome do Produto" alt="Imagem não encontrada">
</div>
<!-- Caixa nome e preço do produto -->
<div class="caixa_nome_preco">
<p class="font-texto nome_produto">Fardo com 16 Crush - 350ml cada<p>
<p class="font-texto font-negrito">R$ 30,40</p>
</div>
<!-- Caixa da quantidade do produto -->
<div class="caixa_qtd">
<div class="caixa_botao_qtd">
<input class="botao_qtd" type="button" name="btnMenos" id="btnMenos" value="-">
</div>
<div class="caixa_quantidade">
<input class="quantidade" type="text" name="txtQuantidade" id="txtQuantidade">
</div>
<div class="caixa_botao_qtd">
<input class="botao_qtd" type="button" name="btnMais" id="btnMais" value="+">
</div>
</div>
<div class="caixa_valor borda_caixa_valor">
<p>R$ 30,40</p>
</div>
<div class="caixa_valor ">
<p>R$ 30,40</p>
</div>
</div>
<!-- DIV SUB TOTAL -->
<div class="div_subtotal">
<p>Total: <span class="font-negrito">R$ 30,40</span> </p>
<input type="button" value="Continuar" id="btnContinuar" name="btnContinuar">
</div>
</div>
<footer><?php require_once 'footer.html'; ?></footer>
</body>
</html>
<file_sep>/sobre.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>Sobre</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/sobre.css">
<link rel="stylesheet" type="text/css" href="css/titulo_pagina.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- CHAMANDO O JQUERY -->
<script src="js/jquery.js">
</script>
<!-- CHAMANDO O ARQUIVO DE EVENTOS EM JQUERY -->
<script src="js/event.js">
</script>
<script src="js/effects.js"></script>
</head>
<body>
<!-- header -->
<header>
<?php require_once('header.php') ?>
</header>
<!-- Título da página -->
<div class="titulo_pagina font-titulo">
<h1>Sobre</h1>
</div>
<!-- caixa que contém todo o conteúdo -->
<div class="caixa_geral_sobre centralizar_div caixa_crescer">
<div class="caixa_principal_sobre centralizar_div caixa_crescer">
<!-- CAIXA DA IMAGEM E TITULO -->
<div class="caixa_titulo_e_imagem centralizar_div">
<div class="imagem div_esquerda">
<img src="img/missao.png" width="80" height="50" title="missao icon" alt="Imagen não encontrada">
</div>
<div class="titulo-sobre div_direita">
<h1>Missão</h1>
</div>
</div>
<div class="caixa_texto centralizar_div caixa_crescer">
<p>
Nossa missão é revolucionar o e-commerce de bebidas e
atingir positivamente e diretamente o nosso público
jurídico e físico.
</p>
</div>
</div>
<div class="caixa_principal_sobre centralizar_div caixa_crescer">
<!-- CAIXA DA IMAGEM E TITULO -->
<div class="caixa_titulo_e_imagem centralizar_div">
<div class="imagem div_esquerda">
<img src="img/visao.png" width="80" height="50" title="visao icon" alt="Imagen não encontrada">
</div>
<div class="titulo-sobre div_direita">
<h1>Visão</h1>
</div>
</div>
<div class="caixa_texto centralizar_div caixa_crescer">
<p>
Ser referência mundial no comércio de bebidas não alcoólicas e
garantia para todos os serviços prestados aos nossos clientes.
</p>
</div>
</div>
<div class="caixa_principal_sobre centralizar_div caixa_crescer">
<!-- CAIXA DA IMAGEM E TITULO -->
<div class="caixa_titulo_e_imagem centralizar_div">
<div class="imagem div_esquerda">
<img src="img/valores.png" width="80" height="50" title="valores" alt="Imagen não encontrada">
</div>
<div class="titulo-sobre div_direita">
<h1>Valores</h1>
</div>
</div>
<div class="caixa_texto centralizar_div caixa_crescer">
<p>
Inovação - Parceria com nossos Clientes - Confiança do Clientes -
Ética e transparência nas relações e no exercício das atividades -
Valorização do ser humano - Preservaçao do meio ambiente.
</p>
</div>
</div>
</div>
<!-- footer -->
<footer> <?php require_once('footer.html') ?> </footer>
</body>
</html>
<file_sep>/fale_conosco.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>Fale Conosco</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/fale_conosco.css">
<link rel="stylesheet" type="text/css" href="css/titulo_pagina.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- CHAMANDO O JQUERY -->
<script src="js/jquery.js">
</script>
<!-- CHAMANDO O ARQUIVO DE EVENTOS EM JQUERY -->
<script src="js/event.js">
</script>
</head>
<body>
<!-- header -->
<header>
<?php require_once('header.php') ?>
</header>
<!-- Título da página -->
<div class="titulo_pagina font-titulo">
<h1>Fale Conosco</h1>
</div>
<!-- caixa central do fomulario -->
<div class="caixa_central_fl">
<div class="caixa_form_fl bordas-form">
<form action="fale_conosco.php" name="frmFaleConosco" id="frmFaleConosco" method="POST">
<!-- Nome: -->
<div class="campos-form bordas-form">
<input class="bordas-form bordas-sombra" type="text" id="txtNome" name="txtNome" placeholder="Nome completo">
</div>
<!-- E-mail: -->
<div class="campos-form bordas-form">
<input class="bordas-form" type="text" id="txtEmail" name="txtEmail" placeholder="Email">
</div>
<!-- Telefone e Celular -->
<div class="campos-form bordas-form">
<div class="caixa_contato">
<input class="bordas-form bordas-sombra" type="text" id="txtTelefone" name="txtTelefone" placeholder="Telefone">
</div>
<div class="caixa_contato margin-direita-contato">
<input class="bordas-form bordas-sombra" type="text" id="txtCelular" name="txtCelular" placeholder="Celular">
</div>
</div>
<!-- Tipo de Contato-->
<div class="campos-form bordas-form">
<select class="slt-form bordas-form bordas-sombra" id="sltContato" name="sltContato">
<option disabled selected>Selecione:</option>
<option>Crítica</option>
<option>Informação</option>
<option>Dúvida</option>
</select>
</div>
<!-- TextArea -->
<div class="campos-form bordas-form">
<label for="txtObservacao" class="font-texto label">Observação:</label><br>
<textarea class="observacao bordas-form bordas-sombra" id="txtObservacao" name="txtObservacao"></textarea>
</div>
<!-- Botão Enviar -->
<div class="caixa_botao">
<input type="button" id="btnEnviar" name="btnEnviar" value="Enviar">
</div>
</form>
</div>
</div>
<!-- footer -->
<footer> <?php require_once('footer.html')?> </footer>
</body>
</html> | 04977ec24118bd11b300e288663ab169176c131b | [
"PHP"
]
| 13 | PHP | vitoriagoncalvess/pop-soda-drink | 265eca7506f60b1b0bdf5b68cb3da3b438a1adb5 | d6a5028f964d653e70332a7869ffddc130fc7ce4 |
refs/heads/master | <file_sep>package br.com.mobilesaude.cliente;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import br.com.mobilesaude.cliente.source.Campeonato;
/*
*
*
* <script type="text/javascript">
//put this somewhere in "show.html"
//using window onload event to run function
//so function runs after all content has been loaded.
//After refresh this entire script will run again.
// window.onload = function () {
// 'use strict';
//var millisecondsBeforeRefresh = 1000; //Adjust time here
//window.setTimeout(function () {
//refresh the entire document
// document.location.reload();
//}, millisecondsBeforeRefresh);
// };
</script>
*
*
*/
public class CCampeonato{
private static int HTTP_COD_SUCESSO = 200;
public CCampeonato(){
}
public Campeonato inciar(int rodadas) throws JAXBException{
Campeonato c = new Campeonato();
try {
URL url = new URL("http://localhost:8080/Campeonato/ws/servico/campeonato/iniciar?rodadas="+rodadas);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != HTTP_COD_SUCESSO) {
throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
}
InputStream in = con.getInputStream();
InputStreamReader inputStream = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStream);
JAXBContext jaxbContext = JAXBContext.newInstance(Campeonato.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
c = (Campeonato) jaxbUnmarshaller.unmarshal(br);
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return c;
}
public String tratarString(String palavra) {
char one;
StringBuffer n = new StringBuffer( palavra.length() );
for (int i=0; i<palavra.length(); i++) {
one = palavra.charAt(i);
switch( one ) {
case ' ':
n.append('%');
n.append('2');
n.append('0');
break;
default:
n.append( one );
}
}
return n.toString();
}
}<file_sep>package br.com.mobilesaude.main;
import java.util.List;
import javax.xml.bind.JAXBException;
import br.com.mobilesaude.cliente.CCampeonato;
import br.com.mobilesaude.cliente.CGol;
import br.com.mobilesaude.cliente.CGolPost;
import br.com.mobilesaude.cliente.CPartida;
import br.com.mobilesaude.cliente.CTime;
import br.com.mobilesaude.cliente.source.Gol;
import br.com.mobilesaude.cliente.source.Partida;
import br.com.mobilesaude.cliente.source.Time;
public class Main {
public static void main(String[] args) throws JAXBException {
// TODO Auto-generated method stub
CGolPost gol = new CGolPost();
gol.inserir2("Aguero", "42", "1");
}
}
<file_sep>package br.com.mobilesaude.cliente.bean;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.xml.bind.JAXBException;
import br.com.mobilesaude.cliente.CPartida;
import br.com.mobilesaude.cliente.CTime;
import br.com.mobilesaude.cliente.source.Partida;
import br.com.mobilesaude.cliente.source.Time;
@ManagedBean
@ViewScoped
public class Bean {
boolean iniciou;
boolean terminou;
List<Time> times = new ArrayList<Time>();
List<Partida> partidas = new ArrayList<Partida>();
public Bean() throws JAXBException{
CTime ctime = new CTime();
times = ctime.getLista();
CPartida cpartida = new CPartida();
partidas = cpartida.getLista();
if(times.isEmpty()==false){
if( partidas.isEmpty() ){
setIniciou(false);
}else setIniciou(true);
if( partidas.get( partidas.size()-1 ).isAcabou()==true ){
setTerminou(true);
}else setTerminou(false);
}
}
public String nomeTime_novoTime;
public String nomeJogador_novoTime;
public void pegarTime() throws JAXBException{
CTime ctime = new CTime();
ctime.inserir(nomeTime_novoTime, nomeJogador_novoTime);
}
public boolean isIniciou() {
return iniciou;
}
public void setIniciou(boolean iniciou) {
this.iniciou = iniciou;
}
public boolean isTerminou() {
return terminou;
}
public void setTerminou(boolean terminou) {
this.terminou = terminou;
}
public List<Time> getTimes() {
return times;
}
public void setTimes(List<Time> times) {
this.times = times;
}
public List<Partida> getPartidas() {
return partidas;
}
public void setPartidas(List<Partida> partidas) {
this.partidas = partidas;
}
public String getNomeJogador_novoTime() {
return nomeJogador_novoTime;
}
public void setNomeJogador_novoTime(String nomeJogador_novoTime) {
this.nomeJogador_novoTime = nomeJogador_novoTime;
}
public String getNomeTime_novoTime() {
return nomeTime_novoTime;
}
public void setNomeTime_novoTime(String nomeTime_novoTime) {
this.nomeTime_novoTime = nomeTime_novoTime;
}
}
<file_sep>package br.com.mobilesaude.cliente.listas;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import br.com.mobilesaude.cliente.source.Partida;
@XmlRootElement(name = "collection")
@XmlAccessorType(XmlAccessType.FIELD)
public class Partidas {
@XmlElement(name = "partida")
List<Partida> partidas = new ArrayList<Partida>();
public List<Partida> getPartidas() {
return partidas;
}
public void setPartidas(List<Partida> partidas) {
this.partidas = partidas;
}
}
<file_sep>package br.com.mobilesaude.teste.bean;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import br.com.mobilesaude.teste.objetos.Book;
//import javax.faces.bean.ManagedBean;
@ManagedBean
@ViewScoped
public class AdminBooksBean implements Serializable{
private Book product = new Book();
private List<Book> products;
private String mensagem = "Quem é você?";
private String nome;
List<String> frases;
public AdminBooksBean(){
products = new ArrayList<Book>();
System.out.println("AdminBooksBean");
frases = new ArrayList<String>();
frases.add("Andre");
frases.add("ta");
frases.add("Esquecendo");
frases.add("algo");
}
public void save(){
System.out.println("save");
product.mostrar();
}
public Book getProduct() {
System.out.println("getProduct\n");
product.setDescription(product.getTitle());
return product;
}
public List<Book> getProducts() {
System.out.println("getProducts\n");
Book b1 = new Book(1,"titulo1","descricao1",10,new BigDecimal(10));
Book b2 = new Book(2,"titulo2","descricao2",11,new BigDecimal(11));
Book b3 = new Book(3,"titulo3","descricao3",12,new BigDecimal(12));
products.add(b1);
products.add(b2);
products.add(b3);
return this.products;
}
public void setProducts(List<Book> products) {
System.out.println("setProducts\n");
this.products = products;
}
public void setProduct(Book product) {
System.out.println("setProduct\n");
this.product = product;
}
public String getHorario() {
System.out.println("getHorario\n");
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
return "Atualizado em " + sdf.format(new Date());
}
public String getMensagem() {
System.out.println("getMensagem");
return mensagem;
}
public String getNome() {
System.out.println("getNome\n");
return nome;
}
public void setNome(String nome){
System.out.println("setNome\n");
this.nome=nome;
}
public void nomeFoiDigitado() {
System.out.println("nomeFoiDigitado");
System.out.println(nome);
System.out.println("Chamou o botão\n");
}
public List<String> getFrases() {
return frases;
}
public void setFrases(List<String> frases) {
this.frases = frases;
}
}
<file_sep>package br.com.mobilesaude.cliente;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import br.com.mobilesaude.cliente.listas.Times;
import br.com.mobilesaude.cliente.source.Time;
public class CTime {
private static int HTTP_COD_SUCESSO = 200;
public CTime(){
}
public List<Time> getLista() throws JAXBException{
Times times = new Times();
try {
URL url = new URL("http://localhost:8080/Campeonato/ws/servico/time/listar");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != HTTP_COD_SUCESSO) {
throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
}
InputStream in = con.getInputStream();
InputStreamReader inputStream = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStream);
JAXBContext jaxbContext = JAXBContext.newInstance(Times.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
times = (Times) jaxbUnmarshaller.unmarshal(br);
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
times.getTimes().sort(null);
return times.getTimes();
}
public List<Time> alterar(long id, String nome, int pontos, int jogos, int vitorias, int empates, int derrotas, int gp, int gc, int gs, String jogador) throws JAXBException{
Times times = new Times();
try {
String nom, jog;
nom = tratarString(nome);
jog = tratarString(jogador);
URL url = new URL("http://localhost:8080/Campeonato/ws/servico/time/alterar?id="+id+"&nome="+nom+"&pontos="+pontos+"&jogos="+jogos+"&vitorias="+vitorias+"&empates="+empates+"&derrotas="+derrotas+"&gp="+gp+"&gc="+gc+"&gs="+gs+"&jogador="+jog);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != HTTP_COD_SUCESSO) {
throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
}
InputStream in = con.getInputStream();
InputStreamReader inputStream = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStream);
JAXBContext jaxbContext = JAXBContext.newInstance(Times.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
times = (Times) jaxbUnmarshaller.unmarshal(br);
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return times.getTimes();
}
public List<Time> inserir(String nome, String jogador) throws JAXBException{
Times times = new Times();
try {
String nom, jog;
nom = tratarString(nome);
jog = tratarString(jogador);
URL url = new URL("http://localhost:8080/Campeonato/ws/servico/time/inserir?nome="+nom+"&pontos=0&jogos=0&vitorias=0&empates=0&derrotas=0&gp=0&gc=0&gs=0&jogador="+jog);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != HTTP_COD_SUCESSO) {
throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
}
InputStream in = con.getInputStream();
InputStreamReader inputStream = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStream);
JAXBContext jaxbContext = JAXBContext.newInstance(Times.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
times = (Times) jaxbUnmarshaller.unmarshal(br);
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return times.getTimes();
}
public List<Time> fazerGol(long id) throws JAXBException{
Times times = new Times();
try {
URL url = new URL("http://localhost:8080/Campeonato/ws/servico/time/fazerGol?id="+id);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != HTTP_COD_SUCESSO) {
throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
}
InputStream in = con.getInputStream();
InputStreamReader inputStream = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStream);
JAXBContext jaxbContext = JAXBContext.newInstance(Times.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
times = (Times) jaxbUnmarshaller.unmarshal(br);
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return times.getTimes();
}
public List<Time> levarGol(long id) throws JAXBException{
Times times = new Times();
try {
URL url = new URL("http://localhost:8080/Campeonato/ws/servico/time/levarGol?id="+id);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != HTTP_COD_SUCESSO) {
throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
}
InputStream in = con.getInputStream();
InputStreamReader inputStream = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStream);
JAXBContext jaxbContext = JAXBContext.newInstance(Times.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
times = (Times) jaxbUnmarshaller.unmarshal(br);
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return times.getTimes();
}
public List<Time> vencer(long id) throws JAXBException{
Times times = new Times();
try {
URL url = new URL("http://localhost:8080/Campeonato/ws/servico/time/vencer?id="+id);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != HTTP_COD_SUCESSO) {
throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
}
InputStream in = con.getInputStream();
InputStreamReader inputStream = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStream);
JAXBContext jaxbContext = JAXBContext.newInstance(Times.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
times = (Times) jaxbUnmarshaller.unmarshal(br);
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return times.getTimes();
}
public List<Time> empatar(long id) throws JAXBException{
Times times = new Times();
try {
URL url = new URL("http://localhost:8080/Campeonato/ws/servico/time/empatar?id="+id);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != HTTP_COD_SUCESSO) {
throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
}
InputStream in = con.getInputStream();
InputStreamReader inputStream = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStream);
JAXBContext jaxbContext = JAXBContext.newInstance(Times.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
times = (Times) jaxbUnmarshaller.unmarshal(br);
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return times.getTimes();
}
public List<Time> perder(long id) throws JAXBException{
Times times = new Times();
try {
URL url = new URL("http://localhost:8080/Campeonato/ws/servico/time/perder?id="+id);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != HTTP_COD_SUCESSO) {
throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
}
InputStream in = con.getInputStream();
InputStreamReader inputStream = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStream);
JAXBContext jaxbContext = JAXBContext.newInstance(Times.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
times = (Times) jaxbUnmarshaller.unmarshal(br);
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return times.getTimes();
}
public String tratarString(String palavra) {
char one;
StringBuffer n = new StringBuffer( palavra.length() );
for (int i=0; i<palavra.length(); i++) {
one = palavra.charAt(i);
switch( one ) {
case ' ':
n.append('%');
n.append('2');
n.append('0');
break;
default:
n.append( one );
}
}
return n.toString();
}
}<file_sep>package br.com.mobilesaude.cliente;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.w3c.dom.Node;
import br.com.mobilesaude.cliente.listas.Gols;
import br.com.mobilesaude.cliente.source.Gol;
import okhttp3.FormBody;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class CGolPost {
public void inserir(String artilheiro, String idTime, String idPartida){
@SuppressWarnings("unused")
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("artilheiro", artilheiro)
.addFormDataPart("idTime", idTime)
.addFormDataPart("idPartida", idPartida)
.build();
Request request = new Request.Builder()
.url("http://localhost:8080/Campeonato/ws/servico/gol/inserir2")
.method("POST", RequestBody.create(null, new byte[0]) )
.post(requestBody)
.build();
}
//funciona
public void inserir2(String artilheiro, String idTime, String idPartida) throws JAXBException{
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("artilheiro", artilheiro)
.add("idTime", idTime)
.add("idPartida", idPartida)
.build();
Request request = new Request.Builder()
.url("http://localhost:8080/Campeonato/ws/servico/gol/inserir2")
.post(formBody)
.build();
try {
Response response = client.newCall(request).execute();
String xmlString = new String(response.body().string());
//System.out.println(response.body().string());
//System.out.println(response.body().string());
///response.body().t
// convert String into InputStream
// InputStream is = new ByteArrayInputStream(response.body().toString().getBytes());
// read it with BufferedReader
// BufferedReader br = new BufferedReader(new InputStreamReader(is) );
/*JAXBContext context = JAXBContext.newInstance( Gols.class );
Unmarshaller unMarshaller = context.createUnmarshaller();
Gols param = (Gols) unMarshaller.unmarshal( br );*/
//String xmlString = response.body().string();
JAXBContext jaxbContext = JAXBContext.newInstance(Gols.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader( xmlString );
Gols gols = (Gols) unmarshaller.unmarshal(reader);
gols.getGols().get(0).mostrar();
// Do something with the response.
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>package br.com.mobilesaude.cliente;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import br.com.mobilesaude.cliente.listas.Partidas;
import br.com.mobilesaude.cliente.source.Partida;
import br.com.mobilesaude.cliente.source.Time;
public class CPartida {
private static int HTTP_COD_SUCESSO = 200;
public CPartida(){
}
public List<Partida> getLista() throws JAXBException{
Partidas partidas = new Partidas();
try {
URL url = new URL("http://localhost:8080/Campeonato/ws/servico/partida/listar");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != HTTP_COD_SUCESSO) {
throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
}
InputStream in = con.getInputStream();
InputStreamReader inputStream = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStream);
JAXBContext jaxbContext = JAXBContext.newInstance(Partidas.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
partidas = (Partidas) jaxbUnmarshaller.unmarshal(br);
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return partidas.getPartidas();
}
public List<Partida> alterarPartida(long id, long ida, long idb, int placara, int placarb, boolean acabou ) throws JAXBException{
Partidas partidas = new Partidas();
try {
URL url = new URL("http://localhost:8080/Campeonato/ws/servico/partida/alterar?id="+id+"&idTimeA="+ida+"&idTimeB="+idb+"&placarA="+placara+"&placarB="+placarb+"&acabou="+acabou);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != HTTP_COD_SUCESSO) {
throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
}
InputStream in = con.getInputStream();
InputStreamReader inputStream = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStream);
JAXBContext jaxbContext = JAXBContext.newInstance(Partidas.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
partidas = (Partidas) jaxbUnmarshaller.unmarshal(br);
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return partidas.getPartidas();
}
public List<Partida> inserirPartida(long ida, long idb) throws JAXBException{
Partidas partidas = new Partidas();
try {
URL url = new URL("http://localhost:8080/Campeonato/ws/servico/partida/insere?idTimeA="+ida+"&idTimeB="+idb+"&placarA=0&placarB=0&acabou=false");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != HTTP_COD_SUCESSO) {
throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
}
InputStream in = con.getInputStream();
InputStreamReader inputStream = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStream);
JAXBContext jaxbContext = JAXBContext.newInstance(Partidas.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
partidas = (Partidas) jaxbUnmarshaller.unmarshal(br);
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return partidas.getPartidas();
}
public List<Partida> golA() throws JAXBException{
List<Partida> partidas = getLista();
long id = 0;
if(!partidas.isEmpty()){
for(Partida p : partidas){
if(p.isAcabou()==false){
id = p.getId();
break;
}
}
}
Partida atual = partidas.get( (int) (id - 1) );
Time tA, tB;
tA = atual.getTimeA();
tB = atual.getTimeB();
int placarA = atual.getPlacarA();
atual.setPlacarA( placarA + 1 );
return alterarPartida(id, tA.getId(), tB.getId(), atual.getPlacarA(), atual.getPlacarB(), atual.isAcabou());
}
public List<Partida> golB() throws JAXBException{
List<Partida> partidas = getLista();
long id = 0;
if(!partidas.isEmpty()){
for(Partida p : partidas){
if(p.isAcabou()==false){
id = p.getId();
break;
}
}
}
Partida atual = partidas.get( (int) (id - 1) );
Time tA, tB;
tA = atual.getTimeA();
tB = atual.getTimeB();
int placarB = atual.getPlacarB();
atual.setPlacarB( placarB + 1 );
return alterarPartida(id, tA.getId(), tB.getId(), atual.getPlacarA(), atual.getPlacarB(), atual.isAcabou());
}
public List<Partida> finalizar(long id) throws JAXBException{
Partidas partidas = new Partidas();
try {
URL url = new URL("http://localhost:8080/Campeonato/ws/servico/partida/finalizar?id="+id);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != HTTP_COD_SUCESSO) {
throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
}
InputStream in = con.getInputStream();
InputStreamReader inputStream = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStream);
JAXBContext jaxbContext = JAXBContext.newInstance(Partidas.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
partidas = (Partidas) jaxbUnmarshaller.unmarshal(br);
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return partidas.getPartidas();
}
public String tratarString(String palavra) {
char one;
StringBuffer n = new StringBuffer( palavra.length() );
for (int i=0; i<palavra.length(); i++) {
one = palavra.charAt(i);
switch( one ) {
case ' ':
n.append('%');
n.append('2');
n.append('0');
break;
default:
n.append( one );
}
}
return n.toString();
}
}
<file_sep>package br.com.mobilesaude.cliente.bean;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBException;
import br.com.mobilesaude.cliente.CCampeonato;
import br.com.mobilesaude.cliente.CGol;
import br.com.mobilesaude.cliente.CPartida;
import br.com.mobilesaude.cliente.CTime;
import br.com.mobilesaude.cliente.source.Artilheiro;
import br.com.mobilesaude.cliente.source.Gol;
import br.com.mobilesaude.cliente.source.Partida;
import br.com.mobilesaude.cliente.source.Time;
import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
@ManagedBean
@ViewScoped
public class CampeonatoBean {
boolean iniciou;
boolean terminou;
List<Time> times = new ArrayList<Time>();
List<Partida> partidas = new ArrayList<Partida>();
List<Gol> gols = new ArrayList<Gol>();
List<Artilheiro> artilheiros = new ArrayList<Artilheiro>();
String mensagemFimPartida;
List<Artilheiro> artilheiros2 = new ArrayList<Artilheiro>();
public CampeonatoBean() throws JAXBException{
CTime ctime = new CTime();
times = ctime.getLista();
CPartida cpartida = new CPartida();
partidas = cpartida.getLista();
CGol cgol = new CGol();
gols = cgol.getLista();
for( int i=0; i<times.size(); i++ ){
times.get(i).setPosicao(i+1);
}
if(!partidas.isEmpty()){
setTerminou(partidas.get(partidas.size()-1).isAcabou());
for( Gol gol : gols ){
int i = (int) (gol.getIdPartida() - 1) ;
Partida golPartida = partidas.get( i );
//setantdo times e partidas de cada gol
gol.setTime( buscarTim( gol.getIdTime() , times ) );
gol.setPartida( partidas.get( (int) ( gol.getIdPartida() - 1) ) );
//gols de cada partida
golPartida.addGol(gol);
//gols do campeonato
//gols.add(gol);
Artilheiro art = new Artilheiro();
art.setNome( gol.getNomeArtilheiro() );
art.setTime( buscarTim( gol.getIdTime() , times ) );
//System.out.println( art.getNome()+" "+art.getTime().getNome()+" "+times.get( (int) ( gol.getIdTime() - 1) ).getNome() );
art.setGols(1);
addArtilhiero(art, artilheiros);
}
artilheiros.sort(null);
for( int i=0; i<artilheiros.size(); i++ ){
artilheiros.get(i).setPosicao(i+1);
if( !artilheiros.get(i).getNome().equals("-") && !artilheiros.get(i).getNome().equals("WO")){
artilheiros2.add( artilheiros.get(i) );
}
}
for( int i = 0; i<artilheiros2.size(); i++ ){
artilheiros2.get(i).setPosicao(i+1);
}
long idpMax = partidas.get(partidas.size()-1).getId();
for(Partida p : partidas){
if(p.isAcabou()==false){
partidaAtual = p;
if(partidaAtual.getPlacarA() > partidaAtual.getPlacarB()){
mensagemFimPartida = partidaAtual.getTimeA().getNome()+" vence ";
}
if(partidaAtual.getPlacarA() < partidaAtual.getPlacarB()){
mensagemFimPartida = partidaAtual.getTimeB().getNome()+" vence ";
}
if(partidaAtual.getPlacarA() == partidaAtual.getPlacarB()){
mensagemFimPartida = " EMPATAR ";
}
int idp = (int) p.getId();
if(idp<idpMax){
proxPartida = partidas.get( idp );
}
if(idp>1){
anterPartida = partidas.get( idp - 2);
}
break;
}
}
}
}
public void refresh() {
times.sort(null);
FacesContext context = FacesContext.getCurrentInstance();
Application application = context.getApplication();
ViewHandler viewHandler = application.getViewHandler();
UIViewRoot viewRoot = viewHandler.createView(context, context.getViewRoot().getViewId());
context.setViewRoot(viewRoot);
context.renderResponse();
}
public String nomeTime_novoTime;
public String nomeJogador_novoTime;
public void pegarTime() throws JAXBException{
CTime ctime = new CTime();
if( !nomeTime_novoTime.isEmpty() && !nomeJogador_novoTime.isEmpty() ){
ctime.inserir(nomeTime_novoTime, nomeJogador_novoTime);
refresh();
}
}
public int rodadas;
public void gerarPartidas() throws JAXBException{
CCampeonato ccamp = new CCampeonato();
if(rodadas==1 || rodadas==2){
ccamp.inciar(rodadas);
refresh();
}
}
public Partida partidaAtual;
public Partida proxPartida;
public Partida anterPartida;
String artilheiro = null;
public void golA() throws JAXBException{
if(!artilheiro.isEmpty()){
CPartida p = new CPartida();
partidas = p.golA();
CGol cgol = new CGol();
cgol.inserir(artilheiro, partidaAtual.getTimeA().getId(),partidaAtual.getId());
//System.out.println(artilheiro+" "+partidaAtual.getId()+" "+partidaAtual.getTimeA().getId());
CTime t = new CTime();
times = t.fazerGol(partidaAtual.getTimeA().getId());
times = t.levarGol(partidaAtual.getTimeB().getId());
refresh();
}
}
public void golB() throws JAXBException{
if(!artilheiro.isEmpty()){
CPartida p = new CPartida();
partidas = p.golB();
CGol cgol = new CGol();
cgol.inserir(artilheiro, partidaAtual.getTimeB().getId(),partidaAtual.getId());
//System.out.println(artilheiro+" "+partidaAtual.getId()+" "+partidaAtual.getTimeB().getId());
CTime t = new CTime();
times = t.fazerGol(partidaAtual.getTimeB().getId());
times = t.levarGol(partidaAtual.getTimeA().getId());
refresh();
}
}
public Time buscarTim(long id, List<Time> lista){
for(Time t : lista){
if( t.getId() == id ){
return t;
}
}
return null;
}
public Artilheiro buscarArt( Artilheiro art, List<Artilheiro> lista ){
for(Artilheiro a : lista){
if( a.getNome().equals( art.getNome() ) ){
return a;
}
}
return null;
}
public void addArtilhiero(Artilheiro art, List<Artilheiro> lista){
Artilheiro busca = buscarArt( art, lista );
if(busca==null){
artilheiros.add(art);
}
else{
int gols = busca.getGols();
gols++;
busca.setGols(gols);
}
}
public void finalizarPartida() throws JAXBException{
CPartida p = new CPartida();
p.finalizar(partidaAtual.getId());
refresh();
}
public boolean isIniciou() {
return iniciou;
}
public void setIniciou(boolean iniciou) {
this.iniciou = iniciou;
}
public boolean isTerminou() {
return terminou;
}
public void setTerminou(boolean terminou) {
this.terminou = terminou;
}
public List<Time> getTimes() {
return times;
}
public void setTimes(List<Time> times) {
this.times = times;
}
public List<Partida> getPartidas() {
return partidas;
}
public void setPartidas(List<Partida> partidas) {
this.partidas = partidas;
}
public String getNomeJogador_novoTime() {
return nomeJogador_novoTime;
}
public void setNomeJogador_novoTime(String nomeJogador_novoTime) {
this.nomeJogador_novoTime = nomeJogador_novoTime;
}
public String getNomeTime_novoTime() {
return nomeTime_novoTime;
}
public void setNomeTime_novoTime(String nomeTime_novoTime) {
this.nomeTime_novoTime = nomeTime_novoTime;
}
public int getRodadas() {
return rodadas;
}
public void setRodadas(int rodadas) {
this.rodadas = rodadas;
}
public Partida getPartidaAtual() {
return partidaAtual;
}
public void setPartidaAtual(Partida partidaAtual) {
this.partidaAtual = partidaAtual;
}
public Partida getProxPartida() {
return proxPartida;
}
public void setProxPartida(Partida proxPartida) {
this.proxPartida = proxPartida;
}
public Partida getAnterPartida() {
return anterPartida;
}
public void setAnterPartida(Partida anterPartida) {
this.anterPartida = anterPartida;
}
public String getArtilheiro() {
return artilheiro;
}
public void setArtilheiro(String artilheiro) {
this.artilheiro = artilheiro;
}
public List<Gol> getGols() {
return gols;
}
public void setGols(List<Gol> gols) {
this.gols = gols;
}
public List<Artilheiro> getArtilheiros() {
return artilheiros;
}
public void setArtilheiros(List<Artilheiro> artilheiros) {
this.artilheiros = artilheiros;
}
public String getMensagemFimPartida() {
return mensagemFimPartida;
}
public void setMensagemFimPartida(String mensagemFimPartida) {
this.mensagemFimPartida = mensagemFimPartida;
}
public List<Artilheiro> getArtilheiros2() {
return artilheiros2;
}
public void setArtilheiros2(List<Artilheiro> artilheiros2) {
this.artilheiros2 = artilheiros2;
}
}
| 0b722cf953aca9a1506d7e71d4bca8e7cfbe7d7d | [
"Java"
]
| 9 | Java | andreluizgomesrangel/campeonato_web | a98f0fc34a6c04b747d1b68a95b097c1fd437256 | 7a005117e741b2f28338ef621286ed950ec1097d |
refs/heads/master | <file_sep>#pragma once
#ifndef MATRIX_VISION_H
#define MATRIX_VISION_H
#include <vector>
#include <Common/exampleHelper.h>
#include <mvIMPACT_CPP/mvIMPACT_acquire.h>
namespace mv
{
class MvDeviceManager
{
private:
static bool is_CameraManager_initialized;
mvIMPACT::acquire::DeviceManager device_manager_;
std::vector<unsigned int> device_IDs_;
std::map<uint32_t, mvIMPACT::acquire::Device*> camera_devices_;
public:
MvDeviceManager();
~MvDeviceManager();
const std::vector<unsigned int>& get_device_IDs();
mvIMPACT::acquire::Device* create_device(unsigned int id);
bool single_capture(uint16_t device_id, int& width, int& height, std::vector<uint8_t>& pixels);
};
class MvDevice
{
private:
mvIMPACT::acquire::Device* device_;
mvIMPACT::acquire::FunctionInterface *mvInterface_;
mvIMPACT::acquire::Request* currentImage_;
mvIMPACT::acquire::Request* previousImage_;
int timeout_ms = 3000;
bool is_acquisition_started;
public:
MvDevice(mvIMPACT::acquire::Device* device);
~MvDevice();
mvIMPACT::acquire::Request* capture();
void request_next_image();
private:
void start_acquisition();
void stop_acquisition();
template<class _Tx, typename _Ty>
bool supports_value(const _Tx& prop, const _Ty& value)
{
if (prop.hasDict()) {
typename std::vector<_Ty> sequence;
prop.getTranslationDictValues(sequence);
return std::find(sequence.begin(), sequence.end(), value) != sequence.end();
}
if (prop.hasMinValue() && (prop.getMinValue() > value)) {
return false;
}
if (prop.hasMaxValue() && (prop.getMaxValue() < value)) {
return false;
}
return true;
}
};
extern MvDeviceManager mvDeviceManager;
}
#endif
<file_sep>#include <GL\glew.h>
#include "entity_image.h"
#include "resources.h"
EntityImage::EntityImage(const glm::ivec2& size, const glm::vec2& position) : Entity("EntityImage"), position_(position)
{
{
program_ = std::make_unique<glsl::Program>(glsl::ShaderPathList{ resources.get_path("rgb.vert"), resources.get_path("rgb.frag") },
glsl::AttributeList{ glsl::VERTICES, glsl::TEXTURE_COORD });
program_->linkUniform({ glsl::VIEW_PROJECTION, glsl::MODEL});
texture_ = std::make_unique<gl::Texture>(gl::FORMAT_RGB, size);
}
{
std::vector<glm::vec2> uv{ { 0.0f, 0.0f },{ 1.0f, 0.0f },{ 0.0f, 1.0f },{ 1.0f, 1.0f } };
std::vector<uint32_t> indices{ 0, 1, 2, 2, 1, 3 };
float rec_size = 1.0f;
std::vector<glm::vec2> vertices = std::vector<glm::vec2>{ { -rec_size, rec_size },{ rec_size, rec_size },{ -rec_size, -rec_size },{ rec_size, -rec_size } };
vao_ = std::make_unique<gl::VAO>();
vao_->bind();
vao_->add_attribute(glsl::VERTICES, vertices.data(), vertices.size() * sizeof(vertices.front()), 2, program_->attreibute_id(glsl::VERTICES), false);
vao_->add_attribute(glsl::TEXTURE_COORD, uv.data(), uv.size() * sizeof(uv.front()), 2, program_->attreibute_id(glsl::TEXTURE_COORD), false);
vao_->add_indices(indices.data(), indices.size() * sizeof(indices.front()), indices.size());
vao_->unbind();
}
}
EntityImage::~EntityImage()
{
}
void EntityImage::position(const glm::vec2 new_pos)
{
position_ = new_pos;
}
const glm::vec2 & EntityImage::position() const
{
return position_;
}
void EntityImage::set_image(const glm::ivec2 & size, const std::vector<uint8_t>& pixels)
{
if (size != glm::ivec2(0)) {
if (texture_->size() != size)
texture_ = std::make_unique<gl::Texture>(gl::FORMAT_RGB, size, pixels);
else
{
texture_->set_data(pixels);
}
}
}
void EntityImage::update()
{
}
void EntityImage::draw(const glm::mat4& projection_view)
{
texture_->bind();
program_->bind();
program_->setUniform(glsl::VIEW_PROJECTION, projection_view);
program_->setUniform(glsl::MODEL, position_);
vao_->bind();
glDrawElements(GL_TRIANGLES, (GLsizei)vao_->index_size(), GL_UNSIGNED_INT, nullptr);
vao_->unbind();
program_->unbind();
texture_->unbind();
}
<file_sep>#pragma once
#ifndef GUI_OBJECT_H
#define GUI_OBJECT_H
#include "headers.h"
#include "gl_vao.h"
#include "glsl_program.h"
#include "gl_texture.h"
class GUI_Object
{
private:
uint16_t id_;
protected:
std::string type_;
std::string text_;
glm::vec2 pos_;
std::unique_ptr<gl::VAO> vao_;
std::unique_ptr<glsl::Program> program_;
std::unique_ptr<gl::Texture> texture_;
public:
GUI_Object() {
id_ = unique_GUI_Object_id();
}
GUI_Object(const std::string& drived_type) : type_(drived_type) {
id_ = unique_GUI_Object_id();
}
virtual ~GUI_Object() {}
const uint16_t& id() { return id_; }
const std::string& type() { return type_; }
const std::string& text() { return text_; }
const glm::vec2& pos() { return pos_; }
virtual void text(const std::string& new_text) { };
virtual void pos(const glm::vec2& new_pos) { }
virtual void draw(const glm::mat4& projection) = 0;
private:
uint16_t unique_GUI_Object_id() {
static uint16_t uniqueGUIObjectId = 0;
return uniqueGUIObjectId++;
}
};
#endif<file_sep>#include <GL\glew.h>
#include "gui_static_text.h"
#include "resources.h"
#include "character_generator.h"
GUI_StaticText::GUI_StaticText(const glm::ivec2 position, core::FontName font_name, uint16_t font_size, const std::string& text, const glm::vec3& color) :
GUI_Object("GUI_StaticText")
{
{
pos_ = position;
text_ = text;
font_name_ = font_name;
font_size_ = font_size;
glm::ivec2 data_size;
std::vector<uint8_t> data;
std::tie(data_size, data) = characterGen.text_to_bitmap(font_name, font_size, text_);
program_ = std::make_unique<glsl::Program>(glsl::ShaderPathList{ resources.get_path("text.vert"), resources.get_path("text.frag") },
glsl::AttributeList{ glsl::VERTICES, glsl::TEXTURE_COORD });
program_->linkUniform({ glsl::MODEL, glsl::PROJECTION, glsl::SCALE, glsl::COLOR });
program_->bind();
program_->setUniform(glsl::MODEL, glm::vec2(pos_.x, pos_.y));
program_->setUniform(glsl::COLOR, color);
program_->setUniform(glsl::SCALE, glm::vec2(data_size.x, data_size.y));
texture_ = std::make_unique<gl::Texture>(gl::FORMAT_R8, data_size, data);
}
{
std::vector<glm::vec2> uv{ { 0.0f, 1.0f },{ 0.0f, 0.0f },{ 1.0f, 1.0f },{ 1.0f, 0.0f } };
std::vector<uint32_t> indices{ 1, 0, 2, 1, 2, 3 };
std::vector<glm::vec2> vertices{ { 0.0f, 0.0f },{ 0.0f, 1.0f },{ 1.0f, 0.0f },{ 1.0f, 1.0f } };
vao_ = std::make_unique<gl::VAO>();
vao_->bind();
vao_->add_attribute(glsl::VERTICES, &vertices[0][0], vertices.size() * sizeof(vertices.front()), 2, program_->attreibute_id(glsl::VERTICES), false);
vao_->add_attribute(glsl::TEXTURE_COORD, &uv[0][0], uv.size() * sizeof(uv.front()), 2, program_->attreibute_id(glsl::TEXTURE_COORD), false);
vao_->add_indices(indices.data(), indices.size() * sizeof(indices.front()), indices.size());
vao_->unbind();
}
}
GUI_StaticText::~GUI_StaticText()
{
}
void GUI_StaticText::text(const std::string & new_text)
{
text_ = new_text;
glm::ivec2 data_size;
std::vector<uint8_t> data;
std::tie(data_size, data) = characterGen.text_to_bitmap(font_name_, font_size_, text_);
texture_ = std::make_unique<gl::Texture>(gl::FORMAT_R8, data_size, data);
}
void GUI_StaticText::pos(const glm::vec2 & new_pos)
{
}
void GUI_StaticText::draw(const glm::mat4& projection)
{
program_->bind();
program_->setUniform(glsl::PROJECTION, projection);
texture_->bind();
vao_->bind();
glDrawElements(GL_TRIANGLES, (GLsizei)vao_->index_size(), GL_UNSIGNED_INT, nullptr);
vao_->unbind();
program_->unbind();
texture_->unbind();
}
<file_sep>#include "gl_utility.h"
#include "image_viewer.h"
#include <QtWidgets/QApplication>
#include <QtGui/QMouseEvent>
#include <QtGui/QKeyEvent>
#include <QtWidgets/QMessageBox>
#include <QtCore/QTimer>
#include "mathematics.h"
#include "time_utility.h"
ImageViewer::ImageViewer(QWidget *parent)
: QGLWidget(parent), is_mouse_middle_released(true)
{
this->setMouseTracking(true);
this->setFocusPolicy(Qt::StrongFocus);
QGLFormat glFormat;
glFormat.setDepthBufferSize(24);
glFormat.setStencilBufferSize(8);
glFormat.setDoubleBuffer(true);
glFormat.setSwapInterval(0);
glFormat.setProfile(QGLFormat::OpenGLContextProfile::CoreProfile);
this->setFormat(glFormat);
}
ImageViewer::~ImageViewer()
{
}
void ImageViewer::set_viewer_image(const glm::ivec2 & image_size, const std::vector<uint8_t>& pixels)
{
this->makeCurrent();
image_->set_image(image_size, pixels);
}
void ImageViewer::initializeGL()
{
gl::initialize();
this->makeCurrent();
gl::clearColor(0.2f, 0.2f, 0.2f, 1.0f);
gl::enable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
gl::enable(GL_TEXTURE_2D);
glCullFace(GL_FRONT_AND_BACK);
camera = std::make_unique<Camera>(glm::vec3(0, 0, 1.3f), glm::vec3(0.0f), glm::ivec2(this->width(), this->height()), 0.0f, 1000000.0f, Camera::PERSPECTIVE);
image_ = std::make_shared<EntityImage>(glm::ivec2(100), glm::vec2(0, 0));
}
void ImageViewer::paintGL()
{
this->makeCurrent();
gl::clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
image_->draw(camera->projection() * camera->view());
}
void ImageViewer::resizeGL(int w, int h) {
camera->viewport(glm::ivec2(w, h));
gl::viewport(0, 0, w, h);
}
void ImageViewer::mouseMoveEvent(QMouseEvent *e) {
mouse_delta = e->pos() - mouse_prev;
if (!is_mouse_middle_released)
{
auto ratio = 0.00255f * glm::length(camera->position() - camera->target());
camera->translate(glm::vec3(-mouse_delta.x() * ratio, mouse_delta.y() * ratio, 0));
}
mouse_prev = e->pos();
update();
}
void ImageViewer::mousePressEvent(QMouseEvent *e) {
if (e->button() == Qt::MouseButton::MidButton)
is_mouse_middle_released = false;
update();
}
void ImageViewer::mouseReleaseEvent(QMouseEvent *e) {
if (e->button() == Qt::MouseButton::MidButton)
is_mouse_middle_released = true;
update();
}
void ImageViewer::mouseDoubleClickEvent(QMouseEvent * e) {
}
void ImageViewer::wheelEvent(QWheelEvent *e) {
QPoint numPixels = e->pixelDelta();
QPoint numDegrees = e->angleDelta() / 8;
if (e->angleDelta().y() > 0)
camera->zoom_in();
else
camera->zoom_out();
update();
e->accept();
}
void ImageViewer::keyPressEvent(QKeyEvent *e) {
}
void ImageViewer::keyReleaseEvent(QKeyEvent *e) {
}
<file_sep>#pragma once
#ifndef TIME_UTILITY_H
#define TIME_UTILITY_H
#include "headers.h"
namespace core
{
using Clock = std::chrono::system_clock;
typedef union
{
std::uint64_t value;
struct
{
std::uint64_t year : 11; // max number 2048
std::uint64_t day : 5; // max number 32
std::uint64_t month : 4; // max number 16
std::uint64_t hour : 5; // max number 32
std::uint64_t minute : 6; // max number 64
std::uint64_t second : 6; // max number 64
std::uint64_t millisecond : 10; // max number 1024
//17 bits still unused
};
} TimeStamp;
inline TimeStamp time_stamp()
{
auto current_time = Clock::now();
auto epoch = current_time.time_since_epoch();
epoch -= std::chrono::duration_cast<std::chrono::seconds>(epoch);
auto ctime = Clock::to_time_t(current_time);
auto local_time = std::localtime(&ctime);
TimeStamp stamp;
stamp.year = local_time->tm_year + 1900;
stamp.month = local_time->tm_mon + 1;
stamp.day = local_time->tm_mday;
stamp.hour = local_time->tm_hour;
stamp.minute = local_time->tm_min;
stamp.second = local_time->tm_sec;
stamp.millisecond = static_cast<unsigned>(epoch / std::chrono::milliseconds(1));
return stamp;
}
inline std::chrono::system_clock::time_point now()
{
return Clock::now();
}
}
#endif // !TIME_UTILITY_H
<file_sep>#ifndef SESSIONINFO_H
#define SESSIONINFO_H
#include <QDialog>
#include "ui_sessioninfo.h"
class SessionInfo : public QDialog
{
Q_OBJECT
public:
SessionInfo(QWidget *parent = 0);
~SessionInfo();
private slots:
void on_btn_load_clicked();
void on_btn_start_clicked();
void updateFullPath(const QString& text);
public:
Ui::SessionInfo *ui;
};
#endif // SESSIONINFO_H
<file_sep>#ifndef SESSION_H
#define SESSION_H
#include "headers.h"
#include "time_utility.h"
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QRadiobutton>
#include <QtWidgets/QFrame>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QFormLayout>
#include <QtWidgets/QGroupBox>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpinBox>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
#include <QtCore/QTimer>
#include <QDir>
class Session : public QGroupBox
{
Q_OBJECT
private:
bool is_started_;
bool is_paused_;
bool interval_reached_;
uint32_t save_counter_;
std::string session_path_;
uint32_t save_index_;
core::Clock::time_point current_time;
core::Clock::time_point next_capture_time;
core::Clock::time_point finish_time;
public:
QTimer* timer_next_capture;
QVBoxLayout *session_layout;
QHBoxLayout *path_Layout;
QSpinBox *interval;
QSpinBox *duration;
QPushButton *path_select;
QLineEdit *path;
QLabel *label_interval;
QCheckBox *with_duration;
QCheckBox *with_folder;
QGroupBox *numbering_box;
QVBoxLayout *numbering_box_layout;
QRadioButton *numberring_0;
QRadioButton *numberring_from_files;
QRadioButton *numberring_custom;
QLineEdit *custom_numbering_edit;
QHBoxLayout *custom_numbering_Layout;
QLabel *label_name;
QLineEdit *name;
QPushButton *start_stop;
QPushButton *paus_resume;
QGroupBox *settings_box;
QGroupBox *info_box;
QVBoxLayout *settings_box_Layout;
QVBoxLayout *info_box_Layout;
QLabel *start_time_label;
QLabel *finish_time_label;
QLabel *next_capture_time_label;
public:
Session(QString title, QWidget *parent);
~Session();
private slots:
void start_stop_clicked();
void paus_resume_clicked();
void path_select_clicked();
void count_duraion(int state);
void check_capture_time();
void custom_numbering_state(bool state);
public:
bool must_save();
std::string full_save_path();
private:
uint32_t get_filename_index(QDir& dir);
void start();
void stop();
void paus();
void resume();
};
#endif // SESSION_H
<file_sep>#define GENERATE_ENUM_STRINGS // Start string generation
#include "enums.h"
#undef GENERATE_ENUM_STRINGS // Stop string generation<file_sep>/****************************************************************************
** Resource object code
**
** Created by: The Resource Compiler for Qt version 5.8.0
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
static const unsigned char qt_resource_data[] = {
// E:/yashar/github/capture_mv_BlueCougar-xd/capture_mv_BlueCougar-xd/Resources/folder.png
0x0,0x0,0x7,0xa0,
0x89,
0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,
0x0,0x0,0x80,0x0,0x0,0x0,0x80,0x8,0x6,0x0,0x0,0x0,0xc3,0x3e,0x61,0xcb,
0x0,0x0,0x0,0x4,0x73,0x42,0x49,0x54,0x8,0x8,0x8,0x8,0x7c,0x8,0x64,0x88,
0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,
0x1,0x0,0x9a,0x9c,0x18,0x0,0x0,0x7,0x42,0x49,0x44,0x41,0x54,0x78,0x9c,0xed,
0xdd,0x6f,0x88,0x1c,0x77,0x19,0x7,0xf0,0xef,0xf3,0xec,0x6c,0x37,0x17,0x2f,0x85,
0xf6,0x76,0x5b,0xa2,0x56,0x11,0x49,0x2d,0xb4,0xd6,0x9e,0x8a,0x20,0x24,0x24,0x2a,
0x25,0xf5,0x45,0xdb,0xbc,0x68,0x24,0xd0,0x17,0x12,0xb9,0xa8,0x8d,0xa2,0x42,0xb,
0x15,0xbd,0xdb,0xcd,0x5c,0xfe,0xe8,0x9b,0x22,0xb5,0x94,0xc6,0x54,0x8,0x68,0x41,
0x25,0x52,0x4a,0xb,0xb5,0x35,0x58,0xd2,0x78,0x2f,0x84,0xca,0xb5,0x29,0x2d,0x25,
0x7,0xa5,0x2d,0x14,0x8f,0x64,0x12,0xcb,0xe9,0x65,0x73,0x97,0x99,0x7d,0x1e,0x5f,
0xe4,0xee,0x9c,0xdd,0xdc,0xee,0xed,0xec,0xbf,0xdf,0xed,0xce,0xf3,0x81,0xc0,0xcd,
0x6f,0x67,0x76,0xbe,0x64,0xbe,0xf9,0xed,0xee,0xcc,0xdc,0x6,0x30,0xc6,0x18,0x63,
0x8c,0x31,0xc6,0x18,0x63,0x8c,0x31,0xc6,0x18,0x63,0x8c,0x31,0xc6,0x18,0x63,0xcc,
0xa0,0xa1,0xda,0x81,0xc2,0xf8,0xe2,0x17,0x94,0x79,0x8c,0x80,0xbb,0x5,0xf2,0x49,
0x6,0x7f,0xcc,0x45,0xb0,0x56,0x9,0xe1,0x6b,0x17,0xfd,0xec,0x29,0xd7,0x39,0xfa,
0x85,0xb7,0xfc,0xc3,0xa7,0x4b,0xba,0xa1,0xac,0xd1,0xe3,0x80,0xec,0xa3,0xa5,0x62,
0x30,0xd8,0x5d,0xb2,0x16,0xb1,0xe2,0x0,0x80,0x1d,0x8e,0x63,0xf4,0xd,0x2,0x56,
0xe,0xfe,0x5f,0x1,0x6c,0x73,0x9c,0xa7,0x23,0x6c,0x16,0x68,0x1e,0x3,0x40,0x59,
0xa3,0x27,0x30,0x20,0x7,0x1f,0x58,0x99,0x5,0x4c,0x13,0x28,0x3f,0xbe,0x38,0x4a,
0xcc,0xd3,0xae,0x83,0x74,0x9a,0xcd,0x2,0xcd,0x61,0x30,0x8f,0xb9,0xe,0xd1,0xd,
0x36,0xb,0x34,0x87,0x9,0xf8,0x86,0xeb,0x10,0x5d,0xb2,0x7d,0xa4,0x14,0xee,0x70,
0x1d,0x62,0xbd,0x63,0x11,0xb9,0xc5,0x75,0x88,0x6e,0xb1,0x59,0x60,0x6d,0xcc,0xcc,
0x1b,0x5d,0x87,0xe8,0x22,0x9b,0x5,0xd6,0xd0,0x7f,0x1f,0xf4,0x13,0xb2,0x59,0xa0,
0xb1,0x81,0x2f,0x0,0x6c,0x16,0x68,0x28,0xd,0x5,0xb0,0x59,0xa0,0x81,0x54,0x14,
0x0,0x36,0xb,0xd4,0x95,0x96,0x2,0xd8,0x2c,0x50,0x47,0x6a,0xa,0x0,0x9b,0x5,
0x56,0x95,0xa6,0x2,0xd8,0x2c,0xb0,0xa,0x2a,0x14,0x43,0x75,0x1d,0xc2,0x24,0x21,
0x21,0x84,0xdf,0x53,0xc2,0xdf,0x88,0xe5,0x58,0xe0,0xe7,0xde,0x68,0xe7,0xd9,0xac,
0x0,0xfd,0x4e,0xf0,0xb4,0x97,0xf1,0x7e,0x32,0xeb,0x53,0xb9,0x95,0xcd,0x53,0xf5,
0x12,0x30,0x90,0x18,0xfb,0x22,0x8d,0x5e,0xda,0x5c,0xd2,0x96,0xce,0xe8,0x5a,0x1,
0x6,0xc3,0xb6,0x48,0xa3,0xc7,0x5b,0xd9,0xd0,0xa,0x30,0x38,0xc6,0xf2,0xa5,0xc5,
0x2f,0x26,0xdd,0xc8,0xa,0x30,0x48,0x94,0xf7,0x25,0xdd,0xc4,0xa,0x30,0x40,0x48,
0xf0,0xf5,0xa4,0xdb,0x58,0x1,0x6,0x9,0xcb,0x67,0x12,0x6f,0xd2,0x8d,0x1c,0xc6,
0x15,0xce,0x26,0xde,0xa2,0x1b,0x31,0x4c,0xff,0xb0,0x2,0xa4,0x9c,0x15,0x20,0xe5,
0xac,0x0,0x29,0x67,0x5,0x48,0x39,0x2b,0x40,0xca,0x59,0x1,0x8c,0x31,0xc6,0x18,
0x63,0x52,0xc8,0x6e,0x9,0x1b,0x30,0xc1,0x64,0xf6,0x9a,0xef,0x7d,0x6a,0xc4,0x3e,
0x5,0xa4,0x9c,0x15,0x20,0xe5,0xac,0x0,0x29,0x67,0x5,0x48,0x39,0x2b,0x40,0xca,
0x59,0x1,0x52,0xce,0xa,0x90,0x72,0x56,0x80,0x94,0xb3,0x2,0xa4,0x9c,0x15,0x20,
0xe5,0xac,0x0,0x29,0xe7,0xad,0xbd,0x8a,0xe9,0xa1,0xb3,0x50,0x9c,0x2,0xe9,0x19,
0x21,0x3a,0x9b,0x41,0xf4,0xbe,0xb7,0x98,0x9b,0xfb,0x57,0x8e,0xfe,0xb,0x20,0xba,
0x79,0x5e,0x87,0x68,0x3,0xf2,0x15,0x2f,0xba,0x45,0x2b,0x7a,0x1b,0x98,0x47,0x55,
0xb0,0x95,0x19,0x77,0xb6,0xba,0x43,0x2b,0x80,0x7b,0xaf,0x2b,0xf4,0xf7,0x42,0xde,
0x89,0x7f,0xfb,0xfc,0x61,0xa3,0x15,0xcf,0x1,0x97,0x70,0xf5,0xcf,0x7,0x0,0xa6,
0x96,0xc7,0x6f,0xfc,0x99,0x7c,0x22,0xe3,0x45,0xbb,0x0,0xfa,0x76,0xd2,0x9d,0xdb,
0xd5,0x40,0x67,0xf4,0x5,0x22,0x1c,0x39,0xef,0x5f,0xf7,0xf,0x97,0x29,0x6c,0x6,
0xe8,0xbd,0xd7,0x84,0x74,0xff,0x45,0xff,0xba,0x7f,0xba,0xe,0x2,0x58,0x1,0x7a,
0x46,0x20,0x8b,0xc,0x7a,0x38,0x78,0x27,0x7b,0x14,0x27,0xa8,0xb2,0xda,0x3a,0x85,
0x92,0xe,0xab,0x44,0xdb,0x0,0x6c,0x27,0x92,0x3b,0x20,0xbc,0x5,0x2c,0x5,0x0,
0xc3,0x4b,0xab,0xcc,0x43,0x38,0x0,0xc9,0x8c,0x12,0xbf,0x5,0xc5,0xe9,0x4c,0x39,
0x73,0xfa,0xdc,0x63,0x7c,0xa9,0xd5,0x5c,0xf6,0x12,0xd0,0xb,0x82,0x19,0x40,0xbe,
0x15,0x1c,0xca,0x9d,0xb9,0xf6,0x41,0xa5,0x7c,0x29,0xfa,0xa6,0x8a,0xee,0x5,0xe9,
0xbd,0xc,0xce,0x25,0x7a,0x6a,0x91,0x5,0x66,0x7a,0x1e,0x44,0xc7,0x3,0x3f,0xfb,
0x52,0xd2,0x68,0x56,0x80,0x2e,0x13,0xc5,0x54,0x14,0x7a,0xf7,0xcd,0xfd,0x92,0x3e,
0xaa,0x7d,0xac,0x50,0x8c,0x76,0xb,0x74,0x82,0x81,0xcf,0x77,0x64,0x5f,0xc0,0x19,
0x26,0x4c,0x6,0x7e,0xf6,0xd9,0x66,0xb7,0xb1,0x2,0x74,0x93,0xca,0x8b,0xb9,0xf9,
0xec,0x3,0x1f,0xfe,0x8a,0x2f,0xc7,0x87,0xf3,0xe3,0xb,0x5b,0x88,0xe8,0x28,0x88,
0x13,0x7f,0xa1,0x43,0x53,0xbb,0x85,0x9c,0xa4,0x8a,0x3c,0x14,0x1c,0x1e,0x7a,0x77,
0xad,0x75,0xed,0x44,0x50,0x97,0x88,0x62,0x6a,0xb5,0x83,0x3f,0x52,0x8c,0x1e,0x54,
0xd0,0x74,0xb7,0xe,0x3e,0x0,0x10,0xf8,0x6e,0x64,0xf8,0xf5,0xfc,0x78,0xb4,0x67,
0xad,0x75,0xad,0x0,0xdd,0x20,0x98,0x89,0x42,0xef,0xbe,0x6b,0xfe,0xe5,0x17,0xc3,
0x5f,0x30,0xf4,0x19,0x66,0x1e,0xae,0xb7,0x69,0xe7,0xf0,0x26,0x62,0xfd,0x43,0xa1,
0x18,0x1e,0x6c,0xb8,0x56,0xf7,0x83,0xa4,0x8b,0x88,0x2c,0x50,0x46,0x76,0xd7,0xbe,
0xe6,0xe7,0x8b,0xe1,0x53,0x4,0xfc,0xd4,0x41,0xa4,0xf1,0x7c,0x31,0x7c,0xb2,0xde,
0x83,0x56,0x80,0xe,0x63,0xa6,0x47,0xce,0xfb,0xb9,0x37,0xe3,0x63,0xf9,0x89,0xf0,
0x8,0x1,0xdf,0x77,0x95,0x89,0x80,0xfd,0xf5,0x66,0x2,0x7b,0x13,0xd8,0x59,0xaf,
0x5,0xef,0x78,0x5f,0x8d,0x7f,0xce,0x1f,0x29,0x46,0xf,0x32,0xf4,0x99,0x56,0x9f,
0xb0,0xf6,0x3e,0xff,0x76,0x8e,0x97,0x82,0xf6,0x5c,0x98,0xf4,0xfe,0x14,0x1f,0xb3,
0x19,0xa0,0x83,0x84,0x74,0x7f,0xfc,0xe0,0xe7,0xc7,0x17,0xb6,0x40,0x2a,0x47,0x5d,
0x66,0x8a,0x23,0x54,0x9e,0x2e,0xfc,0xfc,0xf2,0x67,0xe3,0x63,0x56,0x80,0x8e,0xd1,
0x17,0x6a,0x4f,0xef,0x12,0xd1,0xd1,0xde,0xbc,0xe1,0x6b,0x16,0x6f,0x92,0xc,0x57,
0xbd,0x1f,0xb0,0x2,0x74,0x8,0x11,0x8e,0xc4,0x97,0xb,0xc5,0x68,0x77,0x37,0x3f,
0xea,0xb5,0x8a,0xc1,0x3b,0x6f,0x2a,0x85,0xbb,0xfe,0xbf,0x6c,0xda,0x26,0x82,0x37,
0xaa,0xaf,0xea,0x29,0x9,0x74,0xc2,0x5d,0xa2,0xc6,0x2a,0x15,0x94,0x96,0x7f,0xb6,
0x2,0x74,0x0,0xb1,0xfe,0x2e,0xbe,0x9c,0x9f,0x88,0xee,0xe9,0xd4,0xe9,0xdd,0x6e,
0x60,0xc6,0x5d,0x85,0x89,0x70,0x27,0x60,0x5,0xe8,0x8,0x21,0xef,0x44,0x7c,0x59,
0xa1,0xdf,0x71,0x95,0xa5,0x69,0xaa,0x7b,0x1,0x2b,0x40,0x27,0x9c,0x8d,0xdf,0xc9,
0x53,0x28,0xe9,0x30,0x48,0xef,0x75,0x19,0xa8,0x19,0x2,0xbd,0x7f,0x73,0x49,0x37,
0x5a,0x1,0xda,0xa5,0x38,0x55,0xb5,0x28,0xd1,0xb6,0xa4,0x97,0x74,0x5d,0x60,0xe6,
0xd,0x11,0xa2,0xad,0x56,0x80,0x76,0x91,0xd6,0x5e,0xe3,0xdf,0xee,0x24,0x47,0xb,
0x54,0xb0,0xc3,0xa,0xd0,0x26,0x21,0x3a,0x1b,0x5f,0x26,0x92,0x3b,0x5c,0x65,0x49,
0x8a,0xa0,0xb7,0x5b,0x1,0xda,0x94,0x41,0xf4,0x7e,0xd5,0x80,0xf0,0x16,0x37,0x49,
0x5a,0xa0,0x74,0xab,0xdd,0x13,0xd8,0x26,0x6f,0x31,0x37,0x57,0x35,0xc0,0x52,0x68,
0xf4,0xde,0x3a,0xe9,0x77,0xf8,0xb4,0xbb,0x7d,0xa3,0x6b,0x7,0x2,0xc9,0xdb,0xc,
0xd0,0xa6,0xa5,0x5f,0xda,0x88,0x5b,0x47,0xa7,0x7e,0x1b,0x63,0xe0,0x7a,0x2b,0x40,
0xfb,0x22,0xd7,0x1,0xda,0x61,0x5,0x68,0xd3,0xcd,0xf3,0x3a,0x54,0x33,0x34,0xef,
0x24,0x48,0xb,0x4,0xf8,0x8f,0xbd,0x7,0x68,0xd3,0x95,0x61,0x1a,0xc1,0xd5,0x5f,
0xd7,0xba,0x4a,0x38,0x0,0xe3,0x86,0x7a,0xeb,0x27,0xbd,0x9e,0xdf,0xc9,0xfb,0x1,
0x6a,0x31,0x73,0x60,0x33,0x40,0x9b,0x3c,0x84,0x9f,0xaa,0x1a,0x20,0x99,0x71,0x14,
0x25,0x31,0x85,0xce,0x58,0x1,0xda,0xa4,0xaa,0x9f,0xab,0x5a,0x26,0x7e,0xcb,0x55,
0x96,0xa4,0x8,0xf4,0xb6,0x15,0xa0,0x6d,0x5c,0xfd,0xdf,0xb5,0x2a,0x4e,0x3b,0xa,
0x92,0x1c,0xe1,0x55,0x6,0x24,0x74,0x9d,0xa3,0x9f,0xa9,0x60,0x6b,0x7c,0x39,0x53,
0xce,0x9c,0x16,0x91,0x5,0x57,0x79,0x9a,0x25,0x90,0xcb,0x1e,0xbc,0x29,0x16,0xe1,
0xf,0x5c,0x87,0xe9,0x67,0xcc,0xb8,0x73,0xa4,0x24,0x1f,0x5f,0x5e,0x3e,0xf7,0x18,
0x5f,0x62,0xa6,0xe7,0x5d,0x66,0x6a,0x6,0xb,0x3d,0x37,0xeb,0x53,0x99,0x99,0xf1,
0x8a,0xeb,0x30,0xfd,0x8e,0x25,0xda,0x55,0x35,0x40,0x74,0xdc,0x51,0x94,0xa6,0xd1,
0x52,0x46,0x56,0x92,0xdf,0xb8,0xe,0xd3,0xff,0xaa,0xbf,0x99,0x23,0xf0,0xbd,0x97,
0x45,0xf0,0x66,0xbd,0xb5,0x9d,0x13,0x4c,0x9f,0x3f,0x98,0x3d,0x9,0x0,0x7c,0xc1,
0xcf,0x4d,0x3,0xf8,0xad,0xe3,0x48,0xfd,0x8d,0xf0,0x95,0x91,0xd2,0x95,0x2f,0xc7,
0x6,0x94,0x33,0xf0,0xdd,0x5,0x6a,0x4c,0x62,0xd9,0x18,0x0,0x3c,0xf2,0x7e,0xc,
0xe0,0xef,0xce,0x12,0xd,0x2,0xc1,0xa3,0xf1,0xc5,0xc0,0xcf,0x3e,0xab,0x90,0x93,
0xae,0xe2,0xd4,0xa5,0xf2,0xe2,0x45,0x3f,0xbb,0xf2,0x1e,0x85,0x1,0x60,0xd6,0xa7,
0xb2,0x47,0xde,0x3d,0x0,0x8e,0x39,0xb,0xd6,0xe7,0x98,0xe8,0x81,0xfc,0xc4,0x95,
0x2f,0xc5,0xc7,0xa8,0x22,0xf,0x1,0x52,0x7b,0xb1,0xc8,0x21,0x99,0x63,0x91,0x1f,
0xc6,0x47,0x56,0xce,0x3,0xcc,0xfa,0x54,0xe,0x26,0xb3,0xdf,0x3,0xc9,0xa8,0x2a,
0x9e,0x5a,0xfa,0x56,0xb,0xfb,0x88,0x98,0x80,0x82,0x7e,0x8d,0x92,0xae,0xfc,0x9d,
0x6,0x87,0x87,0xde,0x55,0xc9,0x7c,0xd7,0x65,0xa6,0x2a,0xc4,0x63,0xe7,0xe,0xf,
0xbd,0x57,0x35,0xe4,0x2a,0x4b,0x9a,0x2c,0xfd,0x62,0xe6,0xb8,0xd3,0x10,0xa,0x3f,
0x38,0x98,0x3d,0x50,0x3b,0x6c,0x5,0xe8,0x91,0x7c,0x31,0x7c,0x92,0x80,0xfd,0x2e,
0xf6,0x2d,0x8a,0x27,0x2e,0x1e,0xcc,0xfe,0x68,0xb5,0xc7,0xec,0x54,0x70,0x8f,0x5c,
0x98,0xcc,0xfe,0x0,0xc0,0xa1,0x5e,0xef,0x57,0xa1,0x7,0xea,0x1d,0x7c,0xc0,0x66,
0x80,0x9e,0xcb,0x8f,0x47,0x7b,0x88,0x2b,0xc7,0x0,0xde,0xd4,0xdd,0x3d,0xc9,0x1c,
0x88,0xc7,0x2,0x3f,0xfb,0xe7,0x46,0x6b,0xd9,0xc,0xd0,0x63,0x17,0xe,0x79,0x7f,
0x44,0x45,0x46,0x5,0xf2,0x72,0xf7,0xf6,0x22,0x7f,0xe1,0x8a,0x8c,0xae,0x75,0xf0,
0x1,0x9b,0x1,0x9c,0xba,0xa9,0x14,0xee,0xaa,0x54,0x50,0x62,0xc6,0x5d,0x1d,0x79,
0x42,0xc1,0xb4,0x64,0xe0,0xc7,0x3f,0xe7,0xaf,0xc5,0xa,0xb0,0xe,0x14,0x26,0xc2,
0x9d,0x50,0xdd,0x2b,0xd0,0xfb,0x99,0x79,0x43,0x92,0x6d,0x5,0x72,0x99,0x85,0x9e,
0x23,0xa2,0xe3,0xcb,0xa7,0x77,0x93,0xb0,0x2,0xac,0x23,0x9b,0x4b,0xba,0x31,0x42,
0xb4,0x55,0x5,0x3b,0x8,0x7a,0x3b,0x94,0x6e,0x5d,0xba,0x75,0xfb,0x7a,0xe0,0xea,
0x3d,0x7c,0xcc,0x1c,0x28,0x74,0x86,0x40,0x6f,0x83,0xf0,0xaa,0x7,0x6f,0x6a,0xd6,
0xa7,0xb2,0xeb,0xec,0xc6,0x18,0x63,0x8c,0x31,0xc6,0x18,0x63,0x8c,0x31,0xc6,0x18,
0x63,0x8c,0x31,0xc6,0x18,0x63,0x8c,0x59,0x3f,0xfe,0x7,0xf5,0xf3,0x62,0x97,0x96,
0xf,0x36,0x39,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82,
};
static const unsigned char qt_resource_name[] = {
// MainWindow
0x0,0xa,
0x3,0xd6,0x3b,0x67,
0x0,0x4d,
0x0,0x61,0x0,0x69,0x0,0x6e,0x0,0x57,0x0,0x69,0x0,0x6e,0x0,0x64,0x0,0x6f,0x0,0x77,
// Resources
0x0,0x9,
0xa,0x6c,0x38,0x43,
0x0,0x52,
0x0,0x65,0x0,0x73,0x0,0x6f,0x0,0x75,0x0,0x72,0x0,0x63,0x0,0x65,0x0,0x73,
// folder.png
0x0,0xa,
0xa,0xc8,0xfb,0x7,
0x0,0x66,
0x0,0x6f,0x0,0x6c,0x0,0x64,0x0,0x65,0x0,0x72,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67,
};
static const unsigned char qt_resource_struct[] = {
// :
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1,
0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
// :/MainWindow
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x2,
0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
// :/MainWindow/Resources
0x0,0x0,0x0,0x1a,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x3,
0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,
// :/MainWindow/Resources/folder.png
0x0,0x0,0x0,0x32,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0,
0x0,0x0,0x1,0x5b,0x5c,0x7f,0x2e,0xbb,
};
#ifdef QT_NAMESPACE
# define QT_RCC_PREPEND_NAMESPACE(name) ::QT_NAMESPACE::name
# define QT_RCC_MANGLE_NAMESPACE0(x) x
# define QT_RCC_MANGLE_NAMESPACE1(a, b) a##_##b
# define QT_RCC_MANGLE_NAMESPACE2(a, b) QT_RCC_MANGLE_NAMESPACE1(a,b)
# define QT_RCC_MANGLE_NAMESPACE(name) QT_RCC_MANGLE_NAMESPACE2( \
QT_RCC_MANGLE_NAMESPACE0(name), QT_RCC_MANGLE_NAMESPACE0(QT_NAMESPACE))
#else
# define QT_RCC_PREPEND_NAMESPACE(name) name
# define QT_RCC_MANGLE_NAMESPACE(name) name
#endif
#ifdef QT_NAMESPACE
namespace QT_NAMESPACE {
#endif
bool qRegisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *);
bool qUnregisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *);
#ifdef QT_NAMESPACE
}
#endif
int QT_RCC_MANGLE_NAMESPACE(qInitResources_MainWindow)();
int QT_RCC_MANGLE_NAMESPACE(qInitResources_MainWindow)()
{
QT_RCC_PREPEND_NAMESPACE(qRegisterResourceData)
(0x02, qt_resource_struct, qt_resource_name, qt_resource_data);
return 1;
}
int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_MainWindow)();
int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_MainWindow)()
{
QT_RCC_PREPEND_NAMESPACE(qUnregisterResourceData)
(0x02, qt_resource_struct, qt_resource_name, qt_resource_data);
return 1;
}
namespace {
struct initializer {
initializer() { QT_RCC_MANGLE_NAMESPACE(qInitResources_MainWindow)(); }
~initializer() { QT_RCC_MANGLE_NAMESPACE(qCleanupResources_MainWindow)(); }
} dummy;
}
<file_sep>#pragma once
#ifndef GL_TEXTURE_H
#define GL_TEXTURE_H
#include "headers.h"
#include "mathematics.h"
namespace gl
{
enum TextureFilter
{
FILTER_NEAREST = 0x2600,
FILTER_LINEAR = 0x2601
};
enum TextureWrapping
{
WRAPPING_REPEAT = 0x2901,
WRAPPING_MIRRORED_REPEAT = 0x8370,
WRAPPING_CLAMP_TO_EDGE = 0x812F,
WRAPPING_CLAMP_TO_BORDER = 0x812D
};
enum TextureFormat
{
FORMAT_R8 = 0x1903,
FORMAT_RGB = 0x1907,
FORMAT_BGR = 0x80E0,
FORMAT_RGBA = 0x1908,
FORMAT_BGRA = 0x80E1
};
class Texture
{
private:
uint32_t id_;
protected:
TextureFormat format_;
glm::ivec2 size_;
std::vector<uint8_t> data_;
public:
Texture(TextureFormat format, const glm::ivec2& size, TextureFilter texture_filter = FILTER_LINEAR,
TextureWrapping texture_wrapping = WRAPPING_CLAMP_TO_EDGE);
Texture(TextureFormat format, const glm::ivec2& size, const std::vector<uint8_t>& data, TextureFilter texture_filter = FILTER_LINEAR,
TextureWrapping texture_wrapping = WRAPPING_CLAMP_TO_EDGE);
virtual ~Texture();
const glm::ivec2& size();
void set_data(const std::vector<uint8_t>& data);
void set_data(const glm::ivec4& rect, const std::vector<uint8_t>& data);
void bind();
void unbind();
protected:
void init();
uint16_t format_size(TextureFormat format);
};
}
#endif // !ABSTRACT_TEXTURE_H
<file_sep>#pragma once
#ifndef GUI_DYNAMIC_TEXT_H
#define GUI_DYNAMIC_TEXT_H
#include "gui_object.h"
class GUI_DynamicText : public GUI_Object
{
private:
std::array<std::shared_ptr<gl::Texture>, 128 > char_textures_;
public:
GUI_DynamicText(const glm::ivec2 position, const std::string& text, uint16_t font_size);
~GUI_DynamicText();
void text(const std::string& new_text) override;
void pos(const glm::vec2& new_pos) override;
void draw(const glm::mat4& projection) override;
};
#endif // !GUI_TEXT_H
<file_sep>#include "resources.h"
#include "macros.h"
bool Resources::is_Resources_initialized = false;
Resources::Resources()
{
ASSERT_IF_TRUE(is_Resources_initialized, "The class 'Resources' already initialized as 'resources'.");
is_Resources_initialized = true;
resource_path_ = fs::current_path();
resource_path_ /= "Resources";
for (auto& entry : fs::recursive_directory_iterator(resource_path_))
{
auto& p = entry.path();
if (p.has_extension()) {
entries_[p.filename().string()] = p;
}
}
}
Resources::~Resources()
{
is_Resources_initialized = false;
}
void Resources::update()
{
entries_.clear();
for (auto& entry : fs::recursive_directory_iterator(resource_path_))
{
auto& p = entry.path();
if (p.has_extension()) {
entries_[p.filename().string()] = p;
}
}
}
bool Resources::exist(const std::string & file_name)
{
return (entries_.find(file_name) != entries_.end());
}
const fs::path & Resources::get_path(const std::string & file_name)
{
return entries_[file_name];
}
fs::path Resources::create_directory(const std::string & directory_name)
{
auto p = resource_path_;
p /= directory_name;
fs::create_directories(p);
return p;
}
Resources resources;
<file_sep>#pragma once
#ifndef ABSTRACT_ENTITY_H
#define ABSTRACT_ENTITY_H
#include "headers.h"
#include "mathematics.h"
#include "gl_vao.h"
#include "glsl_program.h"
#include "gl_texture.h"
class Entity
{
protected:
uint16_t id_;
std::string type_;
std::unique_ptr<gl::VAO> vao_;
std::unique_ptr<glsl::Program> program_;
std::unique_ptr<gl::Texture> texture_;
public:
Entity(const std::string& drived_type) : type_(drived_type) {
id_ = unique_entity_id();
}
virtual ~Entity() {}
const uint16_t& id() { return id_; }
const std::string& type() { return type_; }
virtual void update() = 0;
virtual void draw(const glm::mat4& projection_view) = 0;
private:
uint16_t unique_entity_id() {
static uint16_t uniqueEntyityId = 0;
return uniqueEntyityId++;
}
};
#endif // !ABSTRACT_ENTITY_H
<file_sep>#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_MainWindow.h"
#include <QTimer>
#include <QThread>
#include <QGraphicsScene>
#include <QAction>
#include <QTabWidget>
#include "session.h"
#include "sessioninfo.h"
#include "matrix_vision.h"
#include "image_viewer.h"
#include <chrono>
#include <memory>
#include "headers.h"
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = Q_NULLPTR);
~MainWindow();
typedef std::chrono::system_clock Clock;
typedef std::chrono::milliseconds ms;
private slots:
void capture_image();
void newSession();
void stopSession();
void saveImage();
void closeEvent(QCloseEvent *event);
private:
Ui::MainWindowClass ui;
QAction *action_newSession_;
QAction *action_stopSession_;
QAction *action_addCamera_;
QTabWidget *tabWidget_;
std::map<uint32_t, Session*> session_map_;
std::map<uint32_t, ImageViewer*> viewer_map_;
const unsigned int timeout_ms = 500;
bool saveCapturedImage_;
int saveInterval_;
int saveDuration_;
qint64 saveStartTime_;
int savedImageCounter_;
std::string savePath_;
std::string fileName_;
std::stringstream stream_;
Clock::time_point currentTime;
Clock::time_point previousTime;
QTimer* timer_saveImage_;
QTimer* timer_captureImage_;
QImage* image_;
std::unique_ptr<mv::MvDevice> mv_device;
std::vector<uint32_t> camera_IDs;
uint16_t capture_index;
std::atomic<bool> thread_finished;
std::atomic<bool> capture_succeed;
std::thread thread_worker;
glm::ivec2 size;
std::vector<uint8_t> pixels;
std::function<void(uint32_t)> thread_function;
std::function<void(const std::string&)> thread_save_image_function;
};
<file_sep>#pragma once
#ifndef VERTEX_ARRAY_OBJECT_H
#define VERTEX_ARRAY_OBJECT_H
#include "headers.h"
#include "enums.h"
namespace gl
{
class VAO
{
private:
uint32_t vao_id_;
uint32_t ebo_id_;
std::unordered_map<glsl::Attribute, uint32_t> vbo_id_map_;
std::size_t index_size_;
public:
VAO();
~VAO();
void add_attribute(glsl::Attribute attrib_type, const void* buffer_data, const std::size_t& buffer_stride, const uint8_t& attrib_size, const uint32_t& shader_location_id, bool is_instance);
void add_indices(const void* buffer_data, const std::size_t& buffer_size, std::size_t indexSize);
std::uint32_t buffer_id(glsl::Attribute attrib_type);
void bind() const;
void unbind() const;
const std::size_t& index_size() const { return index_size_; }
};
template<typename T>
inline void VAO::add_attribute_buffer(glsl::Attribute attrib_type, const std::vector<T>& attribute_buffer, const uint32_t & shader_location_id)
{
}
}
#endif // !VERTEX_ARRAY_OBJECT_H
<file_sep>#include "MainWindow.h"
#include <QPixmap>
#include <QMessagebox>
#include <iomanip>
#include <sstream>
#include <chrono>
#include <iomanip>
#include <ctime>
#include <QSpacerItem>
#include <QDateTime>
#include <QCloseEvent>
#include "device_selection.h"
#include "headers.h"
#include "time_utility.h"
#include "character_generator.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
saveCapturedImage_ = false;
saveInterval_ = 0;
action_newSession_ = new QAction("New session", this );
action_stopSession_ = new QAction("Stop session", this);
ui.toolBar->addAction(action_newSession_);
ui.toolBar->addAction(action_stopSession_);
action_stopSession_->setEnabled(false);
this->connect(action_newSession_, SIGNAL(triggered()), this, SLOT(newSession()));
this->connect(action_stopSession_, SIGNAL(triggered()), this, SLOT(stopSession()));
timer_captureImage_ = new QTimer(this);
this->connect(timer_captureImage_, SIGNAL(timeout()), this, SLOT(capture_image()));
timer_saveImage_ = new QTimer(this);
this->connect(timer_saveImage_, SIGNAL(timeout()), this, SLOT(saveImage()));
currentTime = Clock::now();
previousTime = Clock::now();
try
{
camera_IDs = mv::mvDeviceManager.get_device_IDs();
if (camera_IDs.empty())
{
QMessageBox::critical(this, "Error", "No Matrix Vision camera found.", QMessageBox::Button::Ok, QMessageBox::Button::Ok);
QApplication::quit();
}
else
{
QTimer::singleShot(1000, [&]()
{
for (auto& id : camera_IDs) {
viewer_map_[id] = new ImageViewer(this);
ui.viewer_layout->addWidget(viewer_map_[id]);
session_map_[id] = new Session( "Session " + QString::number(id), ui.session_fram);
ui.sessions_layout->addWidget(session_map_[id]);
}
ui.sessions_layout->addSpacerItem(new QSpacerItem(0, 1000, QSizePolicy::Expanding, QSizePolicy::Expanding));
capture_index = 0;
thread_finished = true;
capture_succeed = false;
thread_function = [&](uint32_t id) {
capture_succeed = mv::mvDeviceManager.single_capture(id, size.x, size.y, pixels);
thread_finished = true;
};
thread_save_image_function = [&](const std::string& file_path) {
if (pixels.empty()) {
thread_finished = true;
return;
}
std::stringstream stream;
std::time_t now_c = std::chrono::system_clock::to_time_t(core::Clock::now());
stream << std::put_time(std::localtime(&now_c), "%F %T");
glm::ivec2 text_size;
std::vector<uint8_t> text_pixels;
std::tie(text_size, text_pixels) = characterGen.text_to_bitmap(core::ARIAL, 50, stream.str());
glm::u8vec3 color(0, 1, 0);
glm::u8vec3 pix;
for (auto h = 0u; h < text_size.y; ++h) {
for (auto w = 0u; w < text_size.x; ++w) {
pix = color * text_pixels[(h * text_size.x) + w];
if (pix[1] != 0) {
pixels[((100 + h) * size.x * 3) + ((100 + w) * 3)] = pix[0];
pixels[((100 + h) * size.x * 3) + ((100 + w) * 3) + 1] = pix[1];
pixels[((100 + h) * size.x * 3) + ((100 + w) * 3) + 2] = pix[2];
}
}
}
stbi_write_png(file_path.c_str(), size.x, size.y, 3, pixels.data(), sizeof(uint8_t) * size.x * 3);
thread_finished = true;
};
timer_captureImage_->start(1000);
});
}
}
catch (const std::exception& e)
{
QMessageBox::critical(this, "Error", e.what(), QMessageBox::Button::Ok, QMessageBox::Button::Ok);
QApplication::quit();
}
}
MainWindow::~MainWindow()
{
if(timer_captureImage_->isActive())
timer_captureImage_->stop();
}
void MainWindow::capture_image()
{
try
{
if (thread_finished)
{
thread_finished = false;
if (capture_succeed) {
if (size.x * size.y * 3 == pixels.size()) {
viewer_map_[capture_index]->set_viewer_image(size, pixels);
viewer_map_[capture_index]->update();
}
}
if (session_map_[capture_index]->must_save())
thread_worker = std::thread(thread_save_image_function, session_map_[capture_index]->full_save_path());
else {
thread_worker = std::thread(thread_function, capture_index++);
}
if (capture_index >= camera_IDs.size())
capture_index = 0;
thread_worker.detach();
}
}
catch (const std::exception& e)
{
ui.statusBar->showMessage(e.what());
}
{
std::stringstream stream;
auto stamp = core::time_stamp();
stream << stamp.year << "-" << stamp.month << "-" << stamp.day << " " << stamp.hour << ":" << stamp.minute << ":" << stamp.second;
this->ui.statusBar->showMessage(QString(stream.str().c_str()));
}
}
void MainWindow::newSession()
{
SessionInfo session;
session.setModal(true);
if (session.exec() == 1)
{
saveInterval_ = session.ui->txt_interval->value();
saveDuration_ = session.ui->txt_duration->value() * 60;
savePath_ = session.ui->txt_path->text().toStdString();
fileName_ = session.ui->txt_name->text().toStdString();
savedImageCounter_ = 0;
timer_saveImage_->start(saveInterval_ * 60000);
action_stopSession_->setEnabled(true);
action_newSession_->setEnabled(false);
saveStartTime_ = QDateTime::currentSecsSinceEpoch();
}
}
void MainWindow::stopSession()
{
if (timer_saveImage_->isActive()) {
timer_saveImage_->stop();
saveInterval_ = 0;
savePath_ = "";
fileName_ = "";
savedImageCounter_ = 0;
}
action_stopSession_->setEnabled(false);
action_newSession_->setEnabled(true);
long i;
}
void MainWindow::saveImage()
{
std::stringstream stream;
stream << savePath_ << "/" << fileName_ << '_' << std::setfill('0') << std::setw(4) << savedImageCounter_++ << ".png";
if (image_) {
std::time_t now_c = Clock::to_time_t(Clock::now());
std::stringstream time_stamp;
time_stamp << std::put_time(std::localtime(&now_c), "%F %T");
QPainter painter(image_);
painter.setPen(QPen(Qt::white));
painter.setFont(QFont("Times", 20, QFont::Bold));
painter.drawText(50, 50, QString(time_stamp.str().c_str()));
image_->save(stream.str().c_str());
ui.statusBar->showMessage("Image saved: " + QString(stream.str().c_str()));
}
if (saveDuration_ < QDateTime::currentSecsSinceEpoch() - saveStartTime_)
stopSession();
}
void MainWindow::closeEvent(QCloseEvent *event)
{
if (timer_captureImage_->isActive())
timer_captureImage_->stop();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
event->accept();
}
<file_sep>/********************************************************************************
** Form generated from reading UI file 'MainWindow.ui'
**
** Created by: Qt User Interface Compiler version 5.8.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QFrame>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MainWindowClass
{
public:
QAction *actionNew_Session;
QWidget *centralWidget;
QHBoxLayout *horizontalLayout;
QFrame *session_fram;
QVBoxLayout *sessions_layout;
QFrame *viewer_fram;
QHBoxLayout *viewer_layout;
QStatusBar *statusBar;
QToolBar *toolBar;
void setupUi(QMainWindow *MainWindowClass)
{
if (MainWindowClass->objectName().isEmpty())
MainWindowClass->setObjectName(QStringLiteral("MainWindowClass"));
MainWindowClass->resize(803, 556);
actionNew_Session = new QAction(MainWindowClass);
actionNew_Session->setObjectName(QStringLiteral("actionNew_Session"));
centralWidget = new QWidget(MainWindowClass);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
horizontalLayout = new QHBoxLayout(centralWidget);
horizontalLayout->setSpacing(6);
horizontalLayout->setContentsMargins(11, 11, 11, 11);
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
horizontalLayout->setContentsMargins(1, 1, 1, 1);
session_fram = new QFrame(centralWidget);
session_fram->setObjectName(QStringLiteral("session_fram"));
session_fram->setMinimumSize(QSize(200, 0));
session_fram->setMaximumSize(QSize(200, 16777215));
session_fram->setFrameShape(QFrame::StyledPanel);
session_fram->setFrameShadow(QFrame::Raised);
sessions_layout = new QVBoxLayout(session_fram);
sessions_layout->setSpacing(10);
sessions_layout->setContentsMargins(11, 11, 11, 11);
sessions_layout->setObjectName(QStringLiteral("sessions_layout"));
sessions_layout->setContentsMargins(2, 2, 2, 2);
horizontalLayout->addWidget(session_fram);
viewer_fram = new QFrame(centralWidget);
viewer_fram->setObjectName(QStringLiteral("viewer_fram"));
viewer_fram->setFrameShape(QFrame::StyledPanel);
viewer_fram->setFrameShadow(QFrame::Raised);
viewer_layout = new QHBoxLayout(viewer_fram);
viewer_layout->setSpacing(6);
viewer_layout->setContentsMargins(11, 11, 11, 11);
viewer_layout->setObjectName(QStringLiteral("viewer_layout"));
viewer_layout->setContentsMargins(1, 1, 1, 1);
horizontalLayout->addWidget(viewer_fram);
MainWindowClass->setCentralWidget(centralWidget);
statusBar = new QStatusBar(MainWindowClass);
statusBar->setObjectName(QStringLiteral("statusBar"));
MainWindowClass->setStatusBar(statusBar);
toolBar = new QToolBar(MainWindowClass);
toolBar->setObjectName(QStringLiteral("toolBar"));
MainWindowClass->addToolBar(Qt::TopToolBarArea, toolBar);
retranslateUi(MainWindowClass);
QMetaObject::connectSlotsByName(MainWindowClass);
} // setupUi
void retranslateUi(QMainWindow *MainWindowClass)
{
MainWindowClass->setWindowTitle(QApplication::translate("MainWindowClass", "Image capture", Q_NULLPTR));
actionNew_Session->setText(QApplication::translate("MainWindowClass", "New Session", Q_NULLPTR));
toolBar->setWindowTitle(QApplication::translate("MainWindowClass", "toolBar", Q_NULLPTR));
} // retranslateUi
};
namespace Ui {
class MainWindowClass: public Ui_MainWindowClass {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
<file_sep>#pragma once
#ifndef RESOURCES_H
#define RESOURCES_H
#include "headers.h"
class Resources
{
private:
static bool is_Resources_initialized;
fs::path resource_path_;
std::unordered_map<std::string, fs::path> entries_;
public:
Resources();
~Resources();
void update();
bool exist(const std::string& file_name);
const fs::path& get_path(const std::string& file_name);
fs::path create_directory(const std::string& directory_name);
};
extern Resources resources;
#endif // !RESOURCES_H<file_sep>#include "matrix_vision.h"
#include "headers.h"
#include "macros.h"
namespace mv
{
bool MvDeviceManager::is_CameraManager_initialized = false;
MvDeviceManager::MvDeviceManager()
{
assert(!is_CameraManager_initialized);
is_CameraManager_initialized = true;
}
MvDeviceManager::~MvDeviceManager()
{
is_CameraManager_initialized = false;
}
const std::vector<unsigned int>& MvDeviceManager::get_device_IDs()
{
unsigned int device_count = device_manager_.deviceCount();
if (device_count > 0) {
for (auto i = 0u; i < device_count; i++) {
if (device_manager_[i] && !device_manager_[i]->isInUse()) {
device_IDs_.push_back(i);
camera_devices_[i] = getDeviceFromUserInput(device_manager_, i);
}
}
}
return device_IDs_;
}
mvIMPACT::acquire::Device * MvDeviceManager::create_device(unsigned int id)
{
return device_manager_.getDevice(id);
}
bool MvDeviceManager::single_capture(uint16_t device_id, int& width, int& height, std::vector<uint8_t>& pixels)
{
auto pDev = camera_devices_[device_id];
try
{
if (!pDev)
pDev->open();
}
catch (const ImpactAcquireException& e)
{
std::cout << "An error occurred while opening the device(error code: " << e.getErrorCode() << ")." << std::endl;
return false;
}
ImageDestination id(pDev);
unsigned int pixelFormats = id.pixelFormat.dictSize();
for (unsigned int i = 0; i < pixelFormats; i++)
{
if (id.pixelFormat.getTranslationDictString(i) == "BGR888Packed") {
id.pixelFormat.write(id.pixelFormat.getTranslationDictValue(i));
break;
}
}
FunctionInterface fi(pDev);
fi.imageRequestSingle();
manuallyStartAcquisitionIfNeeded(pDev, fi);
const int iMaxWaitTime_ms = -1;
int requestNr = fi.imageRequestWaitFor(iMaxWaitTime_ms);
manuallyStopAcquisitionIfNeeded(pDev, fi);
if (!fi.isRequestNrValid(requestNr))
{
std::cout << "imageRequestWaitFor failed (" << requestNr << ", " << ImpactAcquireException::getErrorCodeAsString(requestNr) << ")"
<< ", timeout value too small?" << std::endl;
return 0;
}
const Request* pRequest = fi.getRequest(requestNr);
if (!pRequest->isOK())
return false;
auto p = (uint8_t*)pRequest->imageData.read();
width = pRequest->imageWidth.read();
height = pRequest->imageHeight.read();
pixels = std::vector<uint8_t>(p, p + (width * height * 3));
fi.imageRequestUnlock(requestNr);
pDev->close();
return true;
}
//####################################################
//####################################################
//####################################################
MvDevice::MvDevice(mvIMPACT::acquire::Device* device) :
device_(device), is_acquisition_started(false), mvInterface_(nullptr), currentImage_(nullptr), previousImage_(nullptr)
{
try
{
if (device_) {
if (device_->interfaceLayout.isValid() && device_->interfaceLayout.isWriteable() && supports_value(device_->interfaceLayout, dilGenICam))
device_->interfaceLayout.write(dilGenICam);
if (device_->acquisitionStartStopBehaviour.isValid() && device_->acquisitionStartStopBehaviour.isWriteable() && supports_value(device_->acquisitionStartStopBehaviour, assbUser))
device_->acquisitionStartStopBehaviour.write(assbUser);
device_->open();
}
else
throw std::runtime_error("'MvDevice::initialize()' The device pointer is not valid.");
}
catch (const ImpactAcquireException& e)
{
throw std::runtime_error("An error occurred while opening the device. Error code: " + e.getErrorString());
}
mvInterface_ = new FunctionInterface(device_);
if (mvInterface_) {
TDMR_ERROR result = DMR_NO_ERROR;
while ((result = static_cast<TDMR_ERROR>(mvInterface_->imageRequestSingle())) == DMR_NO_ERROR) {};
if (result != DEV_NO_FREE_REQUEST_AVAILABLE) {
throw std::runtime_error("'FunctionInterface.imageRequestSingle()' returned with an unexpected result: " + std::to_string(result)
+ "(" + mvIMPACT::acquire::ImpactAcquireException::getErrorCodeAsString(result) + ")");
}
start_acquisition();
//std::this_thread::sleep_for(std::chrono::duration<double>(0.1));
}
else
{
throw std::runtime_error("'FunctionInterface(Device)' returned NULL, No device interface created");
}
}
MvDevice::~MvDevice()
{
stop_acquisition();
if (currentImage_) {
currentImage_->unlock();
}
if (previousImage_)
previousImage_->unlock();
mvInterface_->imageRequestReset(0, 0);
int requestNr = INVALID_ID;
while ((requestNr = mvInterface_->imageRequestWaitFor(0)) >= 0)
{
currentImage_ = mvInterface_->getRequest(requestNr);
currentImage_->unlock();
}
device_->close();
}
mvIMPACT::acquire::Request* MvDevice::capture()
{
int requestNr = mvInterface_->imageRequestWaitFor(timeout_ms);
currentImage_ = mvInterface_->isRequestNrValid(requestNr) ? mvInterface_->getRequest(requestNr) : 0;
if (currentImage_->isOK())
return currentImage_;
/*else
throw std::runtime_error("'mvIMPACT::acquire::FunctionInterface::isRequestNrValid' FAILED :" +
std::to_string(requestNr) + ", " + ImpactAcquireException::getErrorCodeAsString(requestNr));*/
return nullptr;
}
void MvDevice::request_next_image()
{
if (currentImage_->isOK()) {
if (previousImage_)
previousImage_->unlock();
previousImage_ = currentImage_;
mvInterface_->imageRequestSingle();
}
/*else {
throw std::runtime_error("'mvIMPACT::acquire::Request::isOK' FAILED :" + currentImage_->requestResult.readS());
}*/
}
void MvDevice::start_acquisition()
{
if (device_->acquisitionStartStopBehaviour.read() == mvIMPACT::acquire::assbUser)
{
const mvIMPACT::acquire::TDMR_ERROR result = static_cast<mvIMPACT::acquire::TDMR_ERROR>(mvInterface_->acquisitionStart());
if (result != mvIMPACT::acquire::DMR_NO_ERROR)
throw std::runtime_error("'mvIMPACT::acquire::FunctionInterface::acquisitionStart' returned with an unexpected result: " +
std::to_string(result) + "(" + mvIMPACT::acquire::ImpactAcquireException::getErrorCodeAsString(result) + ")");
is_acquisition_started = true;
}
else
throw std::runtime_error("'mvIMPACT::acquire::Device::acquisitionStartStopBehaviour' is not 'mvIMPACT::acquire::assbUser'.");
}
void MvDevice::stop_acquisition()
{
if (device_->acquisitionStartStopBehaviour.read() == mvIMPACT::acquire::assbUser)
{
const mvIMPACT::acquire::TDMR_ERROR result = static_cast<mvIMPACT::acquire::TDMR_ERROR>(mvInterface_->acquisitionStop());
if (result != mvIMPACT::acquire::DMR_NO_ERROR)
throw std::runtime_error("'mvIMPACT::acquire::FunctionInterface::acquisitionStart' returned with an unexpected result: " +
std::to_string(result) + "(" + mvIMPACT::acquire::ImpactAcquireException::getErrorCodeAsString(result) + ")");
is_acquisition_started = false;
}
else
throw std::runtime_error("'mvIMPACT::acquire::Device::acquisitionStartStopBehaviour' is not 'mvIMPACT::acquire::assbUser'.");
}
}
mv::MvDeviceManager mv::mvDeviceManager;
<file_sep>#include "gl_utility.h"
#include "gui_dynamic_text.h"
#include "resources.h"
#include "character_generator.h"
GUI_DynamicText::GUI_DynamicText(const glm::ivec2 position, const std::string& text, uint16_t font_size) :
GUI_Object("GUI_DynamicText")
{
{
pos_ = position;
text_ = text;
glm::ivec2 data_size;
std::vector<uint8_t> data;
std::tie(data_size, data) = characterGen.text_to_bitmap(core::TIMES, font_size, text_);
program_ = std::make_unique<glsl::Program>(glsl::ShaderPathList{ resources.get_path("text.vert"), resources.get_path("text.frag") },
glsl::AttributeList{ glsl::VERTICES, glsl::TEXTURE_COORD });
program_->linkUniform({ glsl::MODEL, glsl::PROJECTION, glsl::SCALE, glsl::COLOR });
program_->bind();
program_->setUniform(glsl::MODEL, glm::vec2(pos_.x, pos_.y));
program_->setUniform(glsl::COLOR, glm::vec3(0.5, 0.8f, 0.2f));
program_->setUniform(glsl::SCALE, glm::vec2(data_size.x, data_size.y));
texture_ = std::make_unique<gl::Texture>(gl::FORMAT_R8, data_size, data);
}
{
std::vector<glm::vec2> uv{ { 0.0f, 1.0f },{ 0.0f, 0.0f },{ 1.0f, 1.0f },{ 1.0f, 0.0f } };
std::vector<uint32_t> indices{ 1, 0, 2, 1, 2, 3 };
std::vector<glm::vec2> vertices{ { 0.0f, 0.0f },{ 0.0f, 1.0f },{ 1.0f, 0.0f },{ 1.0f, 1.0f } };
vao_ = std::make_unique<gl::VAO>();
vao_->bind();
vao_->add_attribute(glsl::VERTICES, &vertices[0][0], vertices.size() * sizeof(vertices.front()), 2, program_->attreibute_id(glsl::VERTICES), false);
vao_->add_attribute(glsl::TEXTURE_COORD, &uv[0][0], uv.size() * sizeof(uv.front()), 2, program_->attreibute_id(glsl::TEXTURE_COORD), false);
vao_->add_indices(indices.data(), indices.size() * sizeof(indices.front()), indices.size());
vao_->unbind();
}
}
GUI_DynamicText::~GUI_DynamicText()
{
}
void GUI_DynamicText::text(const std::string & new_text)
{
}
void GUI_DynamicText::pos(const glm::vec2 & new_pos)
{
}
void GUI_DynamicText::draw(const glm::mat4& projection)
{
program_->bind();
program_->setUniform(glsl::PROJECTION, projection);
vao_->bind();
glDrawElements(GL_TRIANGLES, (GLsizei)vao_->index_size(), GL_UNSIGNED_INT, nullptr);
vao_->unbind();
program_->unbind();
char_textures_[0]->unbind();
}
<file_sep>/********************************************************************************
** Form generated from reading UI file 'sessioninfo.ui'
**
** Created by: Qt User Interface Compiler version 5.8.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_SESSIONINFO_H
#define UI_SESSIONINFO_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpinBox>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_SessionInfo
{
public:
QGridLayout *gridLayout;
QLabel *label_4;
QLabel *label_5;
QLabel *label_2;
QLineEdit *txt_name;
QLineEdit *txt_fullpath;
QPushButton *btn_load;
QLineEdit *txt_path;
QPushButton *btn_start;
QLabel *label;
QLabel *label_3;
QSpinBox *txt_interval;
QSpinBox *txt_duration;
QLabel *label_6;
QLabel *label_7;
void setupUi(QWidget *SessionInfo)
{
if (SessionInfo->objectName().isEmpty())
SessionInfo->setObjectName(QStringLiteral("SessionInfo"));
SessionInfo->resize(769, 149);
QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(SessionInfo->sizePolicy().hasHeightForWidth());
SessionInfo->setSizePolicy(sizePolicy);
gridLayout = new QGridLayout(SessionInfo);
gridLayout->setSpacing(6);
gridLayout->setContentsMargins(11, 11, 11, 11);
gridLayout->setObjectName(QStringLiteral("gridLayout"));
label_4 = new QLabel(SessionInfo);
label_4->setObjectName(QStringLiteral("label_4"));
gridLayout->addWidget(label_4, 7, 7, 1, 1);
label_5 = new QLabel(SessionInfo);
label_5->setObjectName(QStringLiteral("label_5"));
gridLayout->addWidget(label_5, 5, 0, 1, 1);
label_2 = new QLabel(SessionInfo);
label_2->setObjectName(QStringLiteral("label_2"));
gridLayout->addWidget(label_2, 4, 0, 1, 1);
txt_name = new QLineEdit(SessionInfo);
txt_name->setObjectName(QStringLiteral("txt_name"));
gridLayout->addWidget(txt_name, 4, 5, 1, 1);
txt_fullpath = new QLineEdit(SessionInfo);
txt_fullpath->setObjectName(QStringLiteral("txt_fullpath"));
txt_fullpath->setReadOnly(true);
gridLayout->addWidget(txt_fullpath, 5, 5, 1, 1);
btn_load = new QPushButton(SessionInfo);
btn_load->setObjectName(QStringLiteral("btn_load"));
QIcon icon;
icon.addFile(QStringLiteral(":/icon/Resources/folder.png"), QSize(), QIcon::Normal, QIcon::Off);
btn_load->setIcon(icon);
gridLayout->addWidget(btn_load, 0, 7, 1, 1);
txt_path = new QLineEdit(SessionInfo);
txt_path->setObjectName(QStringLiteral("txt_path"));
gridLayout->addWidget(txt_path, 0, 5, 1, 1);
btn_start = new QPushButton(SessionInfo);
btn_start->setObjectName(QStringLiteral("btn_start"));
gridLayout->addWidget(btn_start, 10, 5, 1, 1);
label = new QLabel(SessionInfo);
label->setObjectName(QStringLiteral("label"));
gridLayout->addWidget(label, 0, 0, 1, 1);
label_3 = new QLabel(SessionInfo);
label_3->setObjectName(QStringLiteral("label_3"));
gridLayout->addWidget(label_3, 7, 0, 1, 1);
txt_interval = new QSpinBox(SessionInfo);
txt_interval->setObjectName(QStringLiteral("txt_interval"));
txt_interval->setMinimum(1);
txt_interval->setMaximum(60);
gridLayout->addWidget(txt_interval, 7, 5, 1, 1);
txt_duration = new QSpinBox(SessionInfo);
txt_duration->setObjectName(QStringLiteral("txt_duration"));
txt_duration->setMinimum(2);
txt_duration->setMaximum(5760);
txt_duration->setValue(2880);
gridLayout->addWidget(txt_duration, 8, 5, 1, 1);
label_6 = new QLabel(SessionInfo);
label_6->setObjectName(QStringLiteral("label_6"));
gridLayout->addWidget(label_6, 8, 0, 1, 1);
label_7 = new QLabel(SessionInfo);
label_7->setObjectName(QStringLiteral("label_7"));
gridLayout->addWidget(label_7, 8, 7, 1, 1);
QWidget::setTabOrder(btn_start, txt_path);
QWidget::setTabOrder(txt_path, txt_name);
QWidget::setTabOrder(txt_name, txt_fullpath);
QWidget::setTabOrder(txt_fullpath, btn_load);
retranslateUi(SessionInfo);
QMetaObject::connectSlotsByName(SessionInfo);
} // setupUi
void retranslateUi(QWidget *SessionInfo)
{
SessionInfo->setWindowTitle(QApplication::translate("SessionInfo", "Session Info", Q_NULLPTR));
label_4->setText(QApplication::translate("SessionInfo", "[min]", Q_NULLPTR));
label_5->setText(QApplication::translate("SessionInfo", "Full path:", Q_NULLPTR));
label_2->setText(QApplication::translate("SessionInfo", "Name:", Q_NULLPTR));
btn_load->setText(QString());
btn_start->setText(QApplication::translate("SessionInfo", "Start session", Q_NULLPTR));
label->setText(QApplication::translate("SessionInfo", "Path:", Q_NULLPTR));
label_3->setText(QApplication::translate("SessionInfo", "Capture interval:", Q_NULLPTR));
label_6->setText(QApplication::translate("SessionInfo", "Capture duration:", Q_NULLPTR));
label_7->setText(QApplication::translate("SessionInfo", "[min]", Q_NULLPTR));
} // retranslateUi
};
namespace Ui {
class SessionInfo: public Ui_SessionInfo {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_SESSIONINFO_H
<file_sep>#include "gl_utility.h"
#include "gl_texture.h"
#include "macros.h"
namespace gl
{
Texture::Texture(TextureFormat format, const glm::ivec2 & size, TextureFilter texture_filter, TextureWrapping texture_wrapping) :
id_(0u), format_(format), size_(size)
{
GL_CHECK(glGenTextures(1, &id_));
ASSERT_IF_FALSE(id_, "glGenTextures() failed to generate texture id.");
GL_CHECK(glBindTexture(GL_TEXTURE_2D, id_));
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture_filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texture_filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texture_wrapping);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texture_wrapping);
std::vector<uint8_t> data(size_.x * size_.y * format_size(format_), 0);
GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, format_, size_.x, size_.y, 0, format_, GL_UNSIGNED_BYTE, data.data()));
}
glBindTexture(GL_TEXTURE_2D, 0);
}
Texture::Texture(TextureFormat format, const glm::ivec2 & size, const std::vector<uint8_t>& data, TextureFilter texture_filter, TextureWrapping texture_wrapping) :
id_(0u), format_(format), size_(size)
{
GL_CHECK(glGenTextures(1, &id_));
ASSERT_IF_FALSE(id_, "glGenTextures() failed to generate texture id.");
GL_CHECK(glBindTexture(GL_TEXTURE_2D, id_));
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture_filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texture_filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texture_wrapping);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texture_wrapping);
GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, format_, size_.x, size_.y, 0, format_, GL_UNSIGNED_BYTE, data.data()));
}
glBindTexture(GL_TEXTURE_2D, 0);
}
Texture::~Texture()
{
if (id_ != 0)
glDeleteTextures(1, &id_);
}
const glm::ivec2 & Texture::size()
{
return size_;
}
void Texture::set_data(const std::vector<uint8_t>& data)
{
ASSERT_IF_FALSE(data.size() == size_.x * size_.y * format_size(format_), "'Texture::set_data()' the given pixel data size is not as equal as initialization time.");
glBindTexture(GL_TEXTURE_2D, id_);
glActiveTexture(GL_TEXTURE0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
GL_CHECK(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size_.x, size_.y, format_, GL_UNSIGNED_BYTE, data.data()));
}
void Texture::set_data(const glm::ivec4 & rect, const std::vector<uint8_t>& data)
{
glBindTexture(GL_TEXTURE_2D, id_);
glActiveTexture(GL_TEXTURE0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
GL_CHECK(glTexSubImage2D(GL_TEXTURE_2D, 0, rect.x, rect.y, rect[2], rect[3], format_, GL_UNSIGNED_BYTE, data.data()));
}
void Texture::bind()
{
glBindTexture(GL_TEXTURE_2D, id_);
}
void Texture::unbind()
{
glBindTexture(GL_TEXTURE_2D, 0);
}
uint16_t Texture::format_size(TextureFormat format)
{
switch (format)
{
case gl::FORMAT_R8: return 1;
case gl::FORMAT_RGB:
case gl::FORMAT_BGR: return 3;
case gl::FORMAT_RGBA:
case gl::FORMAT_BGRA: return 4;
default: return 1;
}
}
}<file_sep>#pragma once
#ifndef GUI_STATIC_TEXT_H
#define GUI_STATIC_TEXT_H
#include "gui_object.h"
class GUI_StaticText : public GUI_Object
{
private:
core::FontName font_name_;
uint16_t font_size_;
public:
GUI_StaticText(const glm::ivec2 position, core::FontName font_name, uint16_t font_size, const std::string& text, const glm::vec3& color);
~GUI_StaticText();
void text(const std::string& new_text) override;
void pos(const glm::vec2& new_pos) override;
void draw(const glm::mat4& projection) override;
};
#endif // !GUI_TEXT_H
<file_sep>#pragma once
#ifndef CHARACTER_GENERATOR_H
#define CHARACTER_GENERATOR_H
#include "headers.h"
#include "mathematics.h"
#include "enums.h"
//#include "gl_texture.h"
#include <ft2build.h>
#include FT_FREETYPE_H
struct CharacterData {
private:
//std::shared_ptr<gl::Texture> texture_;
public:
std::vector<uint8_t> buffer;
glm::ivec2 size;
CharacterData() {}
CharacterData(const std::vector<uint8_t>& bitmap_buffer, const glm::ivec2& bitmap_size) :
buffer(bitmap_buffer), size(bitmap_size)
{
//texture_ = std::make_shared<gl::Texture>(gl::FORMAT_R8, size, buffer);
}
~CharacterData() {}
/*std::shared_ptr<gl::Texture> texture() {
if (texture_)
return texture_;
else
{
texture_ = std::make_shared<gl::Texture>(gl::FORMAT_R8, size, buffer);
return texture_;
}
}*/
};
class CharacterGenerator
{
private:
static bool is_characters_initialized;
private:
struct FontInfo
{
using CharacterDataMap = std::array<CharacterData, 128>;
using CharacterSizeMap = std::unordered_map<uint16_t, CharacterDataMap>;
FT_Face face;
CharacterSizeMap characters;
~FontInfo() { }//FT_Done_Face(face); }
};
private:
FT_Library freetype_lib_;
std::unordered_map<core::FontName, FontInfo> fonts_;
public:
CharacterGenerator();
~CharacterGenerator();
CharacterData& get_character(core::FontName font, const uint16_t& size, const int8_t& character);
std::tuple<glm::ivec2, std::vector<uint8_t>> text_to_bitmap(core::FontName, const uint16_t& font_size, const std::string& text);
private:
void load_font(core::FontName font, const uint16_t& size);
};
extern CharacterGenerator characterGen;
#endif // !CHARACTER_GENERATOR_H
<file_sep>#pragma once
#ifndef MACROS_H
#define MACROS_H
#define FILE_LINE std::string("In file " + std::string(__FILE__) + " at line " + std::to_string(__LINE__) + ": ")
#define ASSERT_IF_TRUE(condition, message) \
if ((condition)) { \
std::cout << "[Assertion] " << FILE_LINE << ": " << message << std::endl; \
std::exit(1); \
} \
#define ASSERT_IF_FALSE(condition, message) \
if (!(condition)) { \
std::cout << "[Assertion] " << FILE_LINE << ": " << message << std::endl; \
std::exit(1); \
} \
#define CHECK_IF_TRUE(condition, message) \
if ((condition)) { \
std::cout << "[Assertion] " << FILE_LINE << ": " << message << std::endl; \
} \
#define CHECK_IF_FALSE(condition, message) \
if (!(condition)) { \
std::cout << "[Assertion] " << FILE_LINE << ": " << message << std::endl; \
} \
#pragma once
#undef DECL_ENUM_ELEMENT
#undef BEGIN_ENUM
#undef END_ENUM
#ifndef GENERATE_ENUM_STRINGS
#define DECL_ENUM_ELEMENT( element ) element
#define BEGIN_ENUM( ENUM_NAME ) typedef enum tag##ENUM_NAME
#define END_ENUM( ENUM_NAME ) ENUM_NAME; \
char* ToStr_##ENUM_NAME(enum tag##ENUM_NAME index);
#else
#define DECL_ENUM_ELEMENT( element ) #element
#define BEGIN_ENUM( ENUM_NAME ) char* gs_##ENUM_NAME [] =
#define END_ENUM( ENUM_NAME ) ; char* ToStr_##ENUM_NAME(enum \
tag##ENUM_NAME index){ return gs_##ENUM_NAME [index]; }
#endif
#endif // !MACROS_H<file_sep>#include "device_selection.h"
DeviceSelection::DeviceSelection(std::vector<unsigned int>& IDs, QWidget *parent)
: QDialog(parent)
{
ui.setupUi(this);
for (auto& id : IDs) {
ui.cbox_cameraIDs->insertItem(0, std::to_string(id).c_str());
}
}
DeviceSelection::~DeviceSelection()
{
}
void DeviceSelection::reject()
{
this->done(-1);
}
void DeviceSelection::on_btn_connect_clicked()
{
auto id = ui.cbox_cameraIDs->currentText();
if (!id.isEmpty()) {
this->done(id.toInt());
}
}
<file_sep>#include "session.h"
#include <QFileDialog>
#include <QStandardPaths>
#include "headers.h"
Session::Session(QString title, QWidget *parent)
: QGroupBox(title, parent), is_started_(false), is_paused_(false), interval_reached_(false)
{
session_layout = new QVBoxLayout(this);
session_layout->setSpacing(5);
session_layout->setContentsMargins(1, 1, 1, 1);
start_stop = new QPushButton("Start", this);
session_layout->addWidget(start_stop);
paus_resume = new QPushButton("Paus", this);
session_layout->addWidget(paus_resume);
settings_box = new QGroupBox("Settings", this);
settings_box->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
settings_box_Layout = new QVBoxLayout(this);
settings_box_Layout->setSpacing(2);
settings_box_Layout->setContentsMargins(1, 1, 1, 1);
settings_box->setLayout(settings_box_Layout);
// Settings frame
{
QGridLayout *grid_layout = new QGridLayout();
grid_layout->setContentsMargins(2, 1, 1, 1);
grid_layout->setSpacing(2);
interval = new QSpinBox(settings_box);
interval->setMinimum(1);
interval->setMaximum(99999999);
grid_layout->addWidget(interval, 1, 2);
duration = new QSpinBox(settings_box);
duration->setMinimum(2);
duration->setMaximum(99999999);
duration->setEnabled(false);
grid_layout->addWidget(duration, 2, 2);
label_interval = new QLabel("Interval [min]", settings_box);
grid_layout->addWidget(label_interval, 1, 1);
with_duration = new QCheckBox("With duration", settings_box);
grid_layout->addWidget(with_duration, 2, 1);
label_name = new QLabel("Name", settings_box);
grid_layout->addWidget(label_name, 0, 1);
name = new QLineEdit(settings_box);
grid_layout->addWidget(name, 0, 2);
settings_box_Layout->addLayout(grid_layout);
numbering_box = new QGroupBox("File numbering", settings_box);
numbering_box_layout = new QVBoxLayout(numbering_box);
numbering_box->setLayout(numbering_box_layout);
numberring_0 = new QRadioButton("Start from 0", numbering_box);
numberring_from_files = new QRadioButton("From latest file number", numbering_box);
numberring_from_files->setChecked(true);
numberring_custom = new QRadioButton("Custom", numbering_box);
numbering_box_layout->addWidget(numberring_0);
numbering_box_layout->addWidget(numberring_from_files);
custom_numbering_Layout = new QHBoxLayout(numbering_box);
custom_numbering_edit = new QLineEdit(numbering_box);
custom_numbering_edit->setValidator(new QIntValidator(0, 99999999, settings_box));
custom_numbering_edit->setEnabled(false);
custom_numbering_Layout->addWidget(numberring_custom);
custom_numbering_Layout->addWidget(custom_numbering_edit);
numbering_box_layout->addLayout(custom_numbering_Layout);
connect(numberring_custom, SIGNAL(toggled(bool)), this, SLOT(custom_numbering_state(bool)));
settings_box_Layout->addWidget(numbering_box);
path_select = new QPushButton(settings_box);
path_select->setIcon(QIcon("Resources/folder.png"));
path = new QLineEdit(settings_box);
path->setObjectName(QStringLiteral("path"));
path_Layout = new QHBoxLayout(settings_box);
path_Layout->addWidget(path);
path_Layout->addWidget(path_select);
settings_box_Layout->addLayout(path_Layout);
with_folder = new QCheckBox("Creat a folder for this session", settings_box);
settings_box_Layout->addWidget(with_folder);
}
session_layout->addWidget(settings_box);
info_box = new QGroupBox("Information", this);
info_box->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
info_box_Layout = new QVBoxLayout(info_box);
info_box_Layout->setSpacing(2);
info_box_Layout->setContentsMargins(1, 1, 1, 1);
info_box->setLayout(info_box_Layout);
// information box
{
QFormLayout *form_layout = new QFormLayout();
form_layout->setContentsMargins(2, 1, 1, 1);
form_layout->setSpacing(2);
start_time_label = new QLabel("", info_box);
finish_time_label = new QLabel("", info_box);
next_capture_time_label = new QLabel("", info_box);
form_layout->addRow("Start time:", start_time_label);
form_layout->addRow("Finish time:", finish_time_label);
form_layout->addRow("Next capture: ", next_capture_time_label);
info_box_Layout->addLayout(form_layout);
}
session_layout->addWidget(info_box);
connect(with_duration, SIGNAL(stateChanged(int)), this, SLOT(count_duraion(int)));
connect(path_select, SIGNAL(clicked()), this, SLOT(path_select_clicked()));
connect(start_stop, SIGNAL(clicked()), this, SLOT(start_stop_clicked()));
connect(paus_resume, SIGNAL(clicked()), this, SLOT(paus_resume_clicked()));
timer_next_capture = new QTimer(this);
connect(timer_next_capture, SIGNAL(timeout()), this, SLOT(check_capture_time()));
//Initialization
{
name->setText(this->title());
interval->setValue(1);
duration->setValue(2);
with_duration->setCheckState(Qt::Unchecked);
path->setText(QStandardPaths::standardLocations(QStandardPaths::PicturesLocation)[0]);
paus_resume->setEnabled(false);
info_box->setEnabled(false);
}
}
Session::~Session()
{
interval_reached_ = false;
if(is_started_)
stop();
}
void Session::start_stop_clicked()
{
if (is_started_)
stop();
else
start();
}
void Session::paus_resume_clicked()
{
if (is_paused_)
resume();
else
paus();
}
void Session::path_select_clicked()
{
auto new_path = QFileDialog::getExistingDirectory(this, "Select a folder", path->text());
if (!new_path.isEmpty())
path->setText(new_path);
}
void Session::count_duraion(int state)
{
switch (state)
{
case Qt::Unchecked:
duration->setEnabled(false);
break;
case Qt::Checked:
duration->setEnabled(true);
break;
}
}
void Session::check_capture_time()
{
auto time_now = core::Clock::now();
std::stringstream stream;
long long second = 0;
if (with_duration->isChecked()) {
second = std::chrono::duration_cast<std::chrono::seconds>(finish_time - time_now).count();
stream << std::setfill('0') << std::setw(2) << second / 3600
<< ":" << std::setfill('0') << std::setw(2) << (int)fmod(second, 3600) / 60
<< ":" << std::setfill('0') << std::setw(2) << (int)fmod(second, 60);
finish_time_label->setText(stream.str().c_str());
stream.str("");
}
if (next_capture_time <= time_now) {
interval_reached_ = true;
//std::cout << "Save path: " << full_save_path() << std::endl;
next_capture_time = core::now() + std::chrono::minutes(interval->value());
}
second = std::chrono::duration_cast<std::chrono::seconds>(next_capture_time - time_now).count();
stream << std::setfill('0') << std::setw(2) << second / 3600
<< ":" << std::setfill('0') << std::setw(2) << (int)fmod(second, 3600) / 60
<< ":" << std::setfill('0') << std::setw(2) << (int)fmod(second, 60);
next_capture_time_label->setText(stream.str().c_str());
if (with_duration->isChecked() && time_now >= finish_time) {
stop();
return;
}
}
void Session::custom_numbering_state(bool state)
{
custom_numbering_edit->setEnabled(state);
}
bool Session::must_save()
{
return interval_reached_;
}
std::string Session::full_save_path()
{
interval_reached_ = false;
auto folder_name = name->text().replace("_", "").replace(" ", "").toStdString();
std::stringstream full_path;
full_path << path->text().toStdString() << "/";
if (with_folder->isChecked())
full_path << folder_name << "/";
else {
full_path << name->text().replace("_", "").replace(" ", "").toStdString()
<< "_" << std::setfill('0') << std::setw(5) << save_index_++ << ".png";
}
return full_path.str();
}
uint32_t Session::get_filename_index(QDir& dir)
{
QFileInfoList list = dir.entryInfoList();
if (list.empty())
return 0u;
uint32_t idx = 0u;
auto base_name = name->text().replace("_", "").replace(" ", "");
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
auto num = fileInfo.baseName().split('_');
if (num.size() == 2) {
if (num[0] == base_name && num[1].toUInt() > idx)
idx = num[1].toUInt();
}
}
return ++idx;
}
void Session::start()
{
is_started_ = true;
is_paused_ = false;
interval_reached_ = false;
start_stop->setText("Stop");
info_box->setEnabled(true);
settings_box->setEnabled(false);
auto folder_name = name->text().replace("_", "").replace(" ", "");
if (with_folder->isChecked())
{
QDir dir(path->text());
QDir(path->text()).mkpath(folder_name);
}
if (numberring_0->isChecked())
save_index_ = 0u;
else if (numberring_from_files->isChecked()) {
if (with_folder->isChecked())
save_index_ = get_filename_index(QDir(path->text() + "/" + folder_name));
else
save_index_ = get_filename_index(QDir(path->text()));
}
else
save_index_ = custom_numbering_edit->text().toUInt();
std::stringstream stream;
current_time = core::Clock::now();
std::time_t now_c = std::chrono::system_clock::to_time_t(current_time);
stream << std::put_time(std::localtime(&now_c), "%b %dth at %H:%M");
start_time_label->setText(stream.str().c_str());
if (with_duration->isChecked()) {
finish_time = current_time + std::chrono::minutes(duration->value()) + std::chrono::seconds(10);
}
else
{
finish_time_label->setText("Continuous capture");
}
next_capture_time = current_time + std::chrono::minutes(interval->value());
is_paused_ = false;
paus_resume->setEnabled(true);
paus_resume->setText("Paus");
timer_next_capture->start(1000);
}
void Session::stop()
{
timer_next_capture->stop();
is_started_ = false;
start_stop->setText("Start");
info_box->setEnabled(false);
settings_box->setEnabled(true);
start_time_label->setText("");
finish_time_label->setText("");
next_capture_time_label->setText("");
is_paused_ = false;
paus_resume->setEnabled(false);
paus_resume->setText("Paus");
}
void Session::paus()
{
timer_next_capture->stop();
is_paused_ = true;
paus_resume->setText("resume");
info_box->setEnabled(false);
settings_box->setEnabled(true);
start_stop->setEnabled(false);
}
void Session::resume()
{
is_paused_ = false;
paus_resume->setText("Paus");
info_box->setEnabled(true);
settings_box->setEnabled(false);
start_stop->setEnabled(true);
auto folder_name = name->text().replace("_", "").replace(" ", "");
if (with_folder->isChecked())
{
QDir dir(path->text());
QDir(path->text()).mkpath(folder_name);
}
if (numberring_0->isChecked())
save_index_ = 0u;
else if (numberring_from_files->isChecked()) {
if (with_folder->isChecked())
save_index_ = get_filename_index(QDir(path->text() + "/" + folder_name));
else
save_index_ = get_filename_index(QDir(path->text()));
}
else
save_index_ = custom_numbering_edit->text().toUInt();
std::stringstream stream;
if (with_duration->isChecked()) {
finish_time = current_time + std::chrono::minutes(duration->value()) + std::chrono::seconds(10);
}
else
{
finish_time_label->setText("Continuous capture");
}
next_capture_time = core::Clock::now() + std::chrono::minutes(interval->value());
timer_next_capture->start(1000);
}
<file_sep>#pragma once
#ifndef HEADERS_H
#define HEADERS_H
#include <iostream>
#include <iomanip>
#include <exception>
#include <vector>
#include <array>
#include <initializer_list>
#include <string>
#include <sstream>
#include <fstream>
#include <chrono>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <memory>
#include <functional>
#include <random>
#include <limits>
#include <type_traits>
#include <typeinfo>
#include <tuple>
#include <utility>
#include <bitset>
#include <thread>
#include <future>
#include <filesystem>
#include <cmath>
namespace fs = std::experimental::filesystem;
#endif // !HEADERS_H<file_sep>#pragma once
#ifndef ENTITY_IMAGE_H
#define ENTITY_IMAGE_H
#include "entity.h"
class EntityImage : public Entity
{
private:
glm::vec2 position_;
public:
EntityImage(const glm::ivec2& size, const glm::vec2& position);
~EntityImage();
void position(const glm::vec2 new_pos);
const glm::vec2& position() const;
void set_image(const glm::ivec2& size, const std::vector<uint8_t>& pixels);
void update() override;
void draw(const glm::mat4& _view) override;
};
#endif // !ENTITY_RGB_H
<file_sep>/********************************************************************************
** Form generated from reading UI file 'device_selection.ui'
**
** Created by: Qt User Interface Compiler version 5.8.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_DEVICE_SELECTION_H
#define UI_DEVICE_SELECTION_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QDialog>
#include <QtWidgets/QFormLayout>
#include <QtWidgets/QGroupBox>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QVBoxLayout>
QT_BEGIN_NAMESPACE
class Ui_DeviceSelection
{
public:
QHBoxLayout *horizontalLayout;
QGroupBox *groupBox;
QHBoxLayout *horizontalLayout_2;
QVBoxLayout *verticalLayout;
QFormLayout *formLayout;
QLabel *label;
QComboBox *cbox_cameraIDs;
QPushButton *btn_connect;
void setupUi(QDialog *DeviceSelection)
{
if (DeviceSelection->objectName().isEmpty())
DeviceSelection->setObjectName(QStringLiteral("DeviceSelection"));
DeviceSelection->resize(289, 104);
QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(DeviceSelection->sizePolicy().hasHeightForWidth());
DeviceSelection->setSizePolicy(sizePolicy);
horizontalLayout = new QHBoxLayout(DeviceSelection);
horizontalLayout->setSpacing(6);
horizontalLayout->setContentsMargins(11, 11, 11, 11);
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
groupBox = new QGroupBox(DeviceSelection);
groupBox->setObjectName(QStringLiteral("groupBox"));
QSizePolicy sizePolicy1(QSizePolicy::Preferred, QSizePolicy::Preferred);
sizePolicy1.setHorizontalStretch(0);
sizePolicy1.setVerticalStretch(0);
sizePolicy1.setHeightForWidth(groupBox->sizePolicy().hasHeightForWidth());
groupBox->setSizePolicy(sizePolicy1);
horizontalLayout_2 = new QHBoxLayout(groupBox);
horizontalLayout_2->setSpacing(6);
horizontalLayout_2->setContentsMargins(11, 11, 11, 11);
horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2"));
verticalLayout = new QVBoxLayout();
verticalLayout->setSpacing(6);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
formLayout = new QFormLayout();
formLayout->setSpacing(6);
formLayout->setObjectName(QStringLiteral("formLayout"));
label = new QLabel(groupBox);
label->setObjectName(QStringLiteral("label"));
formLayout->setWidget(0, QFormLayout::LabelRole, label);
cbox_cameraIDs = new QComboBox(groupBox);
cbox_cameraIDs->setObjectName(QStringLiteral("cbox_cameraIDs"));
cbox_cameraIDs->setInsertPolicy(QComboBox::InsertAtTop);
formLayout->setWidget(0, QFormLayout::FieldRole, cbox_cameraIDs);
verticalLayout->addLayout(formLayout);
btn_connect = new QPushButton(groupBox);
btn_connect->setObjectName(QStringLiteral("btn_connect"));
verticalLayout->addWidget(btn_connect);
horizontalLayout_2->addLayout(verticalLayout);
horizontalLayout->addWidget(groupBox);
retranslateUi(DeviceSelection);
QMetaObject::connectSlotsByName(DeviceSelection);
} // setupUi
void retranslateUi(QDialog *DeviceSelection)
{
DeviceSelection->setWindowTitle(QApplication::translate("DeviceSelection", "Camera selection", Q_NULLPTR));
groupBox->setTitle(QApplication::translate("DeviceSelection", "Select a camera", Q_NULLPTR));
label->setText(QApplication::translate("DeviceSelection", "Camera Id:", Q_NULLPTR));
cbox_cameraIDs->setCurrentText(QString());
btn_connect->setText(QApplication::translate("DeviceSelection", "Connect to camera", Q_NULLPTR));
} // retranslateUi
};
namespace Ui {
class DeviceSelection: public Ui_DeviceSelection {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_DEVICE_SELECTION_H
<file_sep>#pragma once
#if ( !defined(ENUMS_H) || defined(GENERATE_ENUM_STRINGS) )
#if (!defined(GENERATE_ENUM_STRINGS))
#define ENUMS_H
#endif
#include "macros.h"
namespace glsl
{
BEGIN_ENUM(Attribute)
{
DECL_ENUM_ELEMENT(VERTICES),
DECL_ENUM_ELEMENT(NORMALS),
DECL_ENUM_ELEMENT(TEXTURE_COORD),
DECL_ENUM_ELEMENT(COLORS),
DECL_ENUM_ELEMENT(POSITION_INSTANCE),
DECL_ENUM_ELEMENT(TRANSFORM_INSTANCE),
DECL_ENUM_ELEMENT(COLOR_INSTANCE)
}
END_ENUM(Attribute)
BEGIN_ENUM(Uniform)
{
DECL_ENUM_ELEMENT(VIEW),
DECL_ENUM_ELEMENT(PROJECTION),
DECL_ENUM_ELEMENT(MODEL),
DECL_ENUM_ELEMENT(MODEL_VIEW),
DECL_ENUM_ELEMENT(VIEW_PROJECTION),
DECL_ENUM_ELEMENT(MODEL_VIEW_PROJECTION),
DECL_ENUM_ELEMENT(SCALE),
DECL_ENUM_ELEMENT(COLOR),
DECL_ENUM_ELEMENT(RADIUS),
DECL_ENUM_ELEMENT(OBJECT_ID),
DECL_ENUM_ELEMENT(DRAW_ID)
}
END_ENUM(Uniform)
/*BEGIN_ENUM(Texture)
{
DECL_ENUM_ELEMENT(TEXTURE_0),
DECL_ENUM_ELEMENT(TEXTURE_1),
DECL_ENUM_ELEMENT(TEXTURE_2),
DECL_ENUM_ELEMENT(TEXTURE_3)
}
END_ENUM(Texture)*/
}
namespace core
{
BEGIN_ENUM(FontName)
{
DECL_ENUM_ELEMENT(ARIAL),
DECL_ENUM_ELEMENT(VERA),
DECL_ENUM_ELEMENT(TIMES)
}
END_ENUM(FontName)
}
#endif
<file_sep>#include "sessioninfo.h"
#include <QDir>
#include <QFileDialog>
SessionInfo::SessionInfo(QWidget *parent)
: QDialog(parent), ui(new Ui::SessionInfo)
{
ui->setupUi(this);
connect(ui->txt_path, SIGNAL(textEdited(const QString&)), this, SLOT(updateFullPath(const QString&)));
connect(ui->txt_path, SIGNAL(textChanged(const QString&)), this, SLOT(updateFullPath(const QString&)));
connect(ui->txt_name, SIGNAL(textEdited(const QString&)), this, SLOT(updateFullPath(const QString&)));
ui->txt_path->setText(QDir::current().absolutePath());
ui->txt_name->setText("session");
updateFullPath("");
ui->txt_interval->setValue(5);
}
SessionInfo::~SessionInfo()
{
delete ui;
}
void SessionInfo::on_btn_load_clicked()
{
if (ui->txt_path->text() != "") {
QString path = QFileDialog::getExistingDirectory(this, "Path to save session", ui->txt_path->text());
if(path != "")
ui->txt_path->setText(path);
}
else {
QString path = QFileDialog::getExistingDirectory(this, "Path to save session");
if (path != "")
ui->txt_path->setText(path);
}
}
void SessionInfo::on_btn_start_clicked()
{
this->done(1);
}
void SessionInfo::updateFullPath(const QString& text)
{
ui->txt_fullpath->setText(ui->txt_path->text() + "/" + ui->txt_name->text() + "_0001.png");
}
<file_sep>#include "gl_utility.h"
#include "gl_vao.h"
#include "macros.h"
namespace gl
{
VAO::VAO() : vao_id_(0u), ebo_id_(0u)
{
GL_CHECK(glGenVertexArrays(1, &vao_id_));
ASSERT_IF_TRUE(vao_id_ == 0, "glGenVertexArrays() failed to generate vertex array object id !!!");
}
VAO::~VAO()
{
if (vao_id_ != 0)
glDeleteVertexArrays(1, &vao_id_);
for (auto& vbo : vbo_id_map_)
if (vbo.second != 0)
glDeleteBuffers(1, &vbo.second);
if (ebo_id_ != 0)
glDeleteBuffers(1, &ebo_id_);
}
void VAO::add_attribute(glsl::Attribute attrib_type, const void* buffer_data, const std::size_t& buffer_size, const uint8_t& attrib_size, const uint32_t& shader_location_id, bool is_instance)
{
ASSERT_IF_TRUE(vbo_id_map_.find(attrib_type) != vbo_id_map_.end(), "An attribute with name \"" + std::string(ToStr_Attribute(attrib_type)) + "\" already exist.");
uint32_t vbo(0u);
GL_CHECK(glGenBuffers(1, &vbo));
GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vbo));
GL_CHECK(glBufferData(GL_ARRAY_BUFFER, buffer_size, buffer_data, GL_STATIC_DRAW));
GL_CHECK(glVertexAttribPointer(shader_location_id, attrib_size, GL_FLOAT, GL_FALSE, 0, nullptr));
GL_CHECK(glEnableVertexAttribArray(shader_location_id));
if (is_instance)
GL_CHECK(glVertexAttribDivisor(shader_location_id, 1));
vbo_id_map_[attrib_type] = vbo;
}
void VAO::add_indices(const void* buffer_data, const std::size_t& buffer_size, std::size_t indexSize)
{
ASSERT_IF_TRUE(vbo_id_map_.empty(), "No attribute buffer exist to use index bufer for!!!");
ASSERT_IF_TRUE(ebo_id_ != 0, "An index buffer already exist.");
GL_CHECK(glGenBuffers(1, &ebo_id_));
ASSERT_IF_TRUE(ebo_id_ == 0, "glGenBuffers() failed to generate buffer id for index buffer.");
GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo_id_));
GL_CHECK(glBufferData(GL_ELEMENT_ARRAY_BUFFER, buffer_size, buffer_data, GL_STATIC_DRAW));
index_size_ = indexSize;
}
std::uint32_t VAO::buffer_id(glsl::Attribute attrib_type)
{
return vbo_id_map_[attrib_type];
}
void VAO::bind() const
{
glBindVertexArray(vao_id_);
}
void VAO::unbind() const
{
glBindVertexArray(0);
}
}
<file_sep>#pragma once
#ifndef GLSL_PROGRAM_H
#define GLSL_PROGRAM_H
#include "headers.h"
#include <glm/glm.hpp>
#include "enums.h"
namespace glsl
{
using ShaderPathList = std::initializer_list<fs::path>;
using AttributeList = std::initializer_list<Attribute>;
class Program
{
private:
uint32_t id_;
std::unordered_map<Uniform, uint8_t> uniform_map_;
std::unordered_map<Attribute, uint8_t> attribute_map_;
public:
Program(ShaderPathList shaders_file_path, AttributeList attribute_list);
~Program();
public:
const uint32_t& id() const;
void linkUniform(Uniform uniform);
void linkUniform(std::initializer_list<Uniform> uniform_list);
const uint8_t& attreibute_id(Attribute attribute);
const uint8_t& get_uniform_id(Uniform uniform);
void bind() ;
void unbind() ;
void setUniform(const Uniform& uniform, const int& value) ;
void setUniform(const Uniform& uniform, const uint32_t& value) ;
void setUniform(const Uniform& uniform, const float& value) ;
void setUniform(const Uniform& uniform, const glm::uvec2& vec) ;
void setUniform(const Uniform& uniform, const glm::uvec3& vec) ;
void setUniform(const Uniform& uniform, const glm::uvec4& vec) ;
void setUniform(const Uniform& uniform, const glm::ivec2& vec) ;
void setUniform(const Uniform& uniform, const glm::ivec3& vec) ;
void setUniform(const Uniform& uniform, const glm::ivec4& vec) ;
void setUniform(const Uniform& uniform, const glm::vec2& vec) ;
void setUniform(const Uniform& uniform, const glm::vec3& vec) ;
void setUniform(const Uniform& uniform, const glm::vec4& vec) ;
void setUniform(const Uniform& uniform, const glm::mat3& mat) ;
void setUniform(const Uniform& uniform, const glm::mat4& mat) ;
};
}
#endif //End of GLSL_PROGRAM_H
<file_sep>#ifndef DEVICE_SELECTION_H
#define DEVICE_SELECTION_H
#include <vector>
#include <QDialog>
#include "ui_device_selection.h"
class DeviceSelection : public QDialog
{
Q_OBJECT
public:
DeviceSelection(std::vector<unsigned int>& IDs, QWidget *parent = 0);
~DeviceSelection();
private:
Ui::DeviceSelection ui;
protected:
void reject() override;
private slots:
void on_btn_connect_clicked();
};
#endif // DEVICE_SELECTION_H
<file_sep>#ifndef COSTUME_GL_WIDGET_H
#define COSTUME_GL_WIDGET_H
#include <QGLWidget>
#include <memory>
#include <chrono>
#include "entity_image.h"
#include "gui_static_text.h"
#include "camera.h"
using Clock = std::chrono::high_resolution_clock;
class ImageViewer : public QGLWidget
{
Q_OBJECT
private:
std::unique_ptr<Camera> camera;
QPoint mouse_delta, mouse_prev;
bool is_mouse_middle_released;
std::shared_ptr<EntityImage> image_;
std::shared_ptr<GUI_StaticText> gui_stamp_;
public:
ImageViewer(QWidget *parent);
~ImageViewer();
void set_viewer_image(const glm::ivec2& image_size, const std::vector<uint8_t>& pixels);
protected:
void initializeGL() Q_DECL_OVERRIDE;
void paintGL() Q_DECL_OVERRIDE;
void resizeGL(int w, int h) Q_DECL_OVERRIDE;
void mouseMoveEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
void mousePressEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
void mouseReleaseEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
void mouseDoubleClickEvent(QMouseEvent * e) Q_DECL_OVERRIDE;
void wheelEvent(QWheelEvent *e) Q_DECL_OVERRIDE;
void keyPressEvent(QKeyEvent *e) Q_DECL_OVERRIDE;
void keyReleaseEvent(QKeyEvent *e) Q_DECL_OVERRIDE;
};
#endif // COSTUME_GL_WIDGET_H
| 9202d2d07aacd7a676763fda2e675b4818f94244 | [
"C++"
]
| 37 | C++ | yRezaei/capture_mv_BlueCougar-xd | 73d0b35fd0dd0a9d4a986a388a08ea6bb208c0ab | 4d26052622930a386bb973e06d8dedbc42b6629d |
refs/heads/main | <repo_name>MarijnDM/MDM_JDM_Pack<file_sep>/README.md
# MDM_JDM_Pack
JDM carpack for FiveM/GTA V. List of cars included in the files.
Where do i find the list of cars?
carlist.txt
What can you find in this list?
Name:
Link:
Poly's:
Spawnname:
How to contact me?
Discord: Marijn#1611
<file_sep>/fxmanifest.lua
fx_version 'bodacious'
games { 'gta5' }
author 'LeidenRP'
files {
'vehicles.meta',
'carvariations.meta',
'handling.meta',
'vehiclelayouts.meta',
'dlctext.meta',
'carcols.meta',
}
files {
'data/**/*.meta'
}
data_file 'HANDLING_FILE' 'data/**/handling.meta'
data_file 'VEHICLE_METADATA_FILE' 'data/**/vehicles.meta'
data_file 'CARCOLS_FILE' 'data/**/carcols.meta'
data_file 'VEHICLE_LAYOUTS_FILE' 'data/**/vehiclelayouts.meta'
data_file 'VEHICLE_VARIATION_FILE' 'data/**/carvariations.meta'
client_script 'vehicle_names.lua'
data_file 'HANDLING_FILE' 'data/**/handling.meta'
data_file 'VEHICLE_METADATA_FILE' 'data/**/vehicles.meta'
data_file 'CARCOLS_FILE' 'data/**/carcols.meta'
data_file 'VEHICLE_VARIATION_FILE' 'data/**/carvariations.meta'
data_file 'DLCTEXT_FILE' 'data/**/dlctext.meta'
data_file 'VEHICLE_LAYOUTS_FILE' 'data/**/vehiclelayouts.meta'
data_file 'CONTENT_UNLOCKING_META_FILE' 'data/**/contentunlocks.meta'
is_els 'true' | a9c6467697c48b2908a1d7990a8b7849a42fec3e | [
"Markdown",
"Lua"
]
| 2 | Markdown | MarijnDM/MDM_JDM_Pack | 9b83928f29a5f80c327779a2806f5e7b942d1f8e | 534492ba9abba887007d3dcade0fd8bd2ead3feb |
refs/heads/master | <repo_name>sebacampos/portfolio<file_sep>/README.md
# <NAME> Portfolio
(WIP) Built using the following technologies:
1. [Next.js](https://nextjs.org/)
2. [TypeScript](https://www.typescriptlang.org/)
3. [Chakra UI](https://chakra-ui.com/)
4. [Emotion](https://emotion.sh/)
<file_sep>/config/site.ts
export default {
details: {
title: '<NAME>',
tagLine: 'Full Stack Developer',
description: 'Personal portfolio of <NAME>',
url: 'https://sebastiancampos.com.ar',
},
assets: {
avatar: '/images/common/avatar.png',
// favicon: '/images/common/favicon.png',
},
socialLinks: {
twitter: '@sebacampos012',
},
social: {
twitter: 'https://twitter.com/sebacampos012',
linkedin: 'https://www.linkedin.com/in/sebastiancampos',
github: 'https://github.com/sebacampos',
youtube: 'https://www.youtube.com/watch?v=FLk8uD6FkQo',
},
}
<file_sep>/config/next-seo.ts
import siteConfig from 'config/site'
export default {
title: `${siteConfig.details.title} - ${siteConfig.details.tagLine}`, // max: 65
description: siteConfig.details.description, // max:155
canonical: siteConfig.details.url,
twitter: {
handle: siteConfig.socialLinks.twitter,
site: siteConfig.socialLinks.twitter,
cardType: 'summary_large_image',
},
openGraph: {
type: 'website',
locale: 'en_IE',
site_name: siteConfig.details.title,
url: siteConfig.details.url,
title: `${siteConfig.details.title} - ${siteConfig.details.tagLine}`, // max 35
description: siteConfig.details.description, // max 65
images: [
{
url: `${siteConfig.details.url}${siteConfig.assets.avatar}`,
width: 728,
height: 728,
alt: siteConfig.details.title,
},
],
},
}
| f4d2607862e4530efada66da54fea5ea9a988253 | [
"Markdown",
"TypeScript"
]
| 3 | Markdown | sebacampos/portfolio | 8b1e6e25463b44f7ff0de3c3050ee02f295cd091 | b113fffee3364dbef0a862c0863abe9051b9c540 |
refs/heads/main | <repo_name>RahulBirgonda/FrontEnd-Projects<file_sep>/README.md
# FrontEnd-Projects
Consists of Frontend projects built while learning web-development
<file_sep>/My-Calculator/calculator.js
disp=(num) =>{
var input= document.getElementById('display');
switch (num) {
case 1:
input.value+='1';
break;
case 2:
input.value+='2';
break;
case 3:
input.value+='3';
break;
case 4:
input.value+='4';
break;
case 5:
input.value+='5';
break;
case 6:
input.value+='6';
break;
case 7:
input.value+='7';
break;
case 8:
input.value+='8';
break;
case 9:
input.value+='9';
break;
case 0:
input.value+='0';
break;
case '.':
input.value+='.';
break;
}
}
clean =()=>{
var input = document.getElementById('display');
input.value= ''
}
backspace =()=>{
var input = document.getElementById('display');
var x=input.value;
if(x.length>0){
x=x.substring(0,x.length-1);
input.value=x;
}
}
operand=(op) =>{
var input= document.getElementById('display');
switch (op) {
case '/':
input.value+='/';
break;
case '*':
input.value+='*';
break;
case '+':
input.value+='+';
break;
case '-':
input.value+='-';
break;
case '%':
input.value+='%'
break;
}
}
equal =() =>{
var input =document.getElementById('display');
input.value=eval(input.value);
}
<file_sep>/Personal-Site/Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><NAME></title>
<link rel="stylesheet" href="css/style.css">
<link rel="icon" href="favicon.ico">
<link href="https://fonts.googleapis.com/css?family=Merriweather|Merriweather+Sans|Montserrat|Sacramento&display=swap" rel="stylesheet">
</head>
<body>
<div class="top-container">
<img src="images/cloud.svg" width="150px;" height="100px;" class="top-cloud">
<h1>I'm Rahul</h1>
<h2>A Webdeveloper</h2>
<img src="images/cloud.svg" width="150px;" height="100px; class" class="bottom-cloud">
<img src="images/mountain.svg" width="500px;" height="300px;" alt="A mountain">
</div>
<div class="middle-container">
<div class="profile">
<img src="images/profilepic2.jpg" width="25%" height="250px" alt="profile pic">
<h2>Hello.</h2>
<p class="intro">I am a Data Analyst and a website Developer graduated from VNR Vjiet. I
<img src="images\heavy-black-heart_2764.png" width="15px;" height="15px;"> Watching Movies.</p>
</div>
<hr>
<div class="skills">
<h2>My Skills.</h2>
<div class="skill-row">
<img class="web-img" src="images/MySkills.svg" alt="">
<h3>Design & Development</h3>
<p>I wanted to make my own Web Applications. Over time, <br>I have gained a wealth experience in Designing and Developing My own Web Apps
<br><br><br><br>
<img class="data-img" src="images/DataAnalytics.svg" width="100px;" alt="Image">
<h3>Data Science</h3>
<p>
I'm very much interested in Data Science. I want <br> to be a Data Scientist. I'm very passionate <br> about Data Science and Data Analytics.</p>
</div>
<hr>
<div class="contact-me">
<h2>Get In Touch</h2>
<h3>A big hai to all Data Scientists.</h3>
<p class="contact-message">You are welcomed, if you are passionate <br>about Data Science like me, <br>let's help each other in learning <br>and achieve our dreams.</p>
<br><a class="btn" href="mailto:<EMAIL>" style="padding-bottom: 10px;">CONTACT ME</a>
</div>
</div>
<br><br><br><br>
<div class="bottom-container">
<a class="footer-link" href="https://www.linkedin.com/">LinkedIn</a>
<a class="footer-link" href="https://twitter.com/">Twitter</a>
<a class="footer-link" href="https://www.appbrewery.co/">Website</a>
<p class="copyright">© 2020 <NAME>. @Personal Site</p>
</div>
</body>
</html>
| 40224a25422da245b5305eca058d45a6498842f1 | [
"Markdown",
"JavaScript",
"HTML"
]
| 3 | Markdown | RahulBirgonda/FrontEnd-Projects | 5e70811aa1c6d935cc002d3faaf41197bfdf9394 | a3479284863f20cb99891feb9877091ee50f7fb5 |
refs/heads/master | <repo_name>rioting-daisies/BangazonSite<file_sep>/Bangazon/Controllers/OrdersController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Bangazon.Data;
using Bangazon.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization;
using Bangazon.Models.OrderViewModels;
namespace Bangazon.Controllers
{
public class OrdersController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly ApplicationDbContext _context;
public OrdersController(ApplicationDbContext context,
UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
_context = context;
}
// This method will be called every time we need to get the current user
private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);
// GET: Orders
[Authorize]
public async Task<IActionResult> Index()
{
var currentUser = await GetCurrentUserAsync();
//var applicationDbContext = _context.Order.Include(o => o.PaymentType).Include(o => o.User).Where(o=> o.UserId == currentUser.Id);
var applicationDbContext = _context.Order.Where(o => o.PaymentTypeId != null && currentUser.Id == o.UserId);
return View(await applicationDbContext.ToListAsync());
}
// GET: Orders/Details/5
[Authorize]
public async Task<IActionResult> Details(int? id)
{
var currentuser = await GetCurrentUserAsync();
var order = await _context.Order
.Include(o => o.PaymentType)
.Include(o => o.User)
.Include(o => o.OrderProducts)
.ThenInclude(op => op.Product)
.FirstOrDefaultAsync(m => m.User == currentuser && m.PaymentTypeId == null);
if (order == null || order.OrderProducts.Count() == 0)
{
return View("EmptyCart");
}
OrderDetailViewModel viewmodel = new OrderDetailViewModel
{
Order = order
};
viewmodel.LineItems = order.OrderProducts
.GroupBy(op => op.Product)
.Select(p => new OrderLineItem
{
Product = p.Key,
Units = p.Select(l => l.Product).Count(),
Cost = p.Key.Price * p.Select(l => l.ProductId).Count()
}).ToList();
if (order == null)
{
return NotFound();
}
return View(viewmodel);
}
// GET: Orders/Create
//public IActionResult Create()
//{
// ViewData["PaymentTypeId"] = new SelectList(_context.PaymentType, "PaymentTypeId", "AccountNumber");
// ViewData["UserId"] = new SelectList(_context.ApplicationUsers, "Id", "Id");
// return View();
//}
//// POST: Orders/Create
//// To protect from overposting attacks, please enable the specific properties you want to bind to, for
//// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
//[HttpPost]
//[ValidateAntiForgeryToken]
//public async Task<IActionResult> Create([Bind("OrderId,DateCreated,DateCompleted,UserId,PaymentTypeId")] Order order)
//{
// if (ModelState.IsValid)
// {
// _context.Add(order);
// await _context.SaveChangesAsync();
// return RedirectToAction(nameof(Index));
// }
// ViewData["PaymentTypeId"] = new SelectList(_context.PaymentType, "PaymentTypeId", "AccountNumber", order.PaymentTypeId);
// ViewData["UserId"] = new SelectList(_context.ApplicationUsers, "Id", "Id", order.UserId);
// return View(order);
//}
// GET: Orders/Edit/5
[Authorize]
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var currentuser = await GetCurrentUserAsync();
var order = await _context.Order
.Include(o => o.User).ThenInclude(u => u.PaymentTypes)
.Include(o => o.OrderProducts)
.ThenInclude(op => op.Product)
.FirstOrDefaultAsync(o => o.User == currentuser && o.OrderId == id);
if (order == null)
{
return NotFound();
}
OrderDetailViewModel model = new OrderDetailViewModel
{
LineItems = order.OrderProducts
.GroupBy(op => op.Product)
.Select(p => new OrderLineItem
{
Product = p.Key,
Units = p.Select(l => l.Product).Count(),
Cost = p.Key.Price * p.Select(l => l.ProductId).Count()
}).ToList()
};
foreach (OrderLineItem orderItem in model.LineItems)
{
if (orderItem.Units > orderItem.Product.Quantity)
{
ViewBag.UnitsOver = orderItem.Units - orderItem.Product.Quantity;
return View("CheckoutError", orderItem);
}
}
if (order.User.PaymentTypes.Where(pt=> pt.IsDeleted == false).Count() == 0)
{
return RedirectToAction("Create", "PaymentTypes");
}
ViewData["PaymentTypeId"] = new SelectList(order.User.PaymentTypes, "PaymentTypeId", "Description", order.PaymentTypeId);
return View(order);
}
// POST: Orders/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public async Task<IActionResult> Edit(int id, [Bind("OrderId,DateCreated,DateCompleted,UserId,PaymentTypeId,OrderProducts")] Order order)
{
if (id != order.OrderId)
{
return NotFound();
}
var user = await GetCurrentUserAsync();
ModelState.Remove("User");
ModelState.Remove("UserId");
ModelState.Remove("DateCompleted");
var orderProducts = await _context.OrderProduct.Where(op => op.OrderId == order.OrderId).ToListAsync();
if (ModelState.IsValid)
{
try
{
foreach(OrderProduct op in orderProducts)
{
Product product = await _context.Product.Where(p => p.ProductId == op.ProductId).SingleAsync();
product.Quantity -= 1;
_context.Update(product);
}
order.DateCompleted = DateTime.Now;
order.UserId = user.Id;
_context.Update(order);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!OrderExists(order.OrderId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["PaymentTypeId"] = new SelectList(_context.PaymentType, "PaymentTypeId", "Description", order.PaymentTypeId);
return View(order);
}
//////////////////////////////Created by Alex
// GET: Orders/Delete/5
[Authorize]
public async Task<IActionResult> Delete(int? id)
{
var currentuser = await GetCurrentUserAsync();
var order = await _context.Order
.Include(o => o.PaymentType)
.Include(o => o.User)
.Include(o => o.OrderProducts)
.ThenInclude(op => op.Product)
.Where(o => o.OrderId == id)
.FirstOrDefaultAsync(m => m.UserId == currentuser.Id.ToString() && m.PaymentTypeId == null);
if (order == null || order.OrderProducts.Count() == 0)
{
return NotFound();
}
OrderDetailViewModel viewmodel = new OrderDetailViewModel
{
Order = order
};
//OrderLineItem LineItem = new OrderLineItem();
viewmodel.LineItems = order.OrderProducts
.GroupBy(op => op.Product)
.Select(p => new OrderLineItem
{
Product = p.Key,
Units = p.Select(l => l.Product).Count(),
Cost = p.Key.Price * p.Select(l => l.ProductId).Count()
}).ToList();
if (order == null)
{
return NotFound();
}
return View(viewmodel);
}
// POST: Orders/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[Authorize]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var order = await _context.Order.FindAsync(id);
_context.Order.Remove(order);
//await _context.SaveChangesAsync();
var productOrder = _context.OrderProduct
.Where(op => op.OrderId == id)
.Select(op => op.OrderProductId);
foreach (var po in productOrder)
{
var deleteProductOrder = await _context.OrderProduct.FindAsync(po);
_context.OrderProduct.Remove(deleteProductOrder);
}
await _context.SaveChangesAsync();
return View("EmptyCart");
}
/////////When user clicks his account info, clicks into order history, clicks details on a past order, user will be shown this --
[Authorize]
public async Task<IActionResult> OrderHistoryDetail(int id)
{
var currentuser = await GetCurrentUserAsync();
var order = await _context.Order
.Include(o => o.PaymentType)
.Include(o => o.User)
.Include(o => o.OrderProducts)
.ThenInclude(op => op.Product)
.Where(o => o.OrderId == id)
.FirstOrDefaultAsync(m => m.UserId == currentuser.Id.ToString() && m.PaymentTypeId != null);
if (order == null || order.OrderProducts.Count() == 0)
{
return NotFound();
}
OrderDetailViewModel viewmodel = new OrderDetailViewModel
{
Order = order
};
//OrderLineItem LineItem = new OrderLineItem();
viewmodel.LineItems = order.OrderProducts
.GroupBy(op => op.Product)
.Select(p => new OrderLineItem
{
Product = p.Key,
Units = p.Select(l => l.Product).Count(),
Cost = p.Key.Price * p.Select(l => l.ProductId).Count()
}).ToList();
if (order == null)
{
return NotFound();
}
return View(viewmodel);
}
[Authorize]
public async Task<IActionResult> AddToCart([FromRoute] int id)
{
// Find the product requested
Product productToAdd = await _context.Product.SingleOrDefaultAsync(p => p.ProductId == id);
// Get the current user
var user = await GetCurrentUserAsync();
// See if the user has an open order
var openOrder = await _context.Order.SingleOrDefaultAsync(o => o.User == user && o.PaymentTypeId == null);
Order currentOrder = new Order();
// If no order, create one, else add to existing order
if (openOrder == null)
{
currentOrder.UserId = user.Id;
currentOrder.PaymentType = null;
_context.Add(currentOrder);
await _context.SaveChangesAsync();
}
else
{
currentOrder = openOrder;
}
OrderProduct item = new OrderProduct
{
OrderId = currentOrder.OrderId,
ProductId = productToAdd.ProductId
};
/*currentOrder.OrderProducts.Add(item);*/
_context.Add(item);
await _context.SaveChangesAsync();
return RedirectToAction("Details", "Products", new { id = productToAdd.ProductId });
}
//this is the delete method that will delete a product from the user's shopping cart
[Authorize]
public async Task<IActionResult> DeleteShoppingCartItem(int orderId, int productId)
{
var currentuser = await GetCurrentUserAsync();
var order = await _context.Order
.Include(o => o.PaymentType)
.Include(o => o.User)
.Include(o => o.OrderProducts)
.ThenInclude(op => op.Product)
.FirstOrDefaultAsync(m => m.UserId == currentuser.Id.ToString() && m.PaymentTypeId == null);
var orderProduct = _context.OrderProduct
.Where(op => op.OrderId == orderId && op.ProductId == productId)
.FirstOrDefault();
_context.Remove(orderProduct);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Details));
}
private bool OrderExists(int id)
{
return _context.Order.Any(e => e.OrderId == id);
}
}
/*
*
* Just in case we need later. was in Order Detail. -JH n JE
if (id == null)
{
return NotFound();
}
var order = await _context.Order
.Include(o => o.PaymentType)
.Include(o => o.User)
.FirstOrDefaultAsync(m => m.OrderId == id);
if (order == null)
{
return NotFound();
}*/
}<file_sep>/Bangazon/Migrations/20190719223940_BangazonTables1.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace Bangazon.Migrations
{
public partial class BangazonTables1 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "PaymentType",
keyColumn: "PaymentTypeId",
keyValue: 1);
migrationBuilder.DeleteData(
table: "PaymentType",
keyColumn: "PaymentTypeId",
keyValue: 2);
migrationBuilder.AddColumn<bool>(
name: "IsDeleted",
table: "PaymentType",
nullable: false,
defaultValue: false);
migrationBuilder.UpdateData(
table: "AspNetUsers",
keyColumn: "Id",
keyValue: "00000000-ffff-ffff-ffff-ffffffffffff",
columns: new[] { "ConcurrencyStamp", "PasswordHash" },
values: new object[] { "c16a9ee3-e88e-4180-99f9-21f89827aa8a", "<KEY> });
migrationBuilder.UpdateData(
table: "AspNetUsers",
keyColumn: "Id",
keyValue: "00000001-ffff-ffff-ffff-ffffffffffff",
columns: new[] { "ConcurrencyStamp", "PasswordHash" },
values: new object[] { "02bef034-d531-45a6-a458-101520cff619", "<KEY> });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsDeleted",
table: "PaymentType");
migrationBuilder.UpdateData(
table: "AspNetUsers",
keyColumn: "Id",
keyValue: "00000000-ffff-ffff-ffff-ffffffffffff",
columns: new[] { "ConcurrencyStamp", "PasswordHash" },
values: new object[] { "b20e338b-b4f7-4506-9d51-cca1b8f37703", "<KEY> });
migrationBuilder.UpdateData(
table: "AspNetUsers",
keyColumn: "Id",
keyValue: "00000001-ffff-ffff-ffff-ffffffffffff",
columns: new[] { "ConcurrencyStamp", "PasswordHash" },
values: new object[] { "00d78c96-8839-4e1f-947b-deaae130e52a", "<KEY> });
migrationBuilder.InsertData(
table: "PaymentType",
columns: new[] { "PaymentTypeId", "AccountNumber", "Description", "UserId" },
values: new object[] { 1, "86753095551212", "American Express", "00000000-ffff-ffff-ffff-ffffffffffff" });
migrationBuilder.InsertData(
table: "PaymentType",
columns: new[] { "PaymentTypeId", "AccountNumber", "Description", "UserId" },
values: new object[] { 2, "4102948572991", "Discover", "00000000-ffff-ffff-ffff-ffffffffffff" });
}
}
}
<file_sep>/Bangazon/Models/OrderViewModels/OrderDetailViewModel.cs
using System.Collections.Generic;
namespace Bangazon.Models.OrderViewModels
{
public class OrderDetailViewModel
{
public Order Order { get; set; }
public OrderProduct OrderProduct { get; set; }
public List<OrderLineItem> LineItems { get; set; }
public readonly Product Product;
public double TotalCost
{
get
{
var sum = 0.0;
foreach(var li in LineItems)
{
sum += li.Cost;
}
return sum;
}
}
}
}<file_sep>/Bangazon/Models/ProductViewModels/ProductTypesViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Bangazon.Models.ProductViewModels
{
public class ProductTypesViewModel
{
public List<GroupedProducts> GroupedProducts { get; set; }
public List<ProductType> ProductTypes { get; set; }
}
}<file_sep>/README.md
# Welcome to Bangazon!!
Welcome to our the site that will steal all the money from <NAME> with our superior in every way E-Commerce site. Prices can not be beat, and we use
teleportation with the help of our chief scientists who figured out Star Trek technology so you can instantly get your items (if it changes in size Bangazon is not responsible...).
## Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.
### Prerequisites
1. A computer
2. Visual Studio
3. Azure Data Studio
### Installing
A step by step series of examples that tell you how to get a development env running
Open up git bash / terminal and clone down the repository onto your local machine
Open the BangazonWorkSite directory in Visual Studio
Locate the BangazonAPI.sql file in the project
Copy and paste the contents into a new query in Azure Data Studio and run the query
Refresh the databases on the explorer to ensure that the database was created
Head back on over to Visual Studio and Run the application (make sure the BangazonSite server is selected)
Once the application runs, you should now see the application launch in your browser.
Click around and buy stuff, edit stuff, delete stuff, and sell stuff.
## Authors
* <NAME>
* <NAME>
* <NAME>
* <NAME>
## Acknowledgments
* Hat tip to anyone whose code was used
* Kudos to the new building
* Inspiration - Not Jeff Bezos....
* Thanks to Andy and Leah for being our coding Grand Wizards when we get stuck.
<file_sep>/Bangazon/Models/ProductViewModels/ProductListViewModel.cs
using System.Collections.Generic;
using Bangazon.Models;
using Bangazon.Data;
namespace Bangazon.Models.ProductViewModels
{
public class ProductListViewModel
{
public List<ProductDetailViewModel> ProductsWithSales { get; set; }
public readonly Product Product;
}
}<file_sep>/Bangazon/Controllers/ProductsController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Bangazon.Data;
using Bangazon.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization;
using Bangazon.Models.ProductViewModels;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Bangazon.ViewComponents;
namespace Bangazon.Controllers
{
public class ProductsController : Controller
{
private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private readonly IHostingEnvironment hostingEnvironment;
public ProductsController(ApplicationDbContext context,
UserManager<ApplicationUser> userManager, IHostingEnvironment hostingEnvironment)
{
_context = context;
_userManager = userManager;
this.hostingEnvironment = hostingEnvironment;
}
// This method will be called every time we need to get the current user
private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);
// The product index view has been changed to show the 20 products needed for the homepage model.
// The index controller also adds a search bar, with a dropdown filter to allow searches by city,
// product name, or both.
// GET: Products
public async Task<IActionResult> Index(string searchString, string SearchBar)
{
ViewData["CurrentFilter"] = searchString;
ViewData["SearchBar"] = SearchBar;
var currentUser = GetCurrentUserAsync().Result;
var applicationDbContext = _context.Product.Include(p => p.ProductType).Include(p => p.User);
var products = applicationDbContext.OrderByDescending(p => p.DateCreated).Take(20);
if (!String.IsNullOrEmpty(searchString))
{
switch (SearchBar)
{
case "1":
products = products.Where(p => p.City.ToUpper().Contains(searchString.ToUpper()));
break;
case "2":
products = products.Where(p => p.Title.ToUpper().Contains(searchString.ToUpper()));
break;
default:
products = products.Where(p => p.Title.ToUpper().Contains(searchString.ToUpper())
|| p.City.ToUpper().Contains(searchString.ToUpper()));
break;
}
}
return View(await products.ToListAsync());
}
// GET: Products/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var product = await _context.Product
.Include(p => p.ProductType)
.Include(p => p.User)
.FirstOrDefaultAsync(m => m.ProductId == id);
if (product == null)
{
return NotFound();
}
int count = await GetItemsAsync(product.ProductId);
ViewBag.ProductCount = count;
return View(product);
}
// GET: Products/Create
// user must be authorized to create a product that they want to sell
[Authorize]
public async Task<IActionResult> Create()
{
//ViewData["ProductTypeId"] = new SelectList(_context.ProductType, "ProductTypeId", "Label");
//ViewData["UserId"] = new SelectList(_context.ApplicationUsers, "Id", "Id");
var viewModel = new ProductCreateViewModel
{
AvailableProductTypes = await _context.ProductType.ToListAsync(),
};
return View(viewModel);
}
// POST: Products/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public async Task<IActionResult> Create(ProductCreateViewModel viewModel)
{
//ViewData["ProductTypeId"] = new SelectList(_context.ProductType, "ProductTypeId", "Label", product.ProductTypeId);
//ViewData["UserId"] = new SelectList(_context.ApplicationUsers, "Id", "Id", product.UserId);
ModelState.Remove("Product.ProductType");
ModelState.Remove("Product.User");
ModelState.Remove("Product.UserId");
if (ModelState.IsValid)
{
string uniqueFileName = null;
// If the Photo property on the incoming model object is not null, then the user
// has selected an image to upload.
if (viewModel.Photo != null)
{
// The image must be uploaded to the images folder in wwwroot
// To get the path of the wwwroot folder we are using the inject
// HostingEnvironment service provided by ASP.NET Core
string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "images");
// To make sure the file name is unique we are appending a new
// GUID value and and an underscore to the file name
uniqueFileName = Guid.NewGuid().ToString() + "_" + viewModel.Photo.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
// Use CopyTo() method provided by IFormFile interface to
// copy the file to wwwroot/images folder
viewModel.Photo.CopyTo(new FileStream(filePath, FileMode.Create));
}
var product = viewModel.Product;
var currUser = await GetCurrentUserAsync();
product.ImagePath = uniqueFileName;
product.UserId = currUser.Id;
_context.Add(product);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
viewModel.AvailableProductTypes = await _context.ProductType.ToListAsync();
return View(viewModel);
}
// GET: Products/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var product = await _context.Product.FindAsync(id);
if (product == null)
{
return NotFound();
}
return View(product);
}
// POST: Products/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public async Task<IActionResult> Edit(int id, [Bind("ProductId,DateCreated,Description,Title,Price,Quantity,UserId,City,ImagePath,Active,ProductTypeId")] Product product)
{
if (id != product.ProductId)
{
return NotFound();
}
ModelState.Remove("User");
ModelState.Remove("ProductTypeId");
ModelState.Remove("Title");
ModelState.Remove("Description");
ModelState.Remove("UserId");
var productToUpdate = await _context.Product.FindAsync(id);
productToUpdate.Quantity = product.Quantity;
var currentUser = await GetCurrentUserAsync();
if (ModelState.IsValid)
{
try
{
productToUpdate.User = currentUser;
_context.Update(productToUpdate);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(product.ProductId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Details", "Products", new { id });
}
return View(product);
}
// GET: Products/Delete/5
[Authorize]
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var product = await _context.Product
.Include(p => p.ProductType)
.Include(p => p.User)
.FirstOrDefaultAsync(m => m.ProductId == id);
if (product == null)
{
return NotFound();
}
return View(product);
}
// POST: Products/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[Authorize]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var product = await _context.Product.FindAsync(id);
_context.Product.Remove(product);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
public async Task<IActionResult> Types()
{
var model = new ProductTypesViewModel
{
// Build list of Product instances for display in view
// LINQ is awesome
GroupedProducts = await (
from t in _context.ProductType
join p in _context.Product
on t.ProductTypeId equals p.ProductTypeId
group new { t, p } by new { t.ProductTypeId, t.Label } into grouped
select new GroupedProducts
{
TypeId = grouped.Key.ProductTypeId,
TypeName = grouped.Key.Label,
ProductCount = grouped.Select(x => x.p.ProductId).Count(),
Products = grouped.Select(x => x.p).Take(3)
}).ToListAsync(),
ProductTypes = await (_context.ProductType.ToListAsync())
};
return View(model);
}
[Authorize]
public async Task<IActionResult> MyProducts()
{
var currentUser = await GetCurrentUserAsync();
var products = await _context.Product.Include(p => p.ProductType)
.Include(p => p.User)
.Where(p => p.User == currentUser)
.OrderByDescending(p => p.DateCreated).ToListAsync();
var orderProducts = await _context.OrderProduct
.Include(op => op.Order)
.Where(op => op.Order.PaymentTypeId != null).ToListAsync();
var model = new ProductListViewModel()
{
ProductsWithSales = (
from op in orderProducts
join p in products
on op.ProductId equals p.ProductId
group new { op, p } by new { op.ProductId, p } into grouped
select new ProductDetailViewModel
{
Product = grouped.Key.p,
UnitsSold = grouped.Select(x => x.p.ProductId).Count()
}).ToList()
};
foreach(Product p in products)
{
if (!model.ProductsWithSales.Exists(ps => ps.Product.ProductId == p.ProductId))
{
model.ProductsWithSales.Add(new ProductDetailViewModel { Product = p, UnitsSold = 0 });
}
}
return View(model);
}
private bool ProductExists(int id)
{
return _context.Product.Any(e => e.ProductId == id);
}
private async Task<int> GetItemsAsync(int productId)
{
var user = await GetCurrentUserAsync();
// See if the user has an open order
var openOrder = await _context.Order.SingleOrDefaultAsync(o => o.User == user && o.PaymentTypeId == null);
var product = await _context.Product.Where(p => p.ProductId == productId).SingleOrDefaultAsync();
if (openOrder == null)
{
return product.Quantity;
}
var cartList = await _context.OrderProduct.Where(op => op.OrderId == openOrder.OrderId && op.ProductId == product.ProductId).ToListAsync();
int productCount = product.Quantity - cartList.Count();
return productCount;
}
}
}
<file_sep>/Bangazon/Models/ProductViewModels/ProductCreateViewModel.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Bangazon.Models.ProductViewModels
{
public class ProductCreateViewModel
{
public Product Product { get; set; }
public IFormFile Photo { get; set; }
public List<ProductType> AvailableProductTypes { get; set; }
public List<SelectListItem> ProductTypeOptions
{
get
{
if(AvailableProductTypes == null)
{
return null;
}
var pt = AvailableProductTypes?.Select(p => new SelectListItem(p.Label, p.ProductTypeId.ToString())).ToList();
pt.Insert(0, new SelectListItem("Select Product Type", null));
return pt;
}
}
}
}
<file_sep>/Bangazon/ViewComponents/ProductCountViewComponent.cs
// Author: <NAME> This view component updates the product quantity for individual users when adding products to the cart.
// It allows the correct remaining quantity to be displayed without updating the quantity in the database.
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bangazon.Models;
using Microsoft.AspNetCore.Identity;
using Bangazon.Data;
namespace Bangazon.ViewComponents
{
public class ProductCountViewModel
{
public int ProductCount { get; set; }
}
public class ProductCountViewComponent : ViewComponent
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly ApplicationDbContext _context;
public ProductCountViewComponent(ApplicationDbContext context,
UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
_context = context;
}
// This method will be called every time we need to get the current user
private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);
public async Task<IViewComponentResult> InvokeAsync(int productId)
{
var quantityRemaining = await GetItemsAsync(productId);
ProductCountViewModel model = new ProductCountViewModel
{
ProductCount = quantityRemaining
};
return View(model);
}
private async Task<int> GetItemsAsync(int productId)
{
var user = await GetCurrentUserAsync();
// See if the user has an open order
var openOrder = await _context.Order.SingleOrDefaultAsync(o => o.User == user && o.PaymentTypeId == null);
var product = await _context.Product.Where(p => p.ProductId == productId).SingleOrDefaultAsync();
if (openOrder == null)
{
return product.Quantity;
}
var cartList = await _context.OrderProduct.Where(op => op.OrderId == openOrder.OrderId && op.ProductId == product.ProductId).ToListAsync();
int productCount = product.Quantity - cartList.Count();
if (productCount < 0)
{
productCount = 0;
}
return productCount;
}
}
} | f07be1050e7b46be3ee179483adb88efcf28ba32 | [
"Markdown",
"C#"
]
| 9 | C# | rioting-daisies/BangazonSite | 6070f7e0f1ce0a93d55d5f2e85ad99038da42712 | 518795c9a96431d322e417a42dbb920ad887d435 |
refs/heads/master | <repo_name>lvyueyang/draw<file_sep>/src/plugin/MindEditor/index.js
import { Graph, Shape } from '@antv/x6'
import { maxBy } from 'lodash'
import dagre from 'dagre'
import { uuid, mindDataFormat, createHtmlNodeBody, computedElementSize } from '@/plugin/MindEditor/utils'
const NODE_H_SPACING = 100 // 节点间水平间距
const NODE_V_SPACING = 30 // 节点间垂直间距
class MindEditor {
/**
* @param {Object} options
* @param {HTMLElement} options.container 容器节点
* */
constructor (options) {
console.clear()
this.options = options
this.layoutOptions = {
rankdir: 'LR', // LR RL TB BT
...options.layoutOptions
}
this.options.container.classList.add('x6-mind-draw')
this.editorInput = null
createHtmlNodeBody()
this.registerNode()
this.graph = this.initEditor()
this.init()
console.log(this.graph)
}
initEditor () {
const {
container,
width,
height
} = this.options
const graph = new Graph({
container,
width,
height,
keyboard: {
enabled: true,
global: false
},
// 选中
selecting: {
enabled: true,
rubberband: true // 启用框选
},
showNodeSelectionBox: true,
showEdgeSelectionBox: true,
multiple: true, // 多选
grid: {
size: 1
},
panning: {
enabled: true,
modifiers: 'alt'
},
// 剪切板
clipboard: {
enabled: true
},
// 调节节点大小
resizing: {
enabled: false
},
// 滚轮缩放
mousewheel: {
enabled: true
}
})
return graph
}
initData () {
const data = {
isRoot: true,
id: 'Root',
value: 'Root',
children: [
{
id: 'SubTreeNode1',
value: 'SubTreeNode1',
children: [
{
id: 'SubTreeNode1.1',
value: 'SubTreeNode1.1'
},
{
id: 'SubTreeNode1.2',
value: 'SubTreeNode1.2'
}
]
},
{
id: 'SubTreeNode2',
value: 'SubTreeNode2'
}
]
}
return mindDataFormat(data)
}
init () {
const { graph } = this
// const dagre = new Layout({
// type: 'dagre',
// rankdir: 'LR',
// align: 'UL',
// ranksep: 30,
// nodesep: 15,
// controlPoints: true
// })
const data = this.initData()
// console.log('data:', data)
graph.fromJSON(data)
// 添加根节点
// this.createRootNode()
this.editorInput = this.createInput()
this.layout()
// 居中布局
graph.centerContent()
// 启用历史记录
graph.enableHistory()
// 添加键盘事件
this.keyboardEvent()
// 添加事件监听
this.event()
// const allNodes = graph.getNodes()
// for (const node of allNodes) {
// console.log(node.size())
// const { width, height } = node.size()
// node.resize(width, height)
// }
}
layout () {
const { graph, layoutOptions } = this
const { rankdir } = layoutOptions
const nodes = graph.getNodes()
const edges = graph.getEdges()
const g = new dagre.graphlib.Graph()
g.setGraph({ rankdir, nodesep: 40, ranksep: 40 })
g.setDefaultEdgeLabel(() => ({}))
nodes.forEach((node) => {
const { width, height } = node.size()
g.setNode(node.id, { width, height })
})
edges.forEach((edge) => {
const source = edge.getSource()
const target = edge.getTarget()
g.setEdge(source.cell, target.cell)
})
dagre.layout(g)
graph.freeze()
g.nodes().forEach((id) => {
const node = graph.getCell(id)
if (node) {
const pos = g.node(id)
node.position(pos.x, pos.y)
}
})
edges.forEach((edge) => {
const source = edge.getSourceNode()
const target = edge.getTargetNode()
const sourceBBox = source.getBBox()
const targetBBox = target.getBBox()
console.log(sourceBBox, targetBBox)
if ((rankdir === 'LR' || rankdir === 'RL') && sourceBBox.y !== targetBBox.y) {
const gap = rankdir === 'LR'
? targetBBox.x - sourceBBox.x - sourceBBox.width
: -sourceBBox.x + targetBBox.x + targetBBox.width
const fix = rankdir === 'LR' ? sourceBBox.width : 0
const x = sourceBBox.x + fix + gap / 2
edge.setVertices([
{ x, y: sourceBBox.center.y },
{ x, y: targetBBox.center.y }
])
} else if (
(rankdir === 'TB' || rankdir === 'BT') &&
sourceBBox.x !== targetBBox.x
) {
const gap =
rankdir === 'TB'
? targetBBox.y - sourceBBox.y - sourceBBox.height
: -sourceBBox.y + targetBBox.y + targetBBox.height
const fix = rankdir === 'TB' ? sourceBBox.height : 0
const y = sourceBBox.y + fix + gap / 2
edge.setVertices([
{ x: sourceBBox.center.x, y },
{ x: targetBBox.center.x, y }
])
} else {
edge.setVertices([])
}
})
graph.unfreeze()
}
// 创建输入框
createInput () {
const input = document.createElement('div')
input.setAttribute('id', 'MindEditorInput')
input.setAttribute('contenteditable', 'true')
input.classList.add('x6-mind-input')
document.body.appendChild(input)
input.show = ({
x,
y,
width,
height,
value,
onBlur
}) => {
input.classList.remove('hide')
input.style.left = x + 'px'
input.style.top = y + 'px'
input.style.minWidth = width + 'px'
input.style.minHeight = height + 'px'
input.classList.add('show')
input.innerHTML = value
input.focus()
input.onblur = (e) => {
if (typeof onBlur === 'function') onBlur(e)
}
}
input.hide = () => {
input.classList.remove('show')
input.classList.add('hide')
}
return input
}
// 注册自定义节点
registerNode () {
// 重名时是否覆盖
const overwrite = true
Graph.registerHTMLComponent('mindNode', (node) => {
const data = node.getData()
const {
value,
className
} = data
const wrap = document.createElement('div')
wrap.setAttribute('class', `x6-mind-node ${className || ''}`)
wrap.innerHTML = value
// 设置节点尺寸
const {
width,
height
} = computedElementSize(wrap)
node.resize(width, height)
return wrap
}, overwrite)
}
// 创建连线
createEdge ({
source,
target
}) {
const edge = new Shape.Edge({
source: source,
target: target,
connector: {
name: 'rounded'
},
attrs: {
line: {
sourceMarker: false,
targetMarker: false
}
}
})
return edge
}
// 创建根节点
createRootNode () {
this.graph.addNode({
shape: 'html',
html: 'mindNode',
data: {
root: true,
value: 'Root',
className: 'x6-mind-root-node'
},
ports: {
groups: {
RC: {
position: 'right',
attrs: {
circle: {
r: 0,
magnet: true,
strokeWidth: 0
}
}
}
},
items: [
{
group: 'RC'
}
]
}
})
}
// 创建普通节点
createNode ({
x,
y
}, value) {
const node = this.graph.createNode({
shape: 'html',
html: 'mindNode',
x,
y,
data: {
value
},
ports: {
groups: {
LC: {
position: 'left',
attrs: {
circle: {
r: 0,
magnet: true,
strokeWidth: 0
}
}
},
RC: {
position: 'right',
attrs: {
circle: {
r: 0,
magnet: true,
strokeWidth: 0
}
}
}
},
items: [
{
group: 'LC'
},
{
group: 'RC'
}
]
}
})
return node
}
// 获取选中的节点,多个时返回最后一个
getSelectLastNode () {
const { graph } = this
const cells = graph.getSelectedCells()
if (!cells.length) return false
const selectNode = cells[cells.length - 1]
return selectNode
}
// 获取选中节点,父子都存在时移除子节点
getSelectCell () {
const { graph } = this
const cells = graph.getSelectedCells()
// return cells
const rootCell = cells.find(cell => graph.isRootNode(cell))
// 存在根节点的话直接拷贝根节点
if (rootCell) return [rootCell]
const newCells = []
for (const cell of cells) {
const ancestors = cell.getAncestors().filter(item => !graph.isRootNode(item))
let canPush = true
for (const ancestor of ancestors) {
if (cells.map(item => item.id).includes(ancestor.id)) {
canPush = false
}
}
if (canPush) {
newCells.push(cell)
}
}
return newCells
}
// 添加子节点
appendChildren (node) {
const { graph } = this
const selectNode = this.getSelectLastNode()
if (!selectNode) return
// 获取子节点
const children = selectNode.filterChild(item => item.isNode())
// 是否为根节点
const isRootNode = graph.isRootNode(selectNode)
// 父节点位置与尺寸
const {
x,
y
} = selectNode.position()
const {
width,
height
} = selectNode.size()
let resultX = x + width + NODE_H_SPACING
// 设置子节点位置
const newNode = node || this.createNode(
{},
`节点 ${uuid()}`
)
// 添加子节点
selectNode.addChild(newNode)
graph.resetSelection(newNode)
// 设置子节点位置
let resultY = null
if (children.length) {
// 有子节点
const maxNode = maxBy(children, (item) => item.position().y)
resultY = maxNode.position().y + NODE_V_SPACING + maxNode.size().height
resultX = maxNode.position().x
} else {
// 没有子节点
resultY = y + ((height - newNode.size().height) / 2)
}
newNode.position(resultX, resultY)
// 添加连线
graph.addEdge(this.createEdge({
source: {
cell: selectNode.id,
port: selectNode.port.ports[isRootNode ? 0 : 1].id
},
target: {
cell: newNode.id,
port: newNode.port.ports[0].id
}
}))
}
// 删除选中节点
removeSelectNodes () {
const { graph } = this
const cells = graph.getSelectedCells().filter(item => !graph.isRootNode(item))
graph.removeCells(cells)
}
// 复制选中节点
copySelectNodes () {
const { graph } = this
const cells = this.getSelectCell()
// console.log(cells.map(item => item.data.value))
if (cells.length) {
graph.copy(cells, { deep: true })
}
}
// 剪切选中节点
cutSelectNodes () {
const { graph } = this
const cells = graph.getSelectedCells().filter(item => !graph.isRootNode(item))
if (cells.length) {
graph.cut(cells)
} else {
this.copySelectNodes()
}
}
// 粘贴选中节点
pasteNodes () {
const { graph } = this
if (graph.isClipboardEmpty()) return
const cells = graph.getCellsInClipboard()
// console.log(cells)
for (const cell of cells) {
if (cell.isNode()) {
this.appendChildren(cell)
}
}
// graph.paste(cells)
// console.log(cells)
// graph.cleanSelection()
// graph.select(cells)
}
// 添加兄弟节点
appendBrother () {
const { graph } = this
const selectNode = this.getSelectLastNode()
if (!selectNode) return
const isRootNode = graph.isRootNode(selectNode)
if (isRootNode) return false
const parentNode = selectNode.getParent()
const {
x,
y
} = selectNode.position()
const { height } = selectNode.size()
const newNode = this.createNode({
x,
y: y + height + NODE_H_SPACING
}, `节点 ${uuid()}`)
parentNode.addChild(newNode)
graph.resetSelection(newNode)
// 添加连线
graph.addEdge(this.createEdge({
source: {
cell: parentNode.id,
port: parentNode.port.ports[graph.isRootNode(parentNode) ? 0 : 1].id
},
target: {
cell: newNode.id,
port: newNode.port.ports[0].id
}
}))
}
// 显示输入框编辑器
nodeShowEditorInput (node, wrap) {
const {
x,
y
} = wrap.getBoundingClientRect()
const {
width,
height
} = node.size()
this.editorInput.show({
x,
y,
width,
height,
value: node.data.value,
onBlur: (e) => {
const value = e.target.innerHTML
node.show()
node.updateData({
value
})
wrap.innerHTML = value
const {
width,
height
} = computedElementSize(wrap)
node.size(width, height)
this.editorInput.hide()
}
})
}
// 事件监听
event () {
const { graph } = this
// 双击编辑
graph.on('node:dblclick', (options) => {
const {
e,
node
} = options
const wrap = e.target
this.nodeShowEditorInput(node, wrap)
})
}
// 键盘事件
keyboardEvent () {
const { graph } = this
// 添加子节点
graph.bindKey('tab', () => {
this.appendChildren()
return false
})
// 删除节点
graph.bindKey('backspace', () => {
this.removeSelectNodes()
return false
})
// 添加兄弟节点
graph.bindKey('enter', () => {
this.appendBrother()
return false
})
// 复制节点
graph.bindKey('ctrl+c', () => {
this.copySelectNodes()
return false
})
// 剪切
graph.bindKey('ctrl+x', () => {
this.cutSelectNodes()
return false
})
// 粘贴节点
graph.bindKey('ctrl+v', () => {
this.pasteNodes()
return false
})
// 后退
graph.bindKey('ctrl+z', () => {
graph.history.undo()
return false
})
// 前进
graph.bindKey('ctrl+shift+z', () => {
graph.history.redo()
return false
})
// 全选
graph.bindKey('ctrl+a', () => {
graph.select(graph.getCells())
return false
})
}
// 历史记录状态
getHistoryState () {
const { graph } = this
return {
canRedo: graph.history.canRedo(),
canUndo: graph.history.canUndo()
}
}
}
export default MindEditor
| caae5440c282f7bb60e82e5df6556a3522359e05 | [
"JavaScript"
]
| 1 | JavaScript | lvyueyang/draw | 331b3c55b70e313f127b581633938d0e3fdb7f26 | 1732307ebc294f3455d7fca20e19f30761b0fa3a |
refs/heads/main | <repo_name>dhann4/Tutorial-Web-Development<file_sep>/02. CSS/02. CSS Layouting/04. Box Model ( CSS Layouting )/03. border/border2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Border</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="satu">Lorem ipsum dolor sit amet consectetur adipisicing elit. Quae excepturi esse earum dignissimos atque odit ipsa exercitationem beatae saepe obcaecati reprehenderit omnis quasi, at similique rem recusandae! Rem, adipisci, ab?</div>
<div class="dua">Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel veniam officiis quisquam, eius blanditiis dignissimos beatae pariatur aliquid id culpa harum voluptate quae sit similique dolore iste numquam delectus libero.</div>
</body>
</html><file_sep>/02. CSS/02. CSS Layouting/02. Display ( CSS Layouting )/display2.html
<!-- contoh untuk inline-block -->
<!DOCTYPE html>
<html>
<head>
<title>Display 2</title>
<style>
a {
background-color: pink;
width: 200px;
height: 200px;
display: inline-block;
}
/*semua tag <a> warnanya menjadi pink lalu tinggi dan lebarnya menjadi 200px, karena kita menambahkan display: inline-block;
kalau tidak kita tambahkan maka tidak terjadi apa - apa walaupun warnanya kita ubah tinggi dan lebarnya kita ubah*/
</style>
</head>
<body>
<div class="header">
<h1>Selamat Datang Di Website Kami</h1>
</div>
<div class="navigasi">
<h2>Daftar Link</h2>
<a href="#">ini adalah link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
<a href="#">Link 4</a>
</div>
<div class="main">
<h2>Judul Artikel</h2>
<img src="#">
<!-- untuk <span> di gunakan hanya di dalam teks -->
<p>
Lorem ipsum dolor sit amet, <span>consectetur adipisicing elit</span>, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
<div class="copyright">
<p>
Copyright 2021. Anime Wallpaper & Couple
</p>
</div>
</body>
</html><file_sep>/03. JavaScript/13. Array pada javascript/01. Manipulasi Array/script.js
// manipulasi array
// 1. menambah isi array
// var arr = [];
// arr[0] = "nama";
// arr[1] = 1;
// arr[2] = true;
// console.log(arr);
// 2. menghapus isi array
// var arr = ['nama','user','hewan']
// arr[1] = undefined;
// console.log(arr);var arr = ['nama','user','hewan']
// arr[1] = undefined;
// console.log(arr);
// 3. menampilkan isi array
// console.log(arr);var arr = ['nama','user', 'hewan']
// for(var i = 0; i < arr; i++ ) {
// console.log('no ke-'+ i + ':' + arr[i]);
// }
// array method
// -> length
// -> join
// -> push, pop, shift, unshift
// -> slice, splice
// -> forEach, map
// -> sort
// -> filter, find
// 1.length
// console.log(arr);var arr = ['nama','user', 'hewan']
// for(var i = 0; i < arr.length; i++ ) {
// console.log('no ke-'+ i + ':' + arr[i]);
// }
// 2. join
// var arr = ['nama', 'user', 'hewan'];
// console.log(arr.join());
// 3. push & pop
// digunakan untuk menambah atau menghapus elemen
// terakhir dalam array
// push digunakan untuk menambah elemen
// terakhir dalam array
// var arr = ['nama', 'user', 'hewan'];
// arr.push('boomm!!');
// console.log(arr.join());
// pop digunakan untuk menghapus elemen
// terakhir dalam array
// var arr = ['nama', 'user', 'hewan'];
// arr.pop();
// console.log(arr.join());
// 4. unshift & shift
// sama persis seperti push & pop,
// tapi unshift & shift digunakan untuk elemen pertama
// unshift
// var arr = ['nama', 'user', 'hewan'];
// arr.unshift('boom!!!');
// console.log(arr.join());
// shift
// var arr = ['nama', 'user', 'hewan'];
// arr.shift();
// console.log(arr.join());
// 5. slice & splice
// digunakan untuk menambah atau menghapus elemen
// di tengah dalam array
// splice
// rumus untuk splice
// splice(indexAwal, mauDihapusBerapa,
// elemenBaru1, elemenBaru2,...);
// var arr = ['nama', 'user', 'hewan'];
// arr.splice(1, 2, 'doddy','fitri');
// console.log(arr.join());
// slice
// rumus untuk slice
// slice(indexAwal, indexAkhir);
// perlu diperhatikan juga, untuk slice index awal
// akan terbawa pada index yang baru, sedangkan
// index akhir tidak akan terbawa
// var arr = ['nama', 'user', 'hewan', 'doddy','fitri'];
// var arr2 = arr.slice(1,3);
// console.log(arr.join());
// console.log(arr2.join());
// 6. forEach & map
// forEach
// var nama = ['nama','user','doddy']
// angka.forEach(function(e, i) {
// console.log('nama ke-' + i + 'adalah' + e);
// });
// map
// var angka = [1,2,3,4,5]
// var angka2 = angka.map(function(e) {
// return e * 2;
// });
// console.log(angka2.join(' - '));
// 7. sort
// untuk penggunaan sort harus di perhatikan
// yang akan di urutkan adalah angka pertamanya
// misal kita punya 1,2,10,20
// dalam sort yang akan di urutkan adalah
// 1,10,2,20
// jika ingin mengurutkan dengan sesuai maka
// kita harus menambahkan function
// var angka = [1,2,5,10,20,3,6,8,4,7]
// console.log(angka.join(' - '));
// angka.sort();
// angka.sort(function(a, b) {
// return a-b;
// });
// console.log(angka.join(' - '));
// 8. filter & find
// digunakan untuk mencari elemen pada array
// untuk find, hanya mengembalikan 1 nilai dan tidak
// menghasilkan array
// sedangkan filter, bisa mengembalikan banyak nilai
// dan bisa menghasilkan array
// filter
// var angka = [1,2,5,10,20,3,6,8,4,7]
// var angka2 = angka.filter(function(x) {
// return x == 5;
// kita juga bisa mencari angka yang lebih besar
// atau lebih kecil
// return x > 5
// return x < 5
// });
// console.log(angka2.join(' - '))
// find
// var angka = [1,2,5,10,20,3,6,8,4,7]
// var angka2 = angka.find(function(x) {
// return x == 5;
// untuk find jika kita suruh mencari angka lebih
// besar dari 5 maka yang akan di tampilkan adalah
// nilai yang pertama kali di temukannya
// contoh 6
// });
// console.log(angka2)<file_sep>/02. Javascript DOM (Document Object Model)/04. Latihan DOM 1 ( Bermain dengan warna )/script.js
const btnUbahWarna = document.getElementById('btnUbahWarna');
btnUbahWarna.onclick = function() {
// document.body.style.backgroundColor = 'lightblue';
// document.body.setAttribute('class', 'biru-muda');
document.body.classList.toggle('biru-muda');
}
const btnRandom = document.createElement('button');
const btnText = document.createTextNode('Random Color');
btnRandom.appendChild(btnText);
btnRandom.setAttribute('type', 'button');
btnUbahWarna.after(btnRandom);
btnRandom.addEventListener('click', function() {
const r = Math.round(Math.random() * 255 + 1);
const g = Math.round(Math.random() * 255 + 1);
const b = Math.round(Math.random() * 255 + 1);
document.body.style.backgroundColor = 'rgb('+ r +','+ g +','+ b +')';
});
const sRed = document.querySelector('input[name=sRed]');
const sGreen = document.querySelector('input[name=sGreen]');
const sBlue = document.querySelector('input[name=sBlue]');
sRed.addEventListener('input', function() {
const r = sRed.value;
const g = sGreen.value;
const b = sBlue.value;
document.body.style.backgroundColor = 'rgb('+ r +','+ g +','+ b +')';
});
sGreen.addEventListener('input', function() {
const r = sRed.value;
const g = sGreen.value;
const b = sBlue.value;
document.body.style.backgroundColor = 'rgb('+ r +','+ g +','+ b +')';
});
sBlue.addEventListener('input', function() {
const r = sRed.value;
const g = sGreen.value;
const b = sBlue.value;
document.body.style.backgroundColor = 'rgb('+ r +','+ g +','+ b +')';
});
document.body.addEventListener('mousemove', function(event) {
// posisi mouse
// console.log(event.clientX);
// console.log(event.clienty);
// ukuran browser
// console.log(window.innerWidth);
// console.log(window.innerHeight);
const xPos = Math.round((event.clientX / window.innerWidth) * 255);
const yPos = Math.round((event.clientY / window.innerHeight) * 255);
document.body.style.backgroundColor = 'rgb('+ xPos +','+ yPos +',100)';
});<file_sep>/02. Javascript DOM (Document Object Model)/03. DOM Events/script.js
// Event pada javascript merepresentasikan sebuah kejadian yang terjadi di dalam DOM.
// Kejadian tersebut bisa dilakukan oleh user, contohnya (mouse event, keyboard event, dll)
// ataupun dilakukan secara otomatis oleh API, contohnya (animasi selesai di jalankan, halaman selesai di load, dll)
// cara menjalankan event di javascript
// -> Event Handler
// -> Inline HTML attribute ( tidak disarankan karena pertama, kita mencampur adukkan file HTML dengan javascript. Kedua, kita memodifikasi HTML-nya padahal kita bisa menambahkan event tanpa menyentuh HTML-nya )
// -> Element method
// -> addEventListener()
// ================================================================
// -> Event Handler
// -> Inline HTML attribute
const p3 = document.querySelector('.p3');
function ubahWarnaP3 () {
p3.style.backgroundColor = 'lightblue';
}
// -> Element method
const p2 = document.querySelector('.p2');
function ubahWarnaP2 () {
p2.style.backgroundColor = 'lightblue';
}
p2.onclick = ubahWarna;
// ================================================================
// -> addEventListener()
const p4 = document.querySelector('section#b p');
p4.addEventListener('click', function() {
const ul = document.querySelector('section#b ul');
const liBaru = document.createElement('li');
const teksLiBaru = document.createTextNode('Item Baru');
liBaru.appendChild(teksLiBaru);
ul.appendChild(liBaru);
});
// ================================================================
// -> Event Handler = maka perubahan yang terakhir di lakukan akan menimpa perubahan sebelumnya
const p3 = document.querySelector('.p3');
p3.onclick = function () {
p3.style.backgroundColor = 'lightblue';
}
p3.onclick = function () {
p3.style.color = 'red';
}
// ================================================================
// -> addEventListener() = menambah perubahannya
p3.addEventListener('mouseenter', function () {
p3.style.backgroundColor = 'lightblue';
});
p3.addEventListener('mouseleave', function() {
p3.style.backgroundColor = 'lightgreen';
});
// ================================================================
// Daftar Event
// -> Mouse Event :
// -> click
// -> dblclick
// -> mouseover
// -> mouseenter
// -> mouseup
// -> whell
// -> ....
// -> Keyboard Event :
// -> keydown
// -> keypress
// -> keyup
// -> Resources Event
// -> Focus Event
// -> View Event :
// -> resize
// -> scroll
// -> Form Event :
// -> reset
// -> submit
// -> CSS Animation & Transition Event
// -> Drag & Drop Event
// -> dll.<file_sep>/03. JavaScript/12. Function pada Javascript/01. Parameter & Argument/script.js
// parameter adalah
// variable yang ditulis di dalam kurumh pada saat function di
// buat, digunakan untuk menampung nilai yang di kirimkan saat
// function di panggil.
// argument adalah
// nilai yang dikirimkan ke parameter saat fungsi dipanggil.
// contoh
// function tambah(a, b) {
// return a + b;
// }
// var coba = tambah(5, 10)
// di bagian tambah(a, b) di dalam kurung nya ada a dan b,
// itu disebut parameter.
// sedangkan di bagian tambah(5, 10) di dalam kurung nya ada
// angka 5 dan 10, itu di sebut dengan argument.
// contoh sederhana
function tambah(a, b) {
return a + b;
}
// cara 1
// var a = parseInt(prompt('Masukkan Nilai'));
// var b = parseInt(prompt('Masukkan Nilai'));
// var hasil = tambah(a, b);
// alert('hasil dari : ' + a + ' + ' + b + ' = ' + hasil);
// cara 2
// dengan menggunakan function lagi
// function kali(a, b) {
// return a * b;
// }
// var hasil = kali(tambah(1, 2), tambah(3, 4));
// alert(hasil)
// artinya adalah, sebelum masuk ke fungsi kali
// jalankan dulu fungsi tambah yaitu
// tambah(1, 2) dan tambah(3, 4)
// 1+2 = 3, 3+4 = 7
// lalu setelah itu fungsi kali di jalankan dengan mengkalikan
// hasil dari fungsi tambah yaitu, 3 * 7 = 21
// lalu bagaimana jika parameter dan argument-nya tidak sesuai?
// misalnya jika parameter-nya ada tiga, sedangkan argument-nya
// ada dua atau sebaliknya.
// maka yang terjadi adalah:
// -> jika parameter lebih sedikit dari argument,
// maka argument kelebihannya akan di abaikan
// contoh
// function tambah(a, b) {
// return a + b;
// }
// var coba = tambah(5, 10, 20);
// yang terjadi adalah nilai 20 akan di abaikan.
// lalu jika parameter lebih banyak dari argument,
// maka parameter kelebihannya akan diisi dengan nilai undefined
// contoh
// function tambah(a, b, c) {
// return a + b;
// }
// var coba = tambah(5, 10);
// maka nilai dari parameter c adalah undefined
// sebenarnya untuk pemahaman dari parameter dan argument cukup
// sampai di sini saja. Tapi khusus untuk Javascript ada lagi
// yang namanya arguments, yaitu array yang berisi nilai yang
// dikirimkan saat fungsi dipanggil
// contoh
// tambah(5, 10, 20, "hi", false);
// semua itu di tampung di dalam arguments / semi-function yang
// artinya fungsi tersebut ada tapi tidak terlihat
// lalu arguments nya bagaimana?
// arguments = [5, 10, 20, "hi", false];
// contoh untuk arguments, yaitu adanya tanda [], semua itu
// bisa di bilang sebagai indexs
// contoh sederhana
// function tambah() {
// var hasil = 0;
// for( var i = 0; i < arguments.length; i++ ) {
// hasil += arguments[i];
// }
// return hasil;
// }
// var coba = tambah(1,2,3);
// alert(hasil)<file_sep>/03. JavaScript/00. Latihan/latihan1.js
function jumlahVolumeDuaKubus(a, b) {
return a * a * a + b * b * b;
}
alert('Jumlah kubus 1 adalah : ' + jumlahVolumeDuaKubus(8, 3));<file_sep>/03. JavaScript/09. Pengkondisian/03. Switch/script.js
// syntax pada switch yaitu
// var angka = prompt('masukkan angka');
// switch( angka ) {
// case 1 :
// alert('anda memasukkan angka 1');
// break;
// case 2 :
// alert('anda memasukkan angka 2');
// break;
// case 3 :
// alert('anda memasukkan angka 2');
// break;
// default :
// alert('angka yang anda masukkan salah !');
// break;
// }
// untuk penggunaan pada prompt harus di perhatikan tipe datanya,
// jika saat si user memasukkan angka pada inputan maka yang terjadi
// adalah default yang berisikan alert angka yang anda masukkan salah,
// maka dari itu di dalam case harus di ganti menjadi case '1'
// contoh lain
// var item = prompt('masukkan nama makanan / minuman : \n ( cth: nasi, daging, susu, hamburger, softdrink )');
// switch ( item ) {
// case 'nasi':
// case 'daging':
// case 'susu':
// alert('makanan / minuman SEHAT!');
// break;
// case 'hamburger':
// case ' softdrink':
// alert('makanan / minuman TIDAK SEHAT!');
// default :
// alert('anda memasukkan nama makanan / minuman yang salah!');
// break;
// }
<file_sep>/02. Javascript DOM (Document Object Model)/02. DOM Manipulation/script.js
// Manipulasi Element
// Method-nya
// -> element.innerHTML
// -> element.style.<propertiCSS>
// -> element.setAttribute()
// -> element.getAttribute()
// -> element.removeAttribute()
// -> element.ClassList
// -> element.ClassList.add()
// -> element.ClassList.remove()
// -> element.ClassList.toggle()
// -> element.ClassList.item()
// -> element.ClassList.constains()
// -> element.ClassList.replace()
// ....
// =========================================================
// element.innerHTML
const judul = document.getElementById('judul');
judul.innerHTML = '<em>wardhanna</em>';
const sectionA = document.querySelector('section#a');
sectionA.innerHTML = '<div><p>paragraf 1</p></div>';
// =========================================================
// -> element.style.<propertiCSS>
const judul = document.querySelector('#judul');
judul.style.color = 'lightblue';
judul.style.backgroundColor = 'salmon';
// =========================================================
// -> element.setAttribute()
const judul = document.getElementsByTagName('h1')[0];
judul.setAttribute('name', 'wardhanna');
judul.getAttribute('id');
judul.removeAttribute('name');
const a = document.querySelector('section#a a');
a.setAttribute('id', 'link');
a.getAttribute('href');
a.removeAttribute('href');
// =========================================================
// element.classList
const p2 = document.querySelector('.p2');
p2.classList.add('satu');
p2.classList.add('dua');
p2.classList.add('tiga');
p2.classList.remove('label');
p2.classList.toggle('label'); // jika nilai nya true, maka class label akan di tambahkan sedangkan jika nilainya false, maka class label akan di hilangkan
document.body.classList.toggle('biru-muda');
p2.classList.item(2);
p2.classList.constains('dua');
p2.classList.contains('empat');
p2.classList.replace('tiga', 'empat');
// =========================================================
// Manipulasi Node
// Method-nya
// -> document.createElement()
// -> document.createTextNode()
// -> node.appendChild()
// -> node.insertBefore()
// -> parentNode.removeChild()
// -> parentNode.replaceChild()
// .....
// =========================================================
// -> document.createElement()
// buat elemen baru
const pBaru = document.createElement('p');
// =========================================================
// -> document.createTextNode()
const teksPBaru = document.createTextNode('paragraf baru');
// =========================================================
// -> node.appendChild()
// simpan tulisan ke dalam paragraf
pBaru.appendChild(teksPBaru);
// simpan pBaru di akhir section A
const sectionA = document.getElementById('a');
sectionA.appendChild(pBaru);
// =========================================================
// -> node.insertBefore()
const liBaru = document.createElement('li');
const teksLiBaru = document.createTextNode('Item Baru');
liBaru.appendChild(teksLiBaru);
const ul = document.querySelector('section#b ul');
const li2 = ul.querySelector('li:nth-child(2)');
ul.insertBefore(liBaru, li2);
// =========================================================
// -> parentNode.removeChild()
// const sectionA = document.getElementById('a');
const link = document.getElementsByTagName('a')[0];
sectionA.removeChild(link);
// =========================================================
// -> parentNode.replaceChild()
const sectionB = document.getElementById('b');
const p4 = sectionB.querySelector('p');
const h2Baru = document.createElement('h2');
const teksH2Baru = document.createTextNode('Judul Baru!');
h2Baru.appendChild(teksH2Baru);
sectionB.replaceChild(h2Baru, p4);
// penanda
pBaru.style.backgroundColor = 'lightgreen';
liBaru.style.backgroundColor = 'lightgreen';
h2Baru.style.backgroundColor = 'lightgreen';<file_sep>/README.md
Tutorial untuk Web Development Dasar
list :
1. HTML
2. CSS
3. JavaScript
| 1eb0aad6e8b245c713c5893f5f4cc8dc3f7989c6 | [
"JavaScript",
"HTML",
"Markdown"
]
| 10 | HTML | dhann4/Tutorial-Web-Development | d58f94f0a4d4e556d18a89d8bf7bee8abfc6bbf8 | 7d90cac8dc0426c4df9bdff286b53884d238d415 |
refs/heads/master | <file_sep>$(document).ready(function () {
var inputEmail = $('.win-email');
var btnSubmit = $('.win-email-submit');
$('#form-win-modal').submit(function (e) {
$.post('/Home/PostEmail', $('#form-win-modal').serialize(), function (data) {
if (data == '') {
inputEmail.css('border-color', 'red');
} else {
$('.modal-body p').text("Ваша заявка отправлена, наш специалист свяжется с вами в ближайшее время");
inputEmail.prop('disabled', true);
btnSubmit.prop('disabled', true);
}
});
e.preventDefault();
});
$('.win-email').on('input', function () {
inputEmail.css('border-color', '#5d89a5');
});
}); | 6775c4ccf430bc3f7da2cbd0b20a22c9136b67ae | [
"JavaScript"
]
| 1 | JavaScript | LTCreative/TestTask | e0d33b8c8c6999543aebfccad9f0b70a46fa6016 | 48c26c773b7caa39f9a0c92c6381fa44fde25e76 |
refs/heads/main | <file_sep><?
$nominal = require_once('nominal.php');
$nominal_str = implode(',',$nominal);
?>
<!DOCTYPE html>
<html>
<head>
<title>Банкомат на PHP + jQuery</title>
<link href="media/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<link href="media/style.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col align-self-center">
<form>
<div class="form-group">
<label for="nominal">Номинал в наличии</label>
<input type="text" class="form-control" id="nominal" value="<?= $nominal_str ?>" readonly>
</div>
<div class="form-group">
<label for="summa">Ваша сумма</label>
<input type="number" class="form-control" id="summa">
</div>
<button type="button" id="send" class="btn btn-primary">Отправить</button>
</form>
</div>
</div>
<br /><br />
<div class="alert alert-primary" role="alert" id="root"></div>
</div>
<script src="media/jquery.min.js"></script>
<script>
$(function() {
$('#send').on('click', function() {
$.ajax({
'type': 'get',
'data': 'summa=' + $('#summa').val(),
'url': '/ajax.php',
'success': function(data) {
$('#root').empty();
$('#root').append(data);
},
'error': function(msg) {
console.log(msg);
}
});
});
});
</script>
</body>
</html> | 1210c7f0c16ee75f6e5122ac8c0b247a599d212f | [
"PHP"
]
| 1 | PHP | mikhalkevich/bankomat | b18099d9919b6705cd8486d23314424a5bf92709 | 75e26b579b7ea89fc5a78b55be53dcce6452fdf8 |
refs/heads/master | <file_sep>// // File Validation
function validateuser() {
var first_name = document.getElementById("fname").value;
var last_name = document.getElementById("lname").value;
var email = document.getElementById("mail").value;
var tel = document.getElementById("phone").value;
var telno = /^\d{10}$/;
var re_email = document.getElementById("re-mail").value;
var password = document.getElementById("pass").value;
var re_password = document.getElementById("re-pass").value;
var regEx = /^[A-Z0-9][A-Z0-9._%+-]{0,63}@(?:[A-Z0-9-]{1,63}\.){1,125}[A-Z]{2,63}$/;
var validEmail = regEx.test(email);
var submit = true;
// alert(first_name);
if (first_name == "") {
document.getElementById("fname-msg").innerHTML="Enter first name";
submit= false;
}
if (last_name == ""){
document.getElementById("lname-msg").innerHTML="Enter last name";
submit= false;
}
if (email == "" || email.length < 1 ) {
document.getElementById("mail-msg").innerHTML="Enter mail address";
submit= false;
}
if(email != re_email) {
document.getElementById("remail-msg").innerHTML="Email address mismatch";
submit= false;
}
if(tel.match(telno)) {
document.getElementById("phone-msg").innerHTML="phone number is invalid";
submit= false;
}
if(password === " " ){
document.getElementById("pass-msg").innerHTML="Enter password";
submit= false;
}
if (password != re_password) {
document.getElementById("repass-msg").innerHTML="password mismatch" ;
submit= false;
}
if (submit== false) {
alert("enter the details");
}
else
alert("form is submitted");
}
| f1a1d99d69e009b6f7ed60543f744fff6faad934 | [
"JavaScript"
]
| 1 | JavaScript | Nagur-sheik/Assignment---3-and-4-Form-Design-and-VALIDATION | f79d42f26b53071fd3c84dd1bbae641732f4878a | 88c4d24212827fe7c1b9d9bbba615cdf718e702b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.